blob: 682f3692bac7d1d2f46db9685c2fdb69ee46112e [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
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000041static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return std::any_of(FD->param_begin(), FD->param_end(),
43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44}
45
Nick Lewycky134af912013-02-07 05:08:22 +000046/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000047static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000048CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
49 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000050 SourceLocation Loc = SourceLocation(),
51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000052 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000053 return ExprError();
54 // If FoundDecl is different from Fn (such as if one is a template
55 // and the other a specialization), make sure DiagnoseUseOfDecl is
56 // called on both.
57 // FIXME: This would be more comprehensively addressed by modifying
58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
59 // being used.
60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000061 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000062 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000063 VK_LValue, Loc, LocInfo);
64 if (HadMultipleCandidates)
65 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000066
67 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000068 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
69 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000070}
71
John McCall5c32be02010-08-24 20:38:10 +000072static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000074 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000075 bool CStyle,
76 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000077
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000078static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 QualType &ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000083static OverloadingResult
84IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85 UserDefinedConversionSequence& User,
86 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000087 bool AllowExplicit,
88 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000089
90
91static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000092CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000093 const StandardConversionSequence& SCS1,
94 const StandardConversionSequence& SCS2);
95
96static ImplicitConversionSequence::CompareKind
97CompareQualificationConversions(Sema &S,
98 const StandardConversionSequence& SCS1,
99 const StandardConversionSequence& SCS2);
100
101static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000102CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106/// GetConversionRank - Retrieve the implicit conversion rank
107/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000108ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICR_Promotion,
118 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000127 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000128 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000129 ICR_Conversion,
130 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000131 ICR_Complex_Real_Conversion,
132 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000133 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000134 ICR_Writeback_Conversion,
135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
136 // it was omitted by the patch that added
137 // ICK_Zero_Event_Conversion
138 ICR_C_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 };
140 return Rank[(int)Kind];
141}
142
143/// GetImplicitConversionName - Return the name of this kind of
144/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000145static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "No conversion",
148 "Lvalue-to-rvalue",
149 "Array-to-pointer",
150 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000151 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "Qualification",
153 "Integral promotion",
154 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000155 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 "Integral conversion",
157 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000158 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "Floating-integral conversion",
160 "Pointer conversion",
161 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000162 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000163 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000164 "Derived-to-base conversion",
165 "Vector conversion",
166 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000167 "Complex-real conversion",
168 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000169 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000170 "Writeback conversion",
171 "OpenCL Zero Event Conversion",
172 "C specific type conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000184 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000185 ReferenceBinding = false;
186 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000187 IsLvalueReference = true;
188 BindsToFunctionLvalue = false;
189 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000190 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000191 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000192 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000193}
194
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195/// getRank - Retrieve the rank of this standard conversion sequence
196/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
197/// implicit conversions.
198ImplicitConversionRank StandardConversionSequence::getRank() const {
199 ImplicitConversionRank Rank = ICR_Exact_Match;
200 if (GetConversionRank(First) > Rank)
201 Rank = GetConversionRank(First);
202 if (GetConversionRank(Second) > Rank)
203 Rank = GetConversionRank(Second);
204 if (GetConversionRank(Third) > Rank)
205 Rank = GetConversionRank(Third);
206 return Rank;
207}
208
209/// isPointerConversionToBool - Determines whether this conversion is
210/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000211/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000212/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000213bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000214 // Note that FromType has not necessarily been transformed by the
215 // array-to-pointer or function-to-pointer implicit conversions, so
216 // check for their presence as well as checking whether FromType is
217 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000218 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000219 (getFromType()->isPointerType() ||
220 getFromType()->isObjCObjectPointerType() ||
221 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000222 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
224 return true;
225
226 return false;
227}
228
Douglas Gregor5c407d92008-10-23 00:40:37 +0000229/// isPointerConversionToVoidPointer - Determines whether this
230/// conversion is a conversion of a pointer to a void pointer. This is
231/// used as part of the ranking of standard conversion sequences (C++
232/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000233bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000235isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000236 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000237 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238
239 // Note that FromType has not necessarily been transformed by the
240 // array-to-pointer implicit conversion, so check for its presence
241 // and redo the conversion to get a pointer.
242 if (First == ICK_Array_To_Pointer)
243 FromType = Context.getArrayDecayedType(FromType);
244
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247 return ToPtrType->getPointeeType()->isVoidType();
248
249 return false;
250}
251
Richard Smith66e05fe2012-01-18 05:21:49 +0000252/// Skip any implicit casts which could be either part of a narrowing conversion
253/// or after one in an implicit conversion.
254static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
256 switch (ICE->getCastKind()) {
257 case CK_NoOp:
258 case CK_IntegralCast:
259 case CK_IntegralToBoolean:
260 case CK_IntegralToFloating:
261 case CK_FloatingToIntegral:
262 case CK_FloatingToBoolean:
263 case CK_FloatingCast:
264 Converted = ICE->getSubExpr();
265 continue;
266
267 default:
268 return Converted;
269 }
270 }
271
272 return Converted;
273}
274
275/// Check if this standard conversion sequence represents a narrowing
276/// conversion, according to C++11 [dcl.init.list]p7.
277///
278/// \param Ctx The AST context.
279/// \param Converted The result of applying this standard conversion sequence.
280/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
281/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000282/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
283/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000284NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000285StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
286 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000287 APValue &ConstantValue,
288 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000289 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000290
291 // C++11 [dcl.init.list]p7:
292 // A narrowing conversion is an implicit conversion ...
293 QualType FromType = getToType(0);
294 QualType ToType = getToType(1);
295 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000296 // 'bool' is an integral type; dispatch to the right place to handle it.
297 case ICK_Boolean_Conversion:
298 if (FromType->isRealFloatingType())
299 goto FloatingIntegralConversion;
300 if (FromType->isIntegralOrUnscopedEnumerationType())
301 goto IntegralConversion;
302 // Boolean conversions can be from pointers and pointers to members
303 // [conv.bool], and those aren't considered narrowing conversions.
304 return NK_Not_Narrowing;
305
Richard Smith66e05fe2012-01-18 05:21:49 +0000306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000313 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat());
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000366 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000378 case ICK_Integral_Conversion:
379 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 assert(FromType->isIntegralOrUnscopedEnumerationType());
381 assert(ToType->isIntegralOrUnscopedEnumerationType());
382 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
383 const unsigned FromWidth = Ctx.getIntWidth(FromType);
384 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
385 const unsigned ToWidth = Ctx.getIntWidth(ToType);
386
387 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000388 (FromWidth == ToWidth && FromSigned != ToSigned) ||
389 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000390 // Not all values of FromType can be represented in ToType.
391 llvm::APSInt InitializerValue;
392 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000393 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
394 // Such conversions on variables are always narrowing.
395 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000396 }
397 bool Narrowing = false;
398 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000399 // Negative -> unsigned is narrowing. Otherwise, more bits is never
400 // narrowing.
401 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000402 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000403 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000404 // Add a bit to the InitializerValue so we don't have to worry about
405 // signed vs. unsigned comparisons.
406 InitializerValue = InitializerValue.extend(
407 InitializerValue.getBitWidth() + 1);
408 // Convert the initializer to and from the target width and signed-ness.
409 llvm::APSInt ConvertedValue = InitializerValue;
410 ConvertedValue = ConvertedValue.trunc(ToWidth);
411 ConvertedValue.setIsSigned(ToSigned);
412 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
413 ConvertedValue.setIsSigned(InitializerValue.isSigned());
414 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000415 if (ConvertedValue != InitializerValue)
416 Narrowing = true;
417 }
418 if (Narrowing) {
419 ConstantType = Initializer->getType();
420 ConstantValue = APValue(InitializerValue);
421 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000422 }
423 }
424 return NK_Not_Narrowing;
425 }
426
427 default:
428 // Other kinds of conversions are not narrowings.
429 return NK_Not_Narrowing;
430 }
431}
432
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000433/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000434/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000435void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000436 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000437 bool PrintedSomething = false;
438 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000440 PrintedSomething = true;
441 }
442
443 if (Second != ICK_Identity) {
444 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000445 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000446 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448
449 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000451 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000452 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000453 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000455 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000456 PrintedSomething = true;
457 }
458
459 if (Third != ICK_Identity) {
460 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000464 PrintedSomething = true;
465 }
466
467 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 }
470}
471
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000472/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000474void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000475 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000477 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000479 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000480 if (ConversionFunction)
481 OS << '\'' << *ConversionFunction << '\'';
482 else
483 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000486 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 }
488}
489
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000490/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000493 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000494 if (isStdInitializerListElement())
495 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 switch (ConversionKind) {
497 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000499 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
501 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000502 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 break;
505 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 break;
John McCall0d1da222010-01-12 00:44:57 +0000508 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000510 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000512 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 break;
514 }
515
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000516 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517}
518
John McCall0d1da222010-01-12 00:44:57 +0000519void AmbiguousConversionSequence::construct() {
520 new (&conversions()) ConversionSet();
521}
522
523void AmbiguousConversionSequence::destruct() {
524 conversions().~ConversionSet();
525}
526
527void
528AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
529 FromTypePtr = O.FromTypePtr;
530 ToTypePtr = O.ToTypePtr;
531 new (&conversions()) ConversionSet(O.conversions());
532}
533
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000534namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000535 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000536 // template argument information.
537 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000538 TemplateArgument FirstArg;
539 TemplateArgument SecondArg;
540 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000541 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000542 // template parameter and template argument information.
543 struct DFIParamWithArguments : DFIArguments {
544 TemplateParameter Param;
545 };
Richard Smith9b534542015-12-31 02:02:54 +0000546 // Structure used by DeductionFailureInfo to store template argument
547 // information and the index of the problematic call argument.
548 struct DFIDeducedMismatchArgs : DFIArguments {
549 TemplateArgumentList *TemplateArgs;
550 unsigned CallArgIndex;
551 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000552}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554/// \brief Convert from Sema's representation of template deduction information
555/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000556DeductionFailureInfo
557clang::MakeDeductionFailureInfo(ASTContext &Context,
558 Sema::TemplateDeductionResult TDK,
559 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000560 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000562 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563 switch (TDK) {
564 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000565 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000567 case Sema::TDK_TooManyArguments:
568 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000569 case Sema::TDK_MiscellaneousDeductionFailure:
570 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000571 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000573 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000574 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000575 Result.Data = Info.Param.getOpaqueValue();
576 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577
Richard Smith9b534542015-12-31 02:02:54 +0000578 case Sema::TDK_DeducedMismatch: {
579 // FIXME: Should allocate from normal heap so that we can free this later.
580 auto *Saved = new (Context) DFIDeducedMismatchArgs;
581 Saved->FirstArg = Info.FirstArg;
582 Saved->SecondArg = Info.SecondArg;
583 Saved->TemplateArgs = Info.take();
584 Saved->CallArgIndex = Info.CallArgIndex;
585 Result.Data = Saved;
586 break;
587 }
588
Richard Smith44ecdbd2013-01-31 05:19:49 +0000589 case Sema::TDK_NonDeducedMismatch: {
590 // FIXME: Should allocate from normal heap so that we can free this later.
591 DFIArguments *Saved = new (Context) DFIArguments;
592 Saved->FirstArg = Info.FirstArg;
593 Saved->SecondArg = Info.SecondArg;
594 Result.Data = Saved;
595 break;
596 }
597
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000598 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000599 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000600 // FIXME: Should allocate from normal heap so that we can free this later.
601 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 Saved->Param = Info.Param;
603 Saved->FirstArg = Info.FirstArg;
604 Saved->SecondArg = Info.SecondArg;
605 Result.Data = Saved;
606 break;
607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000610 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000611 if (Info.hasSFINAEDiagnostic()) {
612 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
613 SourceLocation(), PartialDiagnostic::NullDiagnostic());
614 Info.takeSFINAEDiagnostic(*Diag);
615 Result.HasDiagnostic = true;
616 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000617 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000619 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000620 Result.Data = Info.Expression;
621 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000624 return Result;
625}
John McCall0d1da222010-01-12 00:44:57 +0000626
Larisse Voufo98b20f12013-07-19 23:00:19 +0000627void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
629 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000630 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000631 case Sema::TDK_InstantiationDepth:
632 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000633 case Sema::TDK_TooManyArguments:
634 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000635 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000636 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000640 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000641 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000642 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000643 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000644 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000645 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000646
647 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000648 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000649 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000650 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
651 Diag->~PartialDiagnosticAt();
652 HasDiagnostic = false;
653 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000654 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655
Douglas Gregor461761d2010-05-08 18:20:53 +0000656 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000657 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 break;
659 }
660}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
Larisse Voufo98b20f12013-07-19 23:00:19 +0000662PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000663 if (HasDiagnostic)
664 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000665 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000666}
667
Larisse Voufo98b20f12013-07-19 23:00:19 +0000668TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000671 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000673 case Sema::TDK_TooManyArguments:
674 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000675 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000676 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000677 case Sema::TDK_NonDeducedMismatch:
678 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000679 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000681 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000682 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000684
685 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000686 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000687 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000689 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000690 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000691 break;
692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 return TemplateParameter();
695}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696
Larisse Voufo98b20f12013-07-19 23:00:19 +0000697TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000698 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000699 case Sema::TDK_Success:
700 case Sema::TDK_Invalid:
701 case Sema::TDK_InstantiationDepth:
702 case Sema::TDK_TooManyArguments:
703 case Sema::TDK_TooFewArguments:
704 case Sema::TDK_Incomplete:
705 case Sema::TDK_InvalidExplicitArguments:
706 case Sema::TDK_Inconsistent:
707 case Sema::TDK_Underqualified:
708 case Sema::TDK_NonDeducedMismatch:
709 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000710 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000711
Richard Smith9b534542015-12-31 02:02:54 +0000712 case Sema::TDK_DeducedMismatch:
713 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
714
Richard Smith44ecdbd2013-01-31 05:19:49 +0000715 case Sema::TDK_SubstitutionFailure:
716 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 // Unhandled
719 case Sema::TDK_MiscellaneousDeductionFailure:
720 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000721 }
722
Craig Topperc3ec1492014-05-26 06:22:03 +0000723 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000724}
725
Larisse Voufo98b20f12013-07-19 23:00:19 +0000726const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000727 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
728 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000729 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000730 case Sema::TDK_InstantiationDepth:
731 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000732 case Sema::TDK_TooManyArguments:
733 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000734 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000735 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000736 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000737 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000740 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000741 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000742 case Sema::TDK_NonDeducedMismatch:
743 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000744
Douglas Gregor461761d2010-05-08 18:20:53 +0000745 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000746 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000747 break;
748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749
Craig Topperc3ec1492014-05-26 06:22:03 +0000750 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000751}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752
Larisse Voufo98b20f12013-07-19 23:00:19 +0000753const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000754 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
755 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000756 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000757 case Sema::TDK_InstantiationDepth:
758 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000759 case Sema::TDK_TooManyArguments:
760 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000761 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000762 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000763 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000764 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000765
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000767 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000768 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000769 case Sema::TDK_NonDeducedMismatch:
770 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000771
Douglas Gregor461761d2010-05-08 18:20:53 +0000772 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000773 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000774 break;
775 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000776
Craig Topperc3ec1492014-05-26 06:22:03 +0000777 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000778}
779
Larisse Voufo98b20f12013-07-19 23:00:19 +0000780Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000781 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
782 Sema::TDK_FailedOverloadResolution)
783 return static_cast<Expr*>(Data);
784
Craig Topperc3ec1492014-05-26 06:22:03 +0000785 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000786}
787
Richard Smith9b534542015-12-31 02:02:54 +0000788llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
789 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
790 Sema::TDK_DeducedMismatch)
791 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
792
793 return llvm::None;
794}
795
Benjamin Kramer97e59492012-10-09 15:52:25 +0000796void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000797 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000798 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
799 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000800 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
801 i->DeductionFailure.Destroy();
802 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000803}
804
805void OverloadCandidateSet::clear() {
806 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000807 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000808 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000809 Functions.clear();
810}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
John McCall4124c492011-10-17 18:40:02 +0000812namespace {
813 class UnbridgedCastsSet {
814 struct Entry {
815 Expr **Addr;
816 Expr *Saved;
817 };
818 SmallVector<Entry, 2> Entries;
819
820 public:
821 void save(Sema &S, Expr *&E) {
822 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
823 Entry entry = { &E, E };
824 Entries.push_back(entry);
825 E = S.stripARCUnbridgedCast(E);
826 }
827
828 void restore() {
829 for (SmallVectorImpl<Entry>::iterator
830 i = Entries.begin(), e = Entries.end(); i != e; ++i)
831 *i->Addr = i->Saved;
832 }
833 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000834}
John McCall4124c492011-10-17 18:40:02 +0000835
836/// checkPlaceholderForOverload - Do any interesting placeholder-like
837/// preprocessing on the given expression.
838///
839/// \param unbridgedCasts a collection to which to add unbridged casts;
840/// without this, they will be immediately diagnosed as errors
841///
842/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000843static bool
844checkPlaceholderForOverload(Sema &S, Expr *&E,
845 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000846 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
847 // We can't handle overloaded expressions here because overload
848 // resolution might reasonably tweak them.
849 if (placeholder->getKind() == BuiltinType::Overload) return false;
850
851 // If the context potentially accepts unbridged ARC casts, strip
852 // the unbridged cast and add it to the collection for later restoration.
853 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
854 unbridgedCasts) {
855 unbridgedCasts->save(S, E);
856 return false;
857 }
858
859 // Go ahead and check everything else.
860 ExprResult result = S.CheckPlaceholderExpr(E);
861 if (result.isInvalid())
862 return true;
863
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000864 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000865 return false;
866 }
867
868 // Nothing to do.
869 return false;
870}
871
872/// checkArgPlaceholdersForOverload - Check a set of call operands for
873/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000874static bool checkArgPlaceholdersForOverload(Sema &S,
875 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000876 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000877 for (unsigned i = 0, e = Args.size(); i != e; ++i)
878 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000879 return true;
880
881 return false;
882}
883
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000884// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000885// overload of the declarations in Old. This routine returns false if
886// New and Old cannot be overloaded, e.g., if New has the same
887// signature as some function in Old (C++ 1.3.10) or if the Old
888// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000889// it does return false, MatchedDecl will point to the decl that New
890// cannot be overloaded with. This decl may be a UsingShadowDecl on
891// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000892//
893// Example: Given the following input:
894//
895// void f(int, float); // #1
896// void f(int, int); // #2
897// int f(int, int); // #3
898//
899// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000900// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000901//
John McCall3d988d92009-12-02 08:47:38 +0000902// When we process #2, Old contains only the FunctionDecl for #1. By
903// comparing the parameter types, we see that #1 and #2 are overloaded
904// (since they have different signatures), so this routine returns
905// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000906//
John McCall3d988d92009-12-02 08:47:38 +0000907// When we process #3, Old is an overload set containing #1 and #2. We
908// compare the signatures of #3 to #1 (they're overloaded, so we do
909// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
910// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911// signature), IsOverload returns false and MatchedDecl will be set to
912// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000913//
914// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
915// into a class by a using declaration. The rules for whether to hide
916// shadow declarations ignore some properties which otherwise figure
917// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000918Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000919Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
920 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000921 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000922 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000923 NamedDecl *OldD = *I;
924
925 bool OldIsUsingDecl = false;
926 if (isa<UsingShadowDecl>(OldD)) {
927 OldIsUsingDecl = true;
928
929 // We can always introduce two using declarations into the same
930 // context, even if they have identical signatures.
931 if (NewIsUsingDecl) continue;
932
933 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
934 }
935
Richard Smithf091e122015-09-15 01:28:55 +0000936 // A using-declaration does not conflict with another declaration
937 // if one of them is hidden.
938 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
939 continue;
940
John McCalle9cccd82010-06-16 08:42:20 +0000941 // If either declaration was introduced by a using declaration,
942 // we'll need to use slightly different rules for matching.
943 // Essentially, these rules are the normal rules, except that
944 // function templates hide function templates with different
945 // return types or template parameter lists.
946 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000947 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
948 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000949
Alp Tokera2794f92014-01-22 07:29:52 +0000950 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000951 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
952 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
953 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
954 continue;
955 }
956
Alp Tokera2794f92014-01-22 07:29:52 +0000957 if (!isa<FunctionTemplateDecl>(OldD) &&
958 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000959 continue;
960
John McCalldaa3d6b2009-12-09 03:35:25 +0000961 Match = *I;
962 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000963 }
John McCalla8987a2942010-11-10 03:01:53 +0000964 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000965 // We can overload with these, which can show up when doing
966 // redeclaration checks for UsingDecls.
967 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000968 } else if (isa<TagDecl>(OldD)) {
969 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000970 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
971 // Optimistically assume that an unresolved using decl will
972 // overload; if it doesn't, we'll have to diagnose during
973 // template instantiation.
974 } else {
John McCall1f82f242009-11-18 22:49:29 +0000975 // (C++ 13p1):
976 // Only function declarations can be overloaded; object and type
977 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000978 Match = *I;
979 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000980 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000981 }
John McCall1f82f242009-11-18 22:49:29 +0000982
John McCalldaa3d6b2009-12-09 03:35:25 +0000983 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000984}
985
Richard Smithac974a32013-06-30 09:48:50 +0000986bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
987 bool UseUsingDeclRules) {
988 // C++ [basic.start.main]p2: This function shall not be overloaded.
989 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000990 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000991
David Majnemerc729b0b2013-09-16 22:44:20 +0000992 // MSVCRT user defined entry points cannot be overloaded.
993 if (New->isMSVCRTEntryPoint())
994 return false;
995
John McCall1f82f242009-11-18 22:49:29 +0000996 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
997 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
998
999 // C++ [temp.fct]p2:
1000 // A function template can be overloaded with other function templates
1001 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001002 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001003 return true;
1004
1005 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001006 QualType OldQType = Context.getCanonicalType(Old->getType());
1007 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001008
1009 // Compare the signatures (C++ 1.3.10) of the two functions to
1010 // determine whether they are overloads. If we find any mismatch
1011 // in the signature, they are overloads.
1012
1013 // If either of these functions is a K&R-style function (no
1014 // prototype), then we consider them to have matching signatures.
1015 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1016 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1017 return false;
1018
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001019 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1020 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001021
1022 // The signature of a function includes the types of its
1023 // parameters (C++ 1.3.10), which includes the presence or absence
1024 // of the ellipsis; see C++ DR 357).
1025 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001026 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001027 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001028 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001029 return true;
1030
1031 // C++ [temp.over.link]p4:
1032 // The signature of a function template consists of its function
1033 // signature, its return type and its template parameter list. The names
1034 // of the template parameters are significant only for establishing the
1035 // relationship between the template parameters and the rest of the
1036 // signature.
1037 //
1038 // We check the return type and template parameter lists for function
1039 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001040 //
1041 // However, we don't consider either of these when deciding whether
1042 // a member introduced by a shadow declaration is hidden.
1043 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001044 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1045 OldTemplate->getTemplateParameters(),
1046 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001047 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001048 return true;
1049
1050 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001051 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001052 //
1053 // As part of this, also check whether one of the member functions
1054 // is static, in which case they are not overloads (C++
1055 // 13.1p2). While not part of the definition of the signature,
1056 // this check is important to determine whether these functions
1057 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001058 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1059 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001060 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001061 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1062 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1063 if (!UseUsingDeclRules &&
1064 (OldMethod->getRefQualifier() == RQ_None ||
1065 NewMethod->getRefQualifier() == RQ_None)) {
1066 // C++0x [over.load]p2:
1067 // - Member function declarations with the same name and the same
1068 // parameter-type-list as well as member function template
1069 // declarations with the same name, the same parameter-type-list, and
1070 // the same template parameter lists cannot be overloaded if any of
1071 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001072 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001073 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001074 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001075 }
1076 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078
Richard Smith574f4f62013-01-14 05:37:29 +00001079 // We may not have applied the implicit const for a constexpr member
1080 // function yet (because we haven't yet resolved whether this is a static
1081 // or non-static member function). Add it now, on the assumption that this
1082 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001083 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001084 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001085 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001086 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001087 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001088
1089 // We do not allow overloading based off of '__restrict'.
1090 OldQuals &= ~Qualifiers::Restrict;
1091 NewQuals &= ~Qualifiers::Restrict;
1092 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001093 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001095
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001096 // Though pass_object_size is placed on parameters and takes an argument, we
1097 // consider it to be a function-level modifier for the sake of function
1098 // identity. Either the function has one or more parameters with
1099 // pass_object_size or it doesn't.
1100 if (functionHasPassObjectSizeParams(New) !=
1101 functionHasPassObjectSizeParams(Old))
1102 return true;
1103
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001104 // enable_if attributes are an order-sensitive part of the signature.
1105 for (specific_attr_iterator<EnableIfAttr>
1106 NewI = New->specific_attr_begin<EnableIfAttr>(),
1107 NewE = New->specific_attr_end<EnableIfAttr>(),
1108 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1109 OldE = Old->specific_attr_end<EnableIfAttr>();
1110 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1111 if (NewI == NewE || OldI == OldE)
1112 return true;
1113 llvm::FoldingSetNodeID NewID, OldID;
1114 NewI->getCond()->Profile(NewID, Context, true);
1115 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001116 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001117 return true;
1118 }
1119
Artem Belevich94a55e82015-09-22 17:22:59 +00001120 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1121 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1122 OldTarget = IdentifyCUDATarget(Old);
1123 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1124 return false;
1125
1126 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1127
1128 // Don't allow mixing of HD with other kinds. This guarantees that
1129 // we have only one viable function with this signature on any
1130 // side of CUDA compilation .
1131 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1132 return false;
1133
1134 // Allow overloading of functions with same signature, but
1135 // different CUDA target attributes.
1136 return NewTarget != OldTarget;
1137 }
1138
John McCall1f82f242009-11-18 22:49:29 +00001139 // The signatures match; this is not an overload.
1140 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001141}
1142
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001143/// \brief Checks availability of the function depending on the current
1144/// function context. Inside an unavailable function, unavailability is ignored.
1145///
1146/// \returns true if \arg FD is unavailable and current context is inside
1147/// an available function, false otherwise.
1148bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1149 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1150}
1151
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001152/// \brief Tries a user-defined conversion from From to ToType.
1153///
1154/// Produces an implicit conversion sequence for when a standard conversion
1155/// is not an option. See TryImplicitConversion for more information.
1156static ImplicitConversionSequence
1157TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1158 bool SuppressUserConversions,
1159 bool AllowExplicit,
1160 bool InOverloadResolution,
1161 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001162 bool AllowObjCWritebackConversion,
1163 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001164 ImplicitConversionSequence ICS;
1165
1166 if (SuppressUserConversions) {
1167 // We're not in the case above, so there is no conversion that
1168 // we can perform.
1169 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1170 return ICS;
1171 }
1172
1173 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001174 OverloadCandidateSet Conversions(From->getExprLoc(),
1175 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001176 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1177 Conversions, AllowExplicit,
1178 AllowObjCConversionOnExplicit)) {
1179 case OR_Success:
1180 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001181 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001182 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001183 // C++ [over.ics.user]p4:
1184 // A conversion of an expression of class type to the same class
1185 // type is given Exact Match rank, and a conversion of an
1186 // expression of class type to a base class of that type is
1187 // given Conversion rank, in spite of the fact that a copy
1188 // constructor (i.e., a user-defined conversion function) is
1189 // called for those cases.
1190 if (CXXConstructorDecl *Constructor
1191 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1192 QualType FromCanon
1193 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1194 QualType ToCanon
1195 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1196 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001197 (FromCanon == ToCanon ||
1198 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001199 // Turn this into a "standard" conversion sequence, so that it
1200 // gets ranked with standard conversion sequences.
1201 ICS.setStandard();
1202 ICS.Standard.setAsIdentityConversion();
1203 ICS.Standard.setFromType(From->getType());
1204 ICS.Standard.setAllToTypes(ToType);
1205 ICS.Standard.CopyConstructor = Constructor;
1206 if (ToCanon != FromCanon)
1207 ICS.Standard.Second = ICK_Derived_To_Base;
1208 }
1209 }
Richard Smith48372b62015-01-27 03:30:40 +00001210 break;
1211
1212 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001213 ICS.setAmbiguous();
1214 ICS.Ambiguous.setFromType(From->getType());
1215 ICS.Ambiguous.setToType(ToType);
1216 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1217 Cand != Conversions.end(); ++Cand)
1218 if (Cand->Viable)
1219 ICS.Ambiguous.addConversion(Cand->Function);
1220 break;
Richard Smith48372b62015-01-27 03:30:40 +00001221
1222 // Fall through.
1223 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001224 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001225 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001226 }
1227
1228 return ICS;
1229}
1230
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001231/// TryImplicitConversion - Attempt to perform an implicit conversion
1232/// from the given expression (Expr) to the given type (ToType). This
1233/// function returns an implicit conversion sequence that can be used
1234/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235///
1236/// void f(float f);
1237/// void g(int i) { f(i); }
1238///
1239/// this routine would produce an implicit conversion sequence to
1240/// describe the initialization of f from i, which will be a standard
1241/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1242/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1243//
1244/// Note that this routine only determines how the conversion can be
1245/// performed; it does not actually perform the conversion. As such,
1246/// it will not produce any diagnostics if no conversion is available,
1247/// but will instead return an implicit conversion sequence of kind
1248/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001249///
1250/// If @p SuppressUserConversions, then user-defined conversions are
1251/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001252/// If @p AllowExplicit, then explicit user-defined conversions are
1253/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001254///
1255/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1256/// writeback conversion, which allows __autoreleasing id* parameters to
1257/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001258static ImplicitConversionSequence
1259TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1260 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001261 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001262 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001263 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001264 bool AllowObjCWritebackConversion,
1265 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001267 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001268 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001269 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001270 return ICS;
1271 }
1272
David Blaikiebbafb8a2012-03-11 07:00:24 +00001273 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001274 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001275 return ICS;
1276 }
1277
Douglas Gregor836a7e82010-08-11 02:15:33 +00001278 // C++ [over.ics.user]p4:
1279 // A conversion of an expression of class type to the same class
1280 // type is given Exact Match rank, and a conversion of an
1281 // expression of class type to a base class of that type is
1282 // given Conversion rank, in spite of the fact that a copy/move
1283 // constructor (i.e., a user-defined conversion function) is
1284 // called for those cases.
1285 QualType FromType = From->getType();
1286 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001287 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001288 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001289 ICS.setStandard();
1290 ICS.Standard.setAsIdentityConversion();
1291 ICS.Standard.setFromType(FromType);
1292 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001293
Douglas Gregor5ab11652010-04-17 22:01:05 +00001294 // We don't actually check at this point whether there is a valid
1295 // copy/move constructor, since overloading just assumes that it
1296 // exists. When we actually perform initialization, we'll find the
1297 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001298 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001299
Douglas Gregor5ab11652010-04-17 22:01:05 +00001300 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001301 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001302 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303
Douglas Gregor836a7e82010-08-11 02:15:33 +00001304 return ICS;
1305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001306
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001307 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1308 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001309 AllowObjCWritebackConversion,
1310 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001311}
1312
John McCall31168b02011-06-15 23:02:42 +00001313ImplicitConversionSequence
1314Sema::TryImplicitConversion(Expr *From, QualType ToType,
1315 bool SuppressUserConversions,
1316 bool AllowExplicit,
1317 bool InOverloadResolution,
1318 bool CStyle,
1319 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001320 return ::TryImplicitConversion(*this, From, ToType,
1321 SuppressUserConversions, AllowExplicit,
1322 InOverloadResolution, CStyle,
1323 AllowObjCWritebackConversion,
1324 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001325}
1326
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001327/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001328/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001329/// converted expression. Flavor is the kind of conversion we're
1330/// performing, used in the error message. If @p AllowExplicit,
1331/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001332ExprResult
1333Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001334 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001335 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001336 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001337}
1338
John Wiegley01296292011-04-08 18:41:53 +00001339ExprResult
1340Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001341 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001342 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001343 if (checkPlaceholderForOverload(*this, From))
1344 return ExprError();
1345
John McCall31168b02011-06-15 23:02:42 +00001346 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1347 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001348 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001349 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001350 if (getLangOpts().ObjC1)
1351 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1352 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001353 ICS = ::TryImplicitConversion(*this, From, ToType,
1354 /*SuppressUserConversions=*/false,
1355 AllowExplicit,
1356 /*InOverloadResolution=*/false,
1357 /*CStyle=*/false,
1358 AllowObjCWritebackConversion,
1359 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001360 return PerformImplicitConversion(From, ToType, ICS, Action);
1361}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001362
1363/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001364/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001365bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1366 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001367 if (Context.hasSameUnqualifiedType(FromType, ToType))
1368 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001369
John McCall991eb4b2010-12-21 00:44:39 +00001370 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1371 // where F adds one of the following at most once:
1372 // - a pointer
1373 // - a member pointer
1374 // - a block pointer
1375 CanQualType CanTo = Context.getCanonicalType(ToType);
1376 CanQualType CanFrom = Context.getCanonicalType(FromType);
1377 Type::TypeClass TyClass = CanTo->getTypeClass();
1378 if (TyClass != CanFrom->getTypeClass()) return false;
1379 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1380 if (TyClass == Type::Pointer) {
1381 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1382 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1383 } else if (TyClass == Type::BlockPointer) {
1384 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1385 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1386 } else if (TyClass == Type::MemberPointer) {
1387 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1388 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1389 } else {
1390 return false;
1391 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001392
John McCall991eb4b2010-12-21 00:44:39 +00001393 TyClass = CanTo->getTypeClass();
1394 if (TyClass != CanFrom->getTypeClass()) return false;
1395 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1396 return false;
1397 }
1398
1399 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1400 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1401 if (!EInfo.getNoReturn()) return false;
1402
1403 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1404 assert(QualType(FromFn, 0).isCanonical());
1405 if (QualType(FromFn, 0) != CanTo) return false;
1406
1407 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001408 return true;
1409}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410
Douglas Gregor46188682010-05-18 22:42:18 +00001411/// \brief Determine whether the conversion from FromType to ToType is a valid
1412/// vector conversion.
1413///
1414/// \param ICK Will be set to the vector conversion kind, if this is a vector
1415/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001416static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001417 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001418 // We need at least one of these types to be a vector type to have a vector
1419 // conversion.
1420 if (!ToType->isVectorType() && !FromType->isVectorType())
1421 return false;
1422
1423 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001424 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001425 return false;
1426
1427 // There are no conversions between extended vector types, only identity.
1428 if (ToType->isExtVectorType()) {
1429 // There are no conversions between extended vector types other than the
1430 // identity conversion.
1431 if (FromType->isExtVectorType())
1432 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433
Douglas Gregor46188682010-05-18 22:42:18 +00001434 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001435 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001436 ICK = ICK_Vector_Splat;
1437 return true;
1438 }
1439 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001440
1441 // We can perform the conversion between vector types in the following cases:
1442 // 1)vector types are equivalent AltiVec and GCC vector types
1443 // 2)lax vector conversions are permitted and the vector types are of the
1444 // same size
1445 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001446 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1447 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001448 ICK = ICK_Vector_Conversion;
1449 return true;
1450 }
Douglas Gregor46188682010-05-18 22:42:18 +00001451 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001452
Douglas Gregor46188682010-05-18 22:42:18 +00001453 return false;
1454}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001455
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001456static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1457 bool InOverloadResolution,
1458 StandardConversionSequence &SCS,
1459 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001460
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001461/// IsStandardConversion - Determines whether there is a standard
1462/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1463/// expression From to the type ToType. Standard conversion sequences
1464/// only consider non-class types; for conversions that involve class
1465/// types, use TryImplicitConversion. If a conversion exists, SCS will
1466/// contain the standard conversion sequence required to perform this
1467/// conversion and this routine will return true. Otherwise, this
1468/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001469static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1470 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001471 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001472 bool CStyle,
1473 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001474 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001476 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001477 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001478 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001479 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001480 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001481
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001482 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001483 // abort early. When overloading in C, however, we do permit them.
1484 if (S.getLangOpts().CPlusPlus &&
1485 (FromType->isRecordType() || ToType->isRecordType()))
1486 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001487
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488 // The first conversion can be an lvalue-to-rvalue conversion,
1489 // array-to-pointer conversion, or function-to-pointer conversion
1490 // (C++ 4p1).
1491
John McCall5c32be02010-08-24 20:38:10 +00001492 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001493 DeclAccessPair AccessPair;
1494 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001496 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001497 // We were able to resolve the address of the overloaded function,
1498 // so we can convert to the type of that function.
1499 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001500 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001501
1502 // we can sometimes resolve &foo<int> regardless of ToType, so check
1503 // if the type matches (identity) or we are converting to bool
1504 if (!S.Context.hasSameUnqualifiedType(
1505 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1506 QualType resultTy;
1507 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001508 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001509 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1510 // otherwise, only a boolean conversion is standard
1511 if (!ToType->isBooleanType())
1512 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001514
Chandler Carruthffce2452011-03-29 08:08:18 +00001515 // Check if the "from" expression is taking the address of an overloaded
1516 // function and recompute the FromType accordingly. Take advantage of the
1517 // fact that non-static member functions *must* have such an address-of
1518 // expression.
1519 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1520 if (Method && !Method->isStatic()) {
1521 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1522 "Non-unary operator on non-static member address");
1523 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1524 == UO_AddrOf &&
1525 "Non-address-of operator on non-static member address");
1526 const Type *ClassType
1527 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1528 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001529 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1530 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1531 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001532 "Non-address-of operator for overloaded function expression");
1533 FromType = S.Context.getPointerType(FromType);
1534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535
Douglas Gregor980fb162010-04-29 18:24:40 +00001536 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001537 assert(S.Context.hasSameType(
1538 FromType,
1539 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001540 } else {
1541 return false;
1542 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001543 }
John McCall154a2fd2011-08-30 00:57:29 +00001544 // Lvalue-to-rvalue conversion (C++11 4.1):
1545 // A glvalue (3.10) of a non-function, non-array type T can
1546 // be converted to a prvalue.
1547 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001548 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001549 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001550 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001551 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001552
Douglas Gregorc79862f2012-04-12 17:51:55 +00001553 // C11 6.3.2.1p2:
1554 // ... if the lvalue has atomic type, the value has the non-atomic version
1555 // of the type of the lvalue ...
1556 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1557 FromType = Atomic->getValueType();
1558
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559 // If T is a non-class type, the type of the rvalue is the
1560 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001561 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1562 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001563 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001564 } else if (FromType->isArrayType()) {
1565 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567
1568 // An lvalue or rvalue of type "array of N T" or "array of unknown
1569 // bound of T" can be converted to an rvalue of type "pointer to
1570 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001571 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572
John McCall5c32be02010-08-24 20:38:10 +00001573 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001574 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001575 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576
1577 // For the purpose of ranking in overload resolution
1578 // (13.3.3.1.1), this conversion is considered an
1579 // array-to-pointer conversion followed by a qualification
1580 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001581 SCS.Second = ICK_Identity;
1582 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001583 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001584 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001585 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586 }
John McCall086a4642010-11-24 05:12:34 +00001587 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001588 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001589 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001591 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1592 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1593 if (!S.checkAddressOfFunctionIsAvailable(FD))
1594 return false;
1595
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001596 // An lvalue of function type T can be converted to an rvalue of
1597 // type "pointer to T." The result is a pointer to the
1598 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001599 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001600 } else {
1601 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001602 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001603 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001604 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001605
1606 // The second conversion can be an integral promotion, floating
1607 // point promotion, integral conversion, floating point conversion,
1608 // floating-integral conversion, pointer conversion,
1609 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001610 // For overloading in C, this can also be a "compatible-type"
1611 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001612 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001613 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001614 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615 // The unqualified versions of the types are the same: there's no
1616 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001617 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001618 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001619 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001620 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001621 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001622 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001623 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001624 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001625 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001626 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001627 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001628 SCS.Second = ICK_Complex_Promotion;
1629 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001630 } else if (ToType->isBooleanType() &&
1631 (FromType->isArithmeticType() ||
1632 FromType->isAnyPointerType() ||
1633 FromType->isBlockPointerType() ||
1634 FromType->isMemberPointerType() ||
1635 FromType->isNullPtrType())) {
1636 // Boolean conversions (C++ 4.12).
1637 SCS.Second = ICK_Boolean_Conversion;
1638 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001639 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001640 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001641 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001642 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001643 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001644 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001645 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001646 SCS.Second = ICK_Complex_Conversion;
1647 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001648 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1649 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001650 // Complex-real conversions (C99 6.3.1.7)
1651 SCS.Second = ICK_Complex_Real;
1652 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001653 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001654 // Floating point conversions (C++ 4.8).
1655 SCS.Second = ICK_Floating_Conversion;
1656 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001657 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001658 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001659 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001660 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001661 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001662 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001664 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001665 SCS.Second = ICK_Block_Pointer_Conversion;
1666 } else if (AllowObjCWritebackConversion &&
1667 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1668 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001669 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1670 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001671 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001673 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001674 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001676 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001677 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001678 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001679 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001680 SCS.Second = SecondICK;
1681 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001682 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001683 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001684 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001685 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001686 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001687 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001688 // Treat a conversion that strips "noreturn" as an identity conversion.
1689 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001690 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1691 InOverloadResolution,
1692 SCS, CStyle)) {
1693 SCS.Second = ICK_TransparentUnionConversion;
1694 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001695 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1696 CStyle)) {
1697 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001698 // appropriately.
1699 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001700 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001701 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001702 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001703 SCS.Second = ICK_Zero_Event_Conversion;
1704 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001705 } else {
1706 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001707 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001709 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001711 QualType CanonFrom;
1712 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001714 bool ObjCLifetimeConversion;
1715 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1716 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001717 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001718 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001719 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001720 CanonFrom = S.Context.getCanonicalType(FromType);
1721 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001722 } else {
1723 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001724 SCS.Third = ICK_Identity;
1725
Mike Stump11289f42009-09-09 15:08:12 +00001726 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001727 // [...] Any difference in top-level cv-qualification is
1728 // subsumed by the initialization itself and does not constitute
1729 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001730 CanonFrom = S.Context.getCanonicalType(FromType);
1731 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001732 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001733 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001734 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001735 FromType = ToType;
1736 CanonFrom = CanonTo;
1737 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001738 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001739 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001740
George Burgess IV45461812015-10-11 20:13:20 +00001741 if (CanonFrom == CanonTo)
1742 return true;
1743
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001744 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001745 // this is a bad conversion sequence, unless we're resolving an overload in C.
1746 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001747 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748
George Burgess IV45461812015-10-11 20:13:20 +00001749 ExprResult ER = ExprResult{From};
1750 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1751 /*Diagnose=*/false,
1752 /*DiagnoseCFAudited=*/false,
1753 /*ConvertRHS=*/false);
1754 if (Conv != Sema::Compatible)
1755 return false;
1756
1757 SCS.setAllToTypes(ToType);
1758 // We need to set all three because we want this conversion to rank terribly,
1759 // and we don't know what conversions it may overlap with.
1760 SCS.First = ICK_C_Only_Conversion;
1761 SCS.Second = ICK_C_Only_Conversion;
1762 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001763 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001764}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001765
1766static bool
1767IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1768 QualType &ToType,
1769 bool InOverloadResolution,
1770 StandardConversionSequence &SCS,
1771 bool CStyle) {
1772
1773 const RecordType *UT = ToType->getAsUnionType();
1774 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1775 return false;
1776 // The field to initialize within the transparent union.
1777 RecordDecl *UD = UT->getDecl();
1778 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001779 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001780 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1781 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001782 ToType = it->getType();
1783 return true;
1784 }
1785 }
1786 return false;
1787}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001788
1789/// IsIntegralPromotion - Determines whether the conversion from the
1790/// expression From (whose potentially-adjusted type is FromType) to
1791/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1792/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001793bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001794 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001795 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001796 if (!To) {
1797 return false;
1798 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001799
1800 // An rvalue of type char, signed char, unsigned char, short int, or
1801 // unsigned short int can be converted to an rvalue of type int if
1802 // int can represent all the values of the source type; otherwise,
1803 // the source rvalue can be converted to an rvalue of type unsigned
1804 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001805 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1806 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001807 if (// We can promote any signed, promotable integer type to an int
1808 (FromType->isSignedIntegerType() ||
1809 // We can promote any unsigned integer type whose size is
1810 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001811 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001812 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001813 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001814 }
1815
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001816 return To->getKind() == BuiltinType::UInt;
1817 }
1818
Richard Smithb9c5a602012-09-13 21:18:54 +00001819 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820 // A prvalue of an unscoped enumeration type whose underlying type is not
1821 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1822 // following types that can represent all the values of the enumeration
1823 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1824 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001825 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001827 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001828 // with lowest integer conversion rank (4.13) greater than the rank of long
1829 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001830 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001831 // C++11 [conv.prom]p4:
1832 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1833 // can be converted to a prvalue of its underlying type. Moreover, if
1834 // integral promotion can be applied to its underlying type, a prvalue of an
1835 // unscoped enumeration type whose underlying type is fixed can also be
1836 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001837 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1838 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1839 // provided for a scoped enumeration.
1840 if (FromEnumType->getDecl()->isScoped())
1841 return false;
1842
Richard Smithb9c5a602012-09-13 21:18:54 +00001843 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001844 // even if that's not the promoted type. Note that the check for promoting
1845 // the underlying type is based on the type alone, and does not consider
1846 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001847 if (FromEnumType->getDecl()->isFixed()) {
1848 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1849 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001850 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001851 }
1852
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001853 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001854 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001855 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001856 return Context.hasSameUnqualifiedType(
1857 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001858 }
John McCall56774992009-12-09 09:09:27 +00001859
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001860 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1862 // to an rvalue a prvalue of the first of the following types that can
1863 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001864 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001866 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001868 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001869 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001870 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001871 // Determine whether the type we're converting from is signed or
1872 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001873 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001874 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001875
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001876 // The types we'll try to promote to, in the appropriate
1877 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001878 QualType PromoteTypes[6] = {
1879 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001880 Context.LongTy, Context.UnsignedLongTy ,
1881 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001882 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001883 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001884 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1885 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001886 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001887 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1888 // We found the type that we can promote to. If this is the
1889 // type we wanted, we have a promotion. Otherwise, no
1890 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001891 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001892 }
1893 }
1894 }
1895
1896 // An rvalue for an integral bit-field (9.6) can be converted to an
1897 // rvalue of type int if int can represent all the values of the
1898 // bit-field; otherwise, it can be converted to unsigned int if
1899 // unsigned int can represent all the values of the bit-field. If
1900 // the bit-field is larger yet, no integral promotion applies to
1901 // it. If the bit-field has an enumerated type, it is treated as any
1902 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001903 // FIXME: We should delay checking of bit-fields until we actually perform the
1904 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001905 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001906 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001907 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001908 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001909 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001910 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001911 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001912
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001913 // Are we promoting to an int from a bitfield that fits in an int?
1914 if (BitWidth < ToSize ||
1915 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1916 return To->getKind() == BuiltinType::Int;
1917 }
Mike Stump11289f42009-09-09 15:08:12 +00001918
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001919 // Are we promoting to an unsigned int from an unsigned bitfield
1920 // that fits into an unsigned int?
1921 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1922 return To->getKind() == BuiltinType::UInt;
1923 }
Mike Stump11289f42009-09-09 15:08:12 +00001924
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001925 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001926 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001927 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001928 }
Mike Stump11289f42009-09-09 15:08:12 +00001929
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001930 // An rvalue of type bool can be converted to an rvalue of type int,
1931 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001932 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001933 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001934 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001935
1936 return false;
1937}
1938
1939/// IsFloatingPointPromotion - Determines whether the conversion from
1940/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1941/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001942bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001943 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1944 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001945 /// An rvalue of type float can be converted to an rvalue of type
1946 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001947 if (FromBuiltin->getKind() == BuiltinType::Float &&
1948 ToBuiltin->getKind() == BuiltinType::Double)
1949 return true;
1950
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001951 // C99 6.3.1.5p1:
1952 // When a float is promoted to double or long double, or a
1953 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001954 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001955 (FromBuiltin->getKind() == BuiltinType::Float ||
1956 FromBuiltin->getKind() == BuiltinType::Double) &&
1957 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1958 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001959
1960 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001961 if (!getLangOpts().NativeHalfType &&
1962 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001963 ToBuiltin->getKind() == BuiltinType::Float)
1964 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001965 }
1966
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001967 return false;
1968}
1969
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001970/// \brief Determine if a conversion is a complex promotion.
1971///
1972/// A complex promotion is defined as a complex -> complex conversion
1973/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001974/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001975bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001976 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001977 if (!FromComplex)
1978 return false;
1979
John McCall9dd450b2009-09-21 23:43:11 +00001980 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001981 if (!ToComplex)
1982 return false;
1983
1984 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001985 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001986 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001987 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001988}
1989
Douglas Gregor237f96c2008-11-26 23:31:11 +00001990/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1991/// the pointer type FromPtr to a pointer to type ToPointee, with the
1992/// same type qualifiers as FromPtr has on its pointee type. ToType,
1993/// if non-empty, will be a pointer to ToType that may or may not have
1994/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001995///
Mike Stump11289f42009-09-09 15:08:12 +00001996static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001997BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001998 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001999 ASTContext &Context,
2000 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002001 assert((FromPtr->getTypeClass() == Type::Pointer ||
2002 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2003 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
John McCall31168b02011-06-15 23:02:42 +00002005 /// Conversions to 'id' subsume cv-qualifier conversions.
2006 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002007 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
2009 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002010 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002011 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002012 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002013
John McCall31168b02011-06-15 23:02:42 +00002014 if (StripObjCLifetime)
2015 Quals.removeObjCLifetime();
2016
Mike Stump11289f42009-09-09 15:08:12 +00002017 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002018 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002019 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002020 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002021 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002022
2023 // Build a pointer to ToPointee. It has the right qualifiers
2024 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002025 if (isa<ObjCObjectPointerType>(ToType))
2026 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002027 return Context.getPointerType(ToPointee);
2028 }
2029
2030 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002031 QualType QualifiedCanonToPointee
2032 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002034 if (isa<ObjCObjectPointerType>(ToType))
2035 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2036 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002037}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Mike Stump11289f42009-09-09 15:08:12 +00002039static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002040 bool InOverloadResolution,
2041 ASTContext &Context) {
2042 // Handle value-dependent integral null pointer constants correctly.
2043 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2044 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002045 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002046 return !InOverloadResolution;
2047
Douglas Gregor56751b52009-09-25 04:25:58 +00002048 return Expr->isNullPointerConstant(Context,
2049 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2050 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002051}
Mike Stump11289f42009-09-09 15:08:12 +00002052
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002053/// IsPointerConversion - Determines whether the conversion of the
2054/// expression From, which has the (possibly adjusted) type FromType,
2055/// can be converted to the type ToType via a pointer conversion (C++
2056/// 4.10). If so, returns true and places the converted type (that
2057/// might differ from ToType in its cv-qualifiers at some level) into
2058/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002059///
Douglas Gregora29dc052008-11-27 01:19:21 +00002060/// This routine also supports conversions to and from block pointers
2061/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2062/// pointers to interfaces. FIXME: Once we've determined the
2063/// appropriate overloading rules for Objective-C, we may want to
2064/// split the Objective-C checks into a different routine; however,
2065/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002066/// conversions, so for now they live here. IncompatibleObjC will be
2067/// set if the conversion is an allowed Objective-C conversion that
2068/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002070 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002071 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002072 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002073 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002074 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2075 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002076 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002077
Mike Stump11289f42009-09-09 15:08:12 +00002078 // Conversion from a null pointer constant to any Objective-C pointer type.
2079 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002080 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002081 ConvertedType = ToType;
2082 return true;
2083 }
2084
Douglas Gregor231d1c62008-11-27 00:15:41 +00002085 // Blocks: Block pointers can be converted to void*.
2086 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002087 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002088 ConvertedType = ToType;
2089 return true;
2090 }
2091 // Blocks: A null pointer constant can be converted to a block
2092 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002093 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002094 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002095 ConvertedType = ToType;
2096 return true;
2097 }
2098
Sebastian Redl576fd422009-05-10 18:38:11 +00002099 // If the left-hand-side is nullptr_t, the right side can be a null
2100 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002101 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002102 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002103 ConvertedType = ToType;
2104 return true;
2105 }
2106
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002107 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002108 if (!ToTypePtr)
2109 return false;
2110
2111 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002112 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002113 ConvertedType = ToType;
2114 return true;
2115 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002116
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002117 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002118 // , including objective-c pointers.
2119 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002120 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002121 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002122 ConvertedType = BuildSimilarlyQualifiedPointerType(
2123 FromType->getAs<ObjCObjectPointerType>(),
2124 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002125 ToType, Context);
2126 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002127 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002128 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002129 if (!FromTypePtr)
2130 return false;
2131
2132 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002133
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002135 // pointer conversion, so don't do all of the work below.
2136 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2137 return false;
2138
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002139 // An rvalue of type "pointer to cv T," where T is an object type,
2140 // can be converted to an rvalue of type "pointer to cv void" (C++
2141 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002142 if (FromPointeeType->isIncompleteOrObjectType() &&
2143 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002144 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002145 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002146 ToType, Context,
2147 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002148 return true;
2149 }
2150
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002151 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002152 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002153 ToPointeeType->isVoidType()) {
2154 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2155 ToPointeeType,
2156 ToType, Context);
2157 return true;
2158 }
2159
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002160 // When we're overloading in C, we allow a special kind of pointer
2161 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002162 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002163 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002164 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002165 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002166 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002167 return true;
2168 }
2169
Douglas Gregor5c407d92008-10-23 00:40:37 +00002170 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002171 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002172 // An rvalue of type "pointer to cv D," where D is a class type,
2173 // can be converted to an rvalue of type "pointer to cv B," where
2174 // B is a base class (clause 10) of D. If B is an inaccessible
2175 // (clause 11) or ambiguous (10.2) base class of D, a program that
2176 // necessitates this conversion is ill-formed. The result of the
2177 // conversion is a pointer to the base class sub-object of the
2178 // derived class object. The null pointer value is converted to
2179 // the null pointer value of the destination type.
2180 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002181 // Note that we do not check for ambiguity or inaccessibility
2182 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002183 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002184 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002185 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002186 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002187 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002188 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002189 ToType, Context);
2190 return true;
2191 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002192
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002193 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2194 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2195 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2196 ToPointeeType,
2197 ToType, Context);
2198 return true;
2199 }
2200
Douglas Gregora119f102008-12-19 19:13:09 +00002201 return false;
2202}
Douglas Gregoraec25842011-04-26 23:16:46 +00002203
2204/// \brief Adopt the given qualifiers for the given type.
2205static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2206 Qualifiers TQs = T.getQualifiers();
2207
2208 // Check whether qualifiers already match.
2209 if (TQs == Qs)
2210 return T;
2211
2212 if (Qs.compatiblyIncludes(TQs))
2213 return Context.getQualifiedType(T, Qs);
2214
2215 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2216}
Douglas Gregora119f102008-12-19 19:13:09 +00002217
2218/// isObjCPointerConversion - Determines whether this is an
2219/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2220/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002221bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002222 QualType& ConvertedType,
2223 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002224 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002225 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002226
Douglas Gregoraec25842011-04-26 23:16:46 +00002227 // The set of qualifiers on the type we're converting from.
2228 Qualifiers FromQualifiers = FromType.getQualifiers();
2229
Steve Naroff7cae42b2009-07-10 23:34:53 +00002230 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002231 const ObjCObjectPointerType* ToObjCPtr =
2232 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002233 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002234 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002235
Steve Naroff7cae42b2009-07-10 23:34:53 +00002236 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002237 // If the pointee types are the same (ignoring qualifications),
2238 // then this is not a pointer conversion.
2239 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2240 FromObjCPtr->getPointeeType()))
2241 return false;
2242
Douglas Gregorab209d82015-07-07 03:58:42 +00002243 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002244 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002245 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2246 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002247 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002248 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2249 FromObjCPtr->getPointeeType()))
2250 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002251 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002252 ToObjCPtr->getPointeeType(),
2253 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002254 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002255 return true;
2256 }
2257
2258 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2259 // Okay: this is some kind of implicit downcast of Objective-C
2260 // interfaces, which is permitted. However, we're going to
2261 // complain about it.
2262 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002263 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002264 ToObjCPtr->getPointeeType(),
2265 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002266 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002267 return true;
2268 }
Mike Stump11289f42009-09-09 15:08:12 +00002269 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002270 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002271 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002272 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002273 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002275 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002276 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002277 // to a block pointer type.
2278 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002279 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002280 return true;
2281 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002282 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002284 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002285 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002286 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002287 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002288 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002289 return true;
2290 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002291 else
Douglas Gregora119f102008-12-19 19:13:09 +00002292 return false;
2293
Douglas Gregor033f56d2008-12-23 00:53:59 +00002294 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002295 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002296 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002297 else if (const BlockPointerType *FromBlockPtr =
2298 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002299 FromPointeeType = FromBlockPtr->getPointeeType();
2300 else
Douglas Gregora119f102008-12-19 19:13:09 +00002301 return false;
2302
Douglas Gregora119f102008-12-19 19:13:09 +00002303 // If we have pointers to pointers, recursively check whether this
2304 // is an Objective-C conversion.
2305 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2306 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2307 IncompatibleObjC)) {
2308 // We always complain about this conversion.
2309 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002310 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002311 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002312 return true;
2313 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002314 // Allow conversion of pointee being objective-c pointer to another one;
2315 // as in I* to id.
2316 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2317 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2318 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2319 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002320
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002321 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002322 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002323 return true;
2324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002325
Douglas Gregor033f56d2008-12-23 00:53:59 +00002326 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002327 // differences in the argument and result types are in Objective-C
2328 // pointer conversions. If so, we permit the conversion (but
2329 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002330 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002331 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002332 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002333 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002334 if (FromFunctionType && ToFunctionType) {
2335 // If the function types are exactly the same, this isn't an
2336 // Objective-C pointer conversion.
2337 if (Context.getCanonicalType(FromPointeeType)
2338 == Context.getCanonicalType(ToPointeeType))
2339 return false;
2340
2341 // Perform the quick checks that will tell us whether these
2342 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002343 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002344 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2345 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2346 return false;
2347
2348 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002349 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2350 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002351 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002352 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2353 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002354 ConvertedType, IncompatibleObjC)) {
2355 // Okay, we have an Objective-C pointer conversion.
2356 HasObjCConversion = true;
2357 } else {
2358 // Function types are too different. Abort.
2359 return false;
2360 }
Mike Stump11289f42009-09-09 15:08:12 +00002361
Douglas Gregora119f102008-12-19 19:13:09 +00002362 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002363 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002364 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002365 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2366 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002367 if (Context.getCanonicalType(FromArgType)
2368 == Context.getCanonicalType(ToArgType)) {
2369 // Okay, the types match exactly. Nothing to do.
2370 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2371 ConvertedType, IncompatibleObjC)) {
2372 // Okay, we have an Objective-C pointer conversion.
2373 HasObjCConversion = true;
2374 } else {
2375 // Argument types are too different. Abort.
2376 return false;
2377 }
2378 }
2379
2380 if (HasObjCConversion) {
2381 // We had an Objective-C conversion. Allow this pointer
2382 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002383 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002384 IncompatibleObjC = true;
2385 return true;
2386 }
2387 }
2388
Sebastian Redl72b597d2009-01-25 19:43:20 +00002389 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002390}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002391
John McCall31168b02011-06-15 23:02:42 +00002392/// \brief Determine whether this is an Objective-C writeback conversion,
2393/// used for parameter passing when performing automatic reference counting.
2394///
2395/// \param FromType The type we're converting form.
2396///
2397/// \param ToType The type we're converting to.
2398///
2399/// \param ConvertedType The type that will be produced after applying
2400/// this conversion.
2401bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2402 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002403 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002404 Context.hasSameUnqualifiedType(FromType, ToType))
2405 return false;
2406
2407 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2408 QualType ToPointee;
2409 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2410 ToPointee = ToPointer->getPointeeType();
2411 else
2412 return false;
2413
2414 Qualifiers ToQuals = ToPointee.getQualifiers();
2415 if (!ToPointee->isObjCLifetimeType() ||
2416 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002417 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002418 return false;
2419
2420 // Argument must be a pointer to __strong to __weak.
2421 QualType FromPointee;
2422 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2423 FromPointee = FromPointer->getPointeeType();
2424 else
2425 return false;
2426
2427 Qualifiers FromQuals = FromPointee.getQualifiers();
2428 if (!FromPointee->isObjCLifetimeType() ||
2429 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2430 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2431 return false;
2432
2433 // Make sure that we have compatible qualifiers.
2434 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2435 if (!ToQuals.compatiblyIncludes(FromQuals))
2436 return false;
2437
2438 // Remove qualifiers from the pointee type we're converting from; they
2439 // aren't used in the compatibility check belong, and we'll be adding back
2440 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2441 FromPointee = FromPointee.getUnqualifiedType();
2442
2443 // The unqualified form of the pointee types must be compatible.
2444 ToPointee = ToPointee.getUnqualifiedType();
2445 bool IncompatibleObjC;
2446 if (Context.typesAreCompatible(FromPointee, ToPointee))
2447 FromPointee = ToPointee;
2448 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2449 IncompatibleObjC))
2450 return false;
2451
2452 /// \brief Construct the type we're converting to, which is a pointer to
2453 /// __autoreleasing pointee.
2454 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2455 ConvertedType = Context.getPointerType(FromPointee);
2456 return true;
2457}
2458
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002459bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2460 QualType& ConvertedType) {
2461 QualType ToPointeeType;
2462 if (const BlockPointerType *ToBlockPtr =
2463 ToType->getAs<BlockPointerType>())
2464 ToPointeeType = ToBlockPtr->getPointeeType();
2465 else
2466 return false;
2467
2468 QualType FromPointeeType;
2469 if (const BlockPointerType *FromBlockPtr =
2470 FromType->getAs<BlockPointerType>())
2471 FromPointeeType = FromBlockPtr->getPointeeType();
2472 else
2473 return false;
2474 // We have pointer to blocks, check whether the only
2475 // differences in the argument and result types are in Objective-C
2476 // pointer conversions. If so, we permit the conversion.
2477
2478 const FunctionProtoType *FromFunctionType
2479 = FromPointeeType->getAs<FunctionProtoType>();
2480 const FunctionProtoType *ToFunctionType
2481 = ToPointeeType->getAs<FunctionProtoType>();
2482
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002483 if (!FromFunctionType || !ToFunctionType)
2484 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002485
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002486 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002487 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002488
2489 // Perform the quick checks that will tell us whether these
2490 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002491 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002492 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2493 return false;
2494
2495 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2496 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2497 if (FromEInfo != ToEInfo)
2498 return false;
2499
2500 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002501 if (Context.hasSameType(FromFunctionType->getReturnType(),
2502 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002503 // Okay, the types match exactly. Nothing to do.
2504 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002505 QualType RHS = FromFunctionType->getReturnType();
2506 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002507 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002508 !RHS.hasQualifiers() && LHS.hasQualifiers())
2509 LHS = LHS.getUnqualifiedType();
2510
2511 if (Context.hasSameType(RHS,LHS)) {
2512 // OK exact match.
2513 } else if (isObjCPointerConversion(RHS, LHS,
2514 ConvertedType, IncompatibleObjC)) {
2515 if (IncompatibleObjC)
2516 return false;
2517 // Okay, we have an Objective-C pointer conversion.
2518 }
2519 else
2520 return false;
2521 }
2522
2523 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002524 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002525 ArgIdx != NumArgs; ++ArgIdx) {
2526 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002527 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2528 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002529 if (Context.hasSameType(FromArgType, ToArgType)) {
2530 // Okay, the types match exactly. Nothing to do.
2531 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2532 ConvertedType, IncompatibleObjC)) {
2533 if (IncompatibleObjC)
2534 return false;
2535 // Okay, we have an Objective-C pointer conversion.
2536 } else
2537 // Argument types are too different. Abort.
2538 return false;
2539 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002540 if (LangOpts.ObjCAutoRefCount &&
2541 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2542 ToFunctionType))
2543 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002544
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002545 ConvertedType = ToType;
2546 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002547}
2548
Richard Trieucaff2472011-11-23 22:32:32 +00002549enum {
2550 ft_default,
2551 ft_different_class,
2552 ft_parameter_arity,
2553 ft_parameter_mismatch,
2554 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002555 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002556};
2557
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002558/// Attempts to get the FunctionProtoType from a Type. Handles
2559/// MemberFunctionPointers properly.
2560static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2561 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2562 return FPT;
2563
2564 if (auto *MPT = FromType->getAs<MemberPointerType>())
2565 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2566
2567 return nullptr;
2568}
2569
Richard Trieucaff2472011-11-23 22:32:32 +00002570/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2571/// function types. Catches different number of parameter, mismatch in
2572/// parameter types, and different return types.
2573void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2574 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002575 // If either type is not valid, include no extra info.
2576 if (FromType.isNull() || ToType.isNull()) {
2577 PDiag << ft_default;
2578 return;
2579 }
2580
Richard Trieucaff2472011-11-23 22:32:32 +00002581 // Get the function type from the pointers.
2582 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2583 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2584 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002585 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002586 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2587 << QualType(FromMember->getClass(), 0);
2588 return;
2589 }
2590 FromType = FromMember->getPointeeType();
2591 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002592 }
2593
Richard Trieu96ed5b62011-12-13 23:19:45 +00002594 if (FromType->isPointerType())
2595 FromType = FromType->getPointeeType();
2596 if (ToType->isPointerType())
2597 ToType = ToType->getPointeeType();
2598
2599 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002600 FromType = FromType.getNonReferenceType();
2601 ToType = ToType.getNonReferenceType();
2602
Richard Trieucaff2472011-11-23 22:32:32 +00002603 // Don't print extra info for non-specialized template functions.
2604 if (FromType->isInstantiationDependentType() &&
2605 !FromType->getAs<TemplateSpecializationType>()) {
2606 PDiag << ft_default;
2607 return;
2608 }
2609
Richard Trieu96ed5b62011-12-13 23:19:45 +00002610 // No extra info for same types.
2611 if (Context.hasSameType(FromType, ToType)) {
2612 PDiag << ft_default;
2613 return;
2614 }
2615
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002616 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2617 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002618
2619 // Both types need to be function types.
2620 if (!FromFunction || !ToFunction) {
2621 PDiag << ft_default;
2622 return;
2623 }
2624
Alp Toker9cacbab2014-01-20 20:26:09 +00002625 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2626 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2627 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002628 return;
2629 }
2630
2631 // Handle different parameter types.
2632 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002633 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002634 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002635 << ToFunction->getParamType(ArgPos)
2636 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002637 return;
2638 }
2639
2640 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002641 if (!Context.hasSameType(FromFunction->getReturnType(),
2642 ToFunction->getReturnType())) {
2643 PDiag << ft_return_type << ToFunction->getReturnType()
2644 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002645 return;
2646 }
2647
2648 unsigned FromQuals = FromFunction->getTypeQuals(),
2649 ToQuals = ToFunction->getTypeQuals();
2650 if (FromQuals != ToQuals) {
2651 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2652 return;
2653 }
2654
2655 // Unable to find a difference, so add no extra info.
2656 PDiag << ft_default;
2657}
2658
Alp Toker9cacbab2014-01-20 20:26:09 +00002659/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002660/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002661/// they have same number of arguments. If the parameters are different,
2662/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002663bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2664 const FunctionProtoType *NewType,
2665 unsigned *ArgPos) {
2666 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2667 N = NewType->param_type_begin(),
2668 E = OldType->param_type_end();
2669 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002670 if (!Context.hasSameType(O->getUnqualifiedType(),
2671 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002672 if (ArgPos)
2673 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002674 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002675 }
2676 }
2677 return true;
2678}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002679
Douglas Gregor39c16d42008-10-24 04:54:22 +00002680/// CheckPointerConversion - Check the pointer conversion from the
2681/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002682/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002683/// conversions for which IsPointerConversion has already returned
2684/// true. It returns true and produces a diagnostic if there was an
2685/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002686bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002687 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002688 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002689 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002690 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002691 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002692
John McCall8cb679e2010-11-15 09:13:47 +00002693 Kind = CK_BitCast;
2694
David Blaikie1c7c8f72012-08-08 17:33:31 +00002695 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002696 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002697 Expr::NPCK_ZeroExpression) {
2698 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2699 DiagRuntimeBehavior(From->getExprLoc(), From,
2700 PDiag(diag::warn_impcast_bool_to_null_pointer)
2701 << ToType << From->getSourceRange());
2702 else if (!isUnevaluatedContext())
2703 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2704 << ToType << From->getSourceRange();
2705 }
John McCall9320b872011-09-09 05:25:32 +00002706 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2707 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002708 QualType FromPointeeType = FromPtrType->getPointeeType(),
2709 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002710
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002711 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2712 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002713 // We must have a derived-to-base conversion. Check an
2714 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002715 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2716 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002717 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002718 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002719 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002720
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002721 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002722 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002723 }
David Majnemer6bf02822015-10-31 08:42:14 +00002724
2725 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() &&
2726 ToPointeeType->isVoidType()) {
2727 assert(getLangOpts().MSVCCompat &&
2728 "this should only be possible with MSVCCompat!");
2729 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2730 << From->getSourceRange();
2731 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002732 }
John McCall9320b872011-09-09 05:25:32 +00002733 } else if (const ObjCObjectPointerType *ToPtrType =
2734 ToType->getAs<ObjCObjectPointerType>()) {
2735 if (const ObjCObjectPointerType *FromPtrType =
2736 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002737 // Objective-C++ conversions are always okay.
2738 // FIXME: We should have a different class of conversions for the
2739 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002740 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002741 return false;
John McCall9320b872011-09-09 05:25:32 +00002742 } else if (FromType->isBlockPointerType()) {
2743 Kind = CK_BlockPointerToObjCPointerCast;
2744 } else {
2745 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002746 }
John McCall9320b872011-09-09 05:25:32 +00002747 } else if (ToType->isBlockPointerType()) {
2748 if (!FromType->isBlockPointerType())
2749 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002750 }
John McCall8cb679e2010-11-15 09:13:47 +00002751
2752 // We shouldn't fall into this case unless it's valid for other
2753 // reasons.
2754 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2755 Kind = CK_NullToPointer;
2756
Douglas Gregor39c16d42008-10-24 04:54:22 +00002757 return false;
2758}
2759
Sebastian Redl72b597d2009-01-25 19:43:20 +00002760/// IsMemberPointerConversion - Determines whether the conversion of the
2761/// expression From, which has the (possibly adjusted) type FromType, can be
2762/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2763/// If so, returns true and places the converted type (that might differ from
2764/// ToType in its cv-qualifiers at some level) into ConvertedType.
2765bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002766 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002767 bool InOverloadResolution,
2768 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002769 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002770 if (!ToTypePtr)
2771 return false;
2772
2773 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002774 if (From->isNullPointerConstant(Context,
2775 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2776 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002777 ConvertedType = ToType;
2778 return true;
2779 }
2780
2781 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002782 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002783 if (!FromTypePtr)
2784 return false;
2785
2786 // A pointer to member of B can be converted to a pointer to member of D,
2787 // where D is derived from B (C++ 4.11p2).
2788 QualType FromClass(FromTypePtr->getClass(), 0);
2789 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002790
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002791 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002792 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002793 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2794 ToClass.getTypePtr());
2795 return true;
2796 }
2797
2798 return false;
2799}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002800
Sebastian Redl72b597d2009-01-25 19:43:20 +00002801/// CheckMemberPointerConversion - Check the member pointer conversion from the
2802/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002803/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002804/// for which IsMemberPointerConversion has already returned true. It returns
2805/// true and produces a diagnostic if there was an error, or returns false
2806/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002807bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002808 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002809 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002810 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002811 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002812 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002813 if (!FromPtrType) {
2814 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002815 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002816 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002817 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002818 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002819 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002820 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002821
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002822 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002823 assert(ToPtrType && "No member pointer cast has a target type "
2824 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002825
Sebastian Redled8f2002009-01-28 18:33:18 +00002826 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2827 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002828
Sebastian Redled8f2002009-01-28 18:33:18 +00002829 // FIXME: What about dependent types?
2830 assert(FromClass->isRecordType() && "Pointer into non-class.");
2831 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002832
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002833 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002834 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002835 bool DerivationOkay =
2836 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002837 assert(DerivationOkay &&
2838 "Should not have been called if derivation isn't OK.");
2839 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002840
Sebastian Redled8f2002009-01-28 18:33:18 +00002841 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2842 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002843 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2844 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2845 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2846 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002847 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002848
Douglas Gregor89ee6822009-02-28 01:32:25 +00002849 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002850 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2851 << FromClass << ToClass << QualType(VBase, 0)
2852 << From->getSourceRange();
2853 return true;
2854 }
2855
John McCall5b0829a2010-02-10 09:31:12 +00002856 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002857 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2858 Paths.front(),
2859 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002860
Anders Carlssond7923c62009-08-22 23:33:40 +00002861 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002862 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002863 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002864 return false;
2865}
2866
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002867/// Determine whether the lifetime conversion between the two given
2868/// qualifiers sets is nontrivial.
2869static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2870 Qualifiers ToQuals) {
2871 // Converting anything to const __unsafe_unretained is trivial.
2872 if (ToQuals.hasConst() &&
2873 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2874 return false;
2875
2876 return true;
2877}
2878
Douglas Gregor9a657932008-10-21 23:43:52 +00002879/// IsQualificationConversion - Determines whether the conversion from
2880/// an rvalue of type FromType to ToType is a qualification conversion
2881/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002882///
2883/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2884/// when the qualification conversion involves a change in the Objective-C
2885/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002886bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002887Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002888 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002889 FromType = Context.getCanonicalType(FromType);
2890 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002891 ObjCLifetimeConversion = false;
2892
Douglas Gregor9a657932008-10-21 23:43:52 +00002893 // If FromType and ToType are the same type, this is not a
2894 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002895 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002896 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002897
Douglas Gregor9a657932008-10-21 23:43:52 +00002898 // (C++ 4.4p4):
2899 // A conversion can add cv-qualifiers at levels other than the first
2900 // in multi-level pointers, subject to the following rules: [...]
2901 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002902 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002903 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002904 // Within each iteration of the loop, we check the qualifiers to
2905 // determine if this still looks like a qualification
2906 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002907 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002908 // until there are no more pointers or pointers-to-members left to
2909 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002910 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002911
Douglas Gregor90609aa2011-04-25 18:40:17 +00002912 Qualifiers FromQuals = FromType.getQualifiers();
2913 Qualifiers ToQuals = ToType.getQualifiers();
2914
John McCall31168b02011-06-15 23:02:42 +00002915 // Objective-C ARC:
2916 // Check Objective-C lifetime conversions.
2917 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2918 UnwrappedAnyPointer) {
2919 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002920 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2921 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002922 FromQuals.removeObjCLifetime();
2923 ToQuals.removeObjCLifetime();
2924 } else {
2925 // Qualification conversions cannot cast between different
2926 // Objective-C lifetime qualifiers.
2927 return false;
2928 }
2929 }
2930
Douglas Gregorf30053d2011-05-08 06:09:53 +00002931 // Allow addition/removal of GC attributes but not changing GC attributes.
2932 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2933 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2934 FromQuals.removeObjCGCAttr();
2935 ToQuals.removeObjCGCAttr();
2936 }
2937
Douglas Gregor9a657932008-10-21 23:43:52 +00002938 // -- for every j > 0, if const is in cv 1,j then const is in cv
2939 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002940 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002941 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002942
Douglas Gregor9a657932008-10-21 23:43:52 +00002943 // -- if the cv 1,j and cv 2,j are different, then const is in
2944 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002945 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002946 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002947 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002948
Douglas Gregor9a657932008-10-21 23:43:52 +00002949 // Keep track of whether all prior cv-qualifiers in the "to" type
2950 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002951 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002952 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002953 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002954
2955 // We are left with FromType and ToType being the pointee types
2956 // after unwrapping the original FromType and ToType the same number
2957 // of types. If we unwrapped any pointers, and if FromType and
2958 // ToType have the same unqualified type (since we checked
2959 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002960 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002961}
2962
Douglas Gregorc79862f2012-04-12 17:51:55 +00002963/// \brief - Determine whether this is a conversion from a scalar type to an
2964/// atomic type.
2965///
2966/// If successful, updates \c SCS's second and third steps in the conversion
2967/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002968static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2969 bool InOverloadResolution,
2970 StandardConversionSequence &SCS,
2971 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002972 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2973 if (!ToAtomic)
2974 return false;
2975
2976 StandardConversionSequence InnerSCS;
2977 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2978 InOverloadResolution, InnerSCS,
2979 CStyle, /*AllowObjCWritebackConversion=*/false))
2980 return false;
2981
2982 SCS.Second = InnerSCS.Second;
2983 SCS.setToType(1, InnerSCS.getToType(1));
2984 SCS.Third = InnerSCS.Third;
2985 SCS.QualificationIncludesObjCLifetime
2986 = InnerSCS.QualificationIncludesObjCLifetime;
2987 SCS.setToType(2, InnerSCS.getToType(2));
2988 return true;
2989}
2990
Sebastian Redle5417162012-03-27 18:33:03 +00002991static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2992 CXXConstructorDecl *Constructor,
2993 QualType Type) {
2994 const FunctionProtoType *CtorType =
2995 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002996 if (CtorType->getNumParams() > 0) {
2997 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002998 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2999 return true;
3000 }
3001 return false;
3002}
3003
Sebastian Redl82ace982012-02-11 23:51:08 +00003004static OverloadingResult
3005IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3006 CXXRecordDecl *To,
3007 UserDefinedConversionSequence &User,
3008 OverloadCandidateSet &CandidateSet,
3009 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00003010 DeclContext::lookup_result R = S.LookupConstructors(To);
3011 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00003012 Con != ConEnd; ++Con) {
3013 NamedDecl *D = *Con;
3014 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3015
3016 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003017 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00003018 FunctionTemplateDecl *ConstructorTmpl
3019 = dyn_cast<FunctionTemplateDecl>(D);
3020 if (ConstructorTmpl)
3021 Constructor
3022 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3023 else
3024 Constructor = cast<CXXConstructorDecl>(D);
3025
3026 bool Usable = !Constructor->isInvalidDecl() &&
3027 S.isInitListConstructor(Constructor) &&
3028 (AllowExplicit || !Constructor->isExplicit());
3029 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003030 // If the first argument is (a reference to) the target type,
3031 // suppress conversions.
3032 bool SuppressUserConversions =
3033 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00003034 if (ConstructorTmpl)
3035 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003036 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003037 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003038 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003039 else
3040 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003041 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003042 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003043 }
3044 }
3045
3046 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3047
3048 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003049 switch (auto Result =
3050 CandidateSet.BestViableFunction(S, From->getLocStart(),
3051 Best, true)) {
3052 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003053 case OR_Success: {
3054 // Record the standard conversion we used and the conversion function.
3055 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003056 QualType ThisType = Constructor->getThisType(S.Context);
3057 // Initializer lists don't have conversions as such.
3058 User.Before.setAsIdentityConversion();
3059 User.HadMultipleCandidates = HadMultipleCandidates;
3060 User.ConversionFunction = Constructor;
3061 User.FoundConversionFunction = Best->FoundDecl;
3062 User.After.setAsIdentityConversion();
3063 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3064 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003065 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003066 }
3067
3068 case OR_No_Viable_Function:
3069 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003070 case OR_Ambiguous:
3071 return OR_Ambiguous;
3072 }
3073
3074 llvm_unreachable("Invalid OverloadResult!");
3075}
3076
Douglas Gregor576e98c2009-01-30 23:27:23 +00003077/// Determines whether there is a user-defined conversion sequence
3078/// (C++ [over.ics.user]) that converts expression From to the type
3079/// ToType. If such a conversion exists, User will contain the
3080/// user-defined conversion sequence that performs such a conversion
3081/// and this routine will return true. Otherwise, this routine returns
3082/// false and User is unspecified.
3083///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003084/// \param AllowExplicit true if the conversion should consider C++0x
3085/// "explicit" conversion functions as well as non-explicit conversion
3086/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003087///
3088/// \param AllowObjCConversionOnExplicit true if the conversion should
3089/// allow an extra Objective-C pointer conversion on uses of explicit
3090/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003091static OverloadingResult
3092IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003093 UserDefinedConversionSequence &User,
3094 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003095 bool AllowExplicit,
3096 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003097 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003098
Douglas Gregor5ab11652010-04-17 22:01:05 +00003099 // Whether we will only visit constructors.
3100 bool ConstructorsOnly = false;
3101
3102 // If the type we are conversion to is a class type, enumerate its
3103 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003104 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003105 // C++ [over.match.ctor]p1:
3106 // When objects of class type are direct-initialized (8.5), or
3107 // copy-initialized from an expression of the same or a
3108 // derived class type (8.5), overload resolution selects the
3109 // constructor. [...] For copy-initialization, the candidate
3110 // functions are all the converting constructors (12.3.1) of
3111 // that class. The argument list is the expression-list within
3112 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003113 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003114 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003115 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003116 ConstructorsOnly = true;
3117
Richard Smithdb0ac552015-12-18 22:40:25 +00003118 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003119 // We're not going to find any constructors.
3120 } else if (CXXRecordDecl *ToRecordDecl
3121 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003122
3123 Expr **Args = &From;
3124 unsigned NumArgs = 1;
3125 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003126 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003127 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003128 OverloadingResult Result = IsInitializerListConstructorConversion(
3129 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3130 if (Result != OR_No_Viable_Function)
3131 return Result;
3132 // Never mind.
3133 CandidateSet.clear();
3134
3135 // If we're list-initializing, we pass the individual elements as
3136 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003137 Args = InitList->getInits();
3138 NumArgs = InitList->getNumInits();
3139 ListInitializing = true;
3140 }
3141
David Blaikieff7d47a2012-12-19 00:45:41 +00003142 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3143 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003144 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003145 NamedDecl *D = *Con;
3146 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3147
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003148 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003149 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003150 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003151 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003152 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003153 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003154 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3155 else
John McCalla0296f72010-03-19 07:35:19 +00003156 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003158 bool Usable = !Constructor->isInvalidDecl();
3159 if (ListInitializing)
3160 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3161 else
3162 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3163 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003164 bool SuppressUserConversions = !ConstructorsOnly;
3165 if (SuppressUserConversions && ListInitializing) {
3166 SuppressUserConversions = false;
3167 if (NumArgs == 1) {
3168 // If the first argument is (a reference to) the target type,
3169 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003170 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3171 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003172 }
3173 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003174 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003175 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003176 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003177 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003178 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003179 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003180 // Allow one user-defined conversion when user specifies a
3181 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003182 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003183 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003184 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003185 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003186 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003187 }
3188 }
3189
Douglas Gregor5ab11652010-04-17 22:01:05 +00003190 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003191 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003192 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003193 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003194 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003195 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003196 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003197 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3198 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003199 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3200 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003201 DeclAccessPair FoundDecl = I.getPair();
3202 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003203 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3204 if (isa<UsingShadowDecl>(D))
3205 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3206
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003207 CXXConversionDecl *Conv;
3208 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003209 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3210 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003211 else
John McCallda4458e2010-03-31 01:36:47 +00003212 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003213
3214 if (AllowExplicit || !Conv->isExplicit()) {
3215 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003216 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3217 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003218 CandidateSet,
3219 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003220 else
John McCall5c32be02010-08-24 20:38:10 +00003221 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003222 From, ToType, CandidateSet,
3223 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003224 }
3225 }
3226 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003227 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003228
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003229 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3230
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003231 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003232 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3233 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003234 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003235 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003236 // Record the standard conversion we used and the conversion function.
3237 if (CXXConstructorDecl *Constructor
3238 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3239 // C++ [over.ics.user]p1:
3240 // If the user-defined conversion is specified by a
3241 // constructor (12.3.1), the initial standard conversion
3242 // sequence converts the source type to the type required by
3243 // the argument of the constructor.
3244 //
3245 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003246 if (isa<InitListExpr>(From)) {
3247 // Initializer lists don't have conversions as such.
3248 User.Before.setAsIdentityConversion();
3249 } else {
3250 if (Best->Conversions[0].isEllipsis())
3251 User.EllipsisConversion = true;
3252 else {
3253 User.Before = Best->Conversions[0].Standard;
3254 User.EllipsisConversion = false;
3255 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003256 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003257 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003258 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003259 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003260 User.After.setAsIdentityConversion();
3261 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3262 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003263 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003264 }
3265 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003266 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3267 // C++ [over.ics.user]p1:
3268 //
3269 // [...] If the user-defined conversion is specified by a
3270 // conversion function (12.3.2), the initial standard
3271 // conversion sequence converts the source type to the
3272 // implicit object parameter of the conversion function.
3273 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003274 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003275 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003276 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003277 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003278
John McCall5c32be02010-08-24 20:38:10 +00003279 // C++ [over.ics.user]p2:
3280 // The second standard conversion sequence converts the
3281 // result of the user-defined conversion to the target type
3282 // for the sequence. Since an implicit conversion sequence
3283 // is an initialization, the special rules for
3284 // initialization by user-defined conversion apply when
3285 // selecting the best user-defined conversion for a
3286 // user-defined conversion sequence (see 13.3.3 and
3287 // 13.3.3.1).
3288 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003289 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003290 }
David Blaikie8a40f702012-01-17 06:56:22 +00003291 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003292
John McCall5c32be02010-08-24 20:38:10 +00003293 case OR_No_Viable_Function:
3294 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003295
John McCall5c32be02010-08-24 20:38:10 +00003296 case OR_Ambiguous:
3297 return OR_Ambiguous;
3298 }
3299
David Blaikie8a40f702012-01-17 06:56:22 +00003300 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003301}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003302
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003303bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003304Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003305 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003306 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3307 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003309 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003310 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003311 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003312 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3313 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003314 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003315 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003316 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003317 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003318 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003319 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003320 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003321 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003322 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003324}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003325
Douglas Gregor2837aa22012-02-22 17:32:19 +00003326/// \brief Compare the user-defined conversion functions or constructors
3327/// of two user-defined conversion sequences to determine whether any ordering
3328/// is possible.
3329static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003330compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003331 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003332 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003333 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003334
Douglas Gregor2837aa22012-02-22 17:32:19 +00003335 // Objective-C++:
3336 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003337 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003338 // respectively, always prefer the conversion to a function pointer,
3339 // because the function pointer is more lightweight and is more likely
3340 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003341 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003342 if (!Conv1)
3343 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003344
Douglas Gregor2837aa22012-02-22 17:32:19 +00003345 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3346 if (!Conv2)
3347 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003348
Douglas Gregor2837aa22012-02-22 17:32:19 +00003349 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3350 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3351 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3352 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003353 return Block1 ? ImplicitConversionSequence::Worse
3354 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003355 }
3356
3357 return ImplicitConversionSequence::Indistinguishable;
3358}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003359
3360static bool hasDeprecatedStringLiteralToCharPtrConversion(
3361 const ImplicitConversionSequence &ICS) {
3362 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3363 (ICS.isUserDefined() &&
3364 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3365}
3366
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003367/// CompareImplicitConversionSequences - Compare two implicit
3368/// conversion sequences to determine whether one is better than the
3369/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003370static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003371CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003372 const ImplicitConversionSequence& ICS1,
3373 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003374{
3375 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3376 // conversion sequences (as defined in 13.3.3.1)
3377 // -- a standard conversion sequence (13.3.3.1.1) is a better
3378 // conversion sequence than a user-defined conversion sequence or
3379 // an ellipsis conversion sequence, and
3380 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3381 // conversion sequence than an ellipsis conversion sequence
3382 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003383 //
John McCall0d1da222010-01-12 00:44:57 +00003384 // C++0x [over.best.ics]p10:
3385 // For the purpose of ranking implicit conversion sequences as
3386 // described in 13.3.3.2, the ambiguous conversion sequence is
3387 // treated as a user-defined sequence that is indistinguishable
3388 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003389
3390 // String literal to 'char *' conversion has been deprecated in C++03. It has
3391 // been removed from C++11. We still accept this conversion, if it happens at
3392 // the best viable function. Otherwise, this conversion is considered worse
3393 // than ellipsis conversion. Consider this as an extension; this is not in the
3394 // standard. For example:
3395 //
3396 // int &f(...); // #1
3397 // void f(char*); // #2
3398 // void g() { int &r = f("foo"); }
3399 //
3400 // In C++03, we pick #2 as the best viable function.
3401 // In C++11, we pick #1 as the best viable function, because ellipsis
3402 // conversion is better than string-literal to char* conversion (since there
3403 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3404 // convert arguments, #2 would be the best viable function in C++11.
3405 // If the best viable function has this conversion, a warning will be issued
3406 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3407
3408 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3409 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3410 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3411 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3412 ? ImplicitConversionSequence::Worse
3413 : ImplicitConversionSequence::Better;
3414
Douglas Gregor5ab11652010-04-17 22:01:05 +00003415 if (ICS1.getKindRank() < ICS2.getKindRank())
3416 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003417 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003418 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003419
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003420 // The following checks require both conversion sequences to be of
3421 // the same kind.
3422 if (ICS1.getKind() != ICS2.getKind())
3423 return ImplicitConversionSequence::Indistinguishable;
3424
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003425 ImplicitConversionSequence::CompareKind Result =
3426 ImplicitConversionSequence::Indistinguishable;
3427
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003428 // Two implicit conversion sequences of the same form are
3429 // indistinguishable conversion sequences unless one of the
3430 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003431
3432 // List-initialization sequence L1 is a better conversion sequence than
3433 // list-initialization sequence L2 if:
3434 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3435 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003436 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003437 // and N1 is smaller than N2.,
3438 // even if one of the other rules in this paragraph would otherwise apply.
3439 if (!ICS1.isBad()) {
3440 if (ICS1.isStdInitializerListElement() &&
3441 !ICS2.isStdInitializerListElement())
3442 return ImplicitConversionSequence::Better;
3443 if (!ICS1.isStdInitializerListElement() &&
3444 ICS2.isStdInitializerListElement())
3445 return ImplicitConversionSequence::Worse;
3446 }
3447
John McCall0d1da222010-01-12 00:44:57 +00003448 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003449 // Standard conversion sequence S1 is a better conversion sequence than
3450 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003451 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003452 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003453 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003454 // User-defined conversion sequence U1 is a better conversion
3455 // sequence than another user-defined conversion sequence U2 if
3456 // they contain the same user-defined conversion function or
3457 // constructor and if the second standard conversion sequence of
3458 // U1 is better than the second standard conversion sequence of
3459 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003460 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003461 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003462 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003463 ICS1.UserDefined.After,
3464 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003465 else
3466 Result = compareConversionFunctions(S,
3467 ICS1.UserDefined.ConversionFunction,
3468 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003469 }
3470
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003471 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003472}
3473
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003474static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3475 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3476 Qualifiers Quals;
3477 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003481 return Context.hasSameUnqualifiedType(T1, T2);
3482}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003484// Per 13.3.3.2p3, compare the given standard conversion sequences to
3485// determine if one is a proper subset of the other.
3486static ImplicitConversionSequence::CompareKind
3487compareStandardConversionSubsets(ASTContext &Context,
3488 const StandardConversionSequence& SCS1,
3489 const StandardConversionSequence& SCS2) {
3490 ImplicitConversionSequence::CompareKind Result
3491 = ImplicitConversionSequence::Indistinguishable;
3492
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003494 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003495 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3496 return ImplicitConversionSequence::Better;
3497 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3498 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003500 if (SCS1.Second != SCS2.Second) {
3501 if (SCS1.Second == ICK_Identity)
3502 Result = ImplicitConversionSequence::Better;
3503 else if (SCS2.Second == ICK_Identity)
3504 Result = ImplicitConversionSequence::Worse;
3505 else
3506 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003507 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003508 return ImplicitConversionSequence::Indistinguishable;
3509
3510 if (SCS1.Third == SCS2.Third) {
3511 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3512 : ImplicitConversionSequence::Indistinguishable;
3513 }
3514
3515 if (SCS1.Third == ICK_Identity)
3516 return Result == ImplicitConversionSequence::Worse
3517 ? ImplicitConversionSequence::Indistinguishable
3518 : ImplicitConversionSequence::Better;
3519
3520 if (SCS2.Third == ICK_Identity)
3521 return Result == ImplicitConversionSequence::Better
3522 ? ImplicitConversionSequence::Indistinguishable
3523 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003525 return ImplicitConversionSequence::Indistinguishable;
3526}
3527
Douglas Gregore696ebb2011-01-26 14:52:12 +00003528/// \brief Determine whether one of the given reference bindings is better
3529/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003530static bool
3531isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3532 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003533 // C++0x [over.ics.rank]p3b4:
3534 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3535 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003537 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003539 // reference*.
3540 //
3541 // FIXME: Rvalue references. We're going rogue with the above edits,
3542 // because the semantics in the current C++0x working paper (N3225 at the
3543 // time of this writing) break the standard definition of std::forward
3544 // and std::reference_wrapper when dealing with references to functions.
3545 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003546 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3547 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3548 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549
Douglas Gregore696ebb2011-01-26 14:52:12 +00003550 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3551 SCS2.IsLvalueReference) ||
3552 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003553 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003554}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003556/// CompareStandardConversionSequences - Compare two standard
3557/// conversion sequences to determine whether one is better than the
3558/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003559static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003560CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003561 const StandardConversionSequence& SCS1,
3562 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003563{
3564 // Standard conversion sequence S1 is a better conversion sequence
3565 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3566
3567 // -- S1 is a proper subsequence of S2 (comparing the conversion
3568 // sequences in the canonical form defined by 13.3.3.1.1,
3569 // excluding any Lvalue Transformation; the identity conversion
3570 // sequence is considered to be a subsequence of any
3571 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003572 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003573 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003574 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003575
3576 // -- the rank of S1 is better than the rank of S2 (by the rules
3577 // defined below), or, if not that,
3578 ImplicitConversionRank Rank1 = SCS1.getRank();
3579 ImplicitConversionRank Rank2 = SCS2.getRank();
3580 if (Rank1 < Rank2)
3581 return ImplicitConversionSequence::Better;
3582 else if (Rank2 < Rank1)
3583 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003584
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003585 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3586 // are indistinguishable unless one of the following rules
3587 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003588
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003589 // A conversion that is not a conversion of a pointer, or
3590 // pointer to member, to bool is better than another conversion
3591 // that is such a conversion.
3592 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3593 return SCS2.isPointerConversionToBool()
3594 ? ImplicitConversionSequence::Better
3595 : ImplicitConversionSequence::Worse;
3596
Douglas Gregor5c407d92008-10-23 00:40:37 +00003597 // C++ [over.ics.rank]p4b2:
3598 //
3599 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003600 // conversion of B* to A* is better than conversion of B* to
3601 // void*, and conversion of A* to void* is better than conversion
3602 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003603 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003604 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003605 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003606 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003607 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3608 // Exactly one of the conversion sequences is a conversion to
3609 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003610 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3611 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003612 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3613 // Neither conversion sequence converts to a void pointer; compare
3614 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003615 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003616 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003617 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003618 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3619 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003620 // Both conversion sequences are conversions to void
3621 // pointers. Compare the source types to determine if there's an
3622 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003623 QualType FromType1 = SCS1.getFromType();
3624 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003625
3626 // Adjust the types we're converting from via the array-to-pointer
3627 // conversion, if we need to.
3628 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003629 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003630 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003631 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003632
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003633 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3634 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003635
Richard Smith0f59cb32015-12-18 21:45:41 +00003636 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003637 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003638 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003639 return ImplicitConversionSequence::Worse;
3640
3641 // Objective-C++: If one interface is more specific than the
3642 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003643 const ObjCObjectPointerType* FromObjCPtr1
3644 = FromType1->getAs<ObjCObjectPointerType>();
3645 const ObjCObjectPointerType* FromObjCPtr2
3646 = FromType2->getAs<ObjCObjectPointerType>();
3647 if (FromObjCPtr1 && FromObjCPtr2) {
3648 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3649 FromObjCPtr2);
3650 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3651 FromObjCPtr1);
3652 if (AssignLeft != AssignRight) {
3653 return AssignLeft? ImplicitConversionSequence::Better
3654 : ImplicitConversionSequence::Worse;
3655 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003656 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003657 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003658
3659 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3660 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003661 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003662 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003663 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003664
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003665 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003666 // Check for a better reference binding based on the kind of bindings.
3667 if (isBetterReferenceBindingKind(SCS1, SCS2))
3668 return ImplicitConversionSequence::Better;
3669 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3670 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Sebastian Redlb28b4072009-03-22 23:49:27 +00003672 // C++ [over.ics.rank]p3b4:
3673 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3674 // which the references refer are the same type except for
3675 // top-level cv-qualifiers, and the type to which the reference
3676 // initialized by S2 refers is more cv-qualified than the type
3677 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003678 QualType T1 = SCS1.getToType(2);
3679 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003680 T1 = S.Context.getCanonicalType(T1);
3681 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003682 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003683 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3684 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003685 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003686 // Objective-C++ ARC: If the references refer to objects with different
3687 // lifetimes, prefer bindings that don't change lifetime.
3688 if (SCS1.ObjCLifetimeConversionBinding !=
3689 SCS2.ObjCLifetimeConversionBinding) {
3690 return SCS1.ObjCLifetimeConversionBinding
3691 ? ImplicitConversionSequence::Worse
3692 : ImplicitConversionSequence::Better;
3693 }
3694
Chandler Carruth8e543b32010-12-12 08:17:55 +00003695 // If the type is an array type, promote the element qualifiers to the
3696 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003697 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003698 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003699 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003700 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003701 if (T2.isMoreQualifiedThan(T1))
3702 return ImplicitConversionSequence::Better;
3703 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003704 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003705 }
3706 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003707
Francois Pichet08d2fa02011-09-18 21:37:37 +00003708 // In Microsoft mode, prefer an integral conversion to a
3709 // floating-to-integral conversion if the integral conversion
3710 // is between types of the same size.
3711 // For example:
3712 // void f(float);
3713 // void f(int);
3714 // int main {
3715 // long a;
3716 // f(a);
3717 // }
3718 // Here, MSVC will call f(int) instead of generating a compile error
3719 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003720 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3721 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003722 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003723 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003724 return ImplicitConversionSequence::Better;
3725
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003726 return ImplicitConversionSequence::Indistinguishable;
3727}
3728
3729/// CompareQualificationConversions - Compares two standard conversion
3730/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003731/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003732static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003733CompareQualificationConversions(Sema &S,
3734 const StandardConversionSequence& SCS1,
3735 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003736 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003737 // -- S1 and S2 differ only in their qualification conversion and
3738 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3739 // cv-qualification signature of type T1 is a proper subset of
3740 // the cv-qualification signature of type T2, and S1 is not the
3741 // deprecated string literal array-to-pointer conversion (4.2).
3742 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3743 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3744 return ImplicitConversionSequence::Indistinguishable;
3745
3746 // FIXME: the example in the standard doesn't use a qualification
3747 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003748 QualType T1 = SCS1.getToType(2);
3749 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003750 T1 = S.Context.getCanonicalType(T1);
3751 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003752 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003753 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3754 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003755
3756 // If the types are the same, we won't learn anything by unwrapped
3757 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003758 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003759 return ImplicitConversionSequence::Indistinguishable;
3760
Chandler Carruth607f38e2009-12-29 07:16:59 +00003761 // If the type is an array type, promote the element qualifiers to the type
3762 // for comparison.
3763 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003764 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003765 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003766 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003767
Mike Stump11289f42009-09-09 15:08:12 +00003768 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003769 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003770
3771 // Objective-C++ ARC:
3772 // Prefer qualification conversions not involving a change in lifetime
3773 // to qualification conversions that do not change lifetime.
3774 if (SCS1.QualificationIncludesObjCLifetime !=
3775 SCS2.QualificationIncludesObjCLifetime) {
3776 Result = SCS1.QualificationIncludesObjCLifetime
3777 ? ImplicitConversionSequence::Worse
3778 : ImplicitConversionSequence::Better;
3779 }
3780
John McCall5c32be02010-08-24 20:38:10 +00003781 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003782 // Within each iteration of the loop, we check the qualifiers to
3783 // determine if this still looks like a qualification
3784 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003785 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003786 // until there are no more pointers or pointers-to-members left
3787 // to unwrap. This essentially mimics what
3788 // IsQualificationConversion does, but here we're checking for a
3789 // strict subset of qualifiers.
3790 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3791 // The qualifiers are the same, so this doesn't tell us anything
3792 // about how the sequences rank.
3793 ;
3794 else if (T2.isMoreQualifiedThan(T1)) {
3795 // T1 has fewer qualifiers, so it could be the better sequence.
3796 if (Result == ImplicitConversionSequence::Worse)
3797 // Neither has qualifiers that are a subset of the other's
3798 // qualifiers.
3799 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003800
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003801 Result = ImplicitConversionSequence::Better;
3802 } else if (T1.isMoreQualifiedThan(T2)) {
3803 // T2 has fewer qualifiers, so it could be the better sequence.
3804 if (Result == ImplicitConversionSequence::Better)
3805 // Neither has qualifiers that are a subset of the other's
3806 // qualifiers.
3807 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003808
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003809 Result = ImplicitConversionSequence::Worse;
3810 } else {
3811 // Qualifiers are disjoint.
3812 return ImplicitConversionSequence::Indistinguishable;
3813 }
3814
3815 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003816 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003817 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003818 }
3819
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003820 // Check that the winning standard conversion sequence isn't using
3821 // the deprecated string literal array to pointer conversion.
3822 switch (Result) {
3823 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003824 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003825 Result = ImplicitConversionSequence::Indistinguishable;
3826 break;
3827
3828 case ImplicitConversionSequence::Indistinguishable:
3829 break;
3830
3831 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003832 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003833 Result = ImplicitConversionSequence::Indistinguishable;
3834 break;
3835 }
3836
3837 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003838}
3839
Douglas Gregor5c407d92008-10-23 00:40:37 +00003840/// CompareDerivedToBaseConversions - Compares two standard conversion
3841/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003842/// various kinds of derived-to-base conversions (C++
3843/// [over.ics.rank]p4b3). As part of these checks, we also look at
3844/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003845static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003846CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003847 const StandardConversionSequence& SCS1,
3848 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003849 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003850 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003851 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003852 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003853
3854 // Adjust the types we're converting from via the array-to-pointer
3855 // conversion, if we need to.
3856 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003857 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003858 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003859 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003860
3861 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003862 FromType1 = S.Context.getCanonicalType(FromType1);
3863 ToType1 = S.Context.getCanonicalType(ToType1);
3864 FromType2 = S.Context.getCanonicalType(FromType2);
3865 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003866
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003867 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003868 //
3869 // If class B is derived directly or indirectly from class A and
3870 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003871 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003872 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003873 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003874 SCS2.Second == ICK_Pointer_Conversion &&
3875 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3876 FromType1->isPointerType() && FromType2->isPointerType() &&
3877 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003878 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003879 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003880 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003881 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003882 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003883 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003884 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003885 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003886
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003887 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003888 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003889 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003890 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003891 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003892 return ImplicitConversionSequence::Worse;
3893 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003894
3895 // -- conversion of B* to A* is better than conversion of C* to A*,
3896 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003897 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003898 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003899 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003900 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003901 }
3902 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3903 SCS2.Second == ICK_Pointer_Conversion) {
3904 const ObjCObjectPointerType *FromPtr1
3905 = FromType1->getAs<ObjCObjectPointerType>();
3906 const ObjCObjectPointerType *FromPtr2
3907 = FromType2->getAs<ObjCObjectPointerType>();
3908 const ObjCObjectPointerType *ToPtr1
3909 = ToType1->getAs<ObjCObjectPointerType>();
3910 const ObjCObjectPointerType *ToPtr2
3911 = ToType2->getAs<ObjCObjectPointerType>();
3912
3913 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3914 // Apply the same conversion ranking rules for Objective-C pointer types
3915 // that we do for C++ pointers to class types. However, we employ the
3916 // Objective-C pseudo-subtyping relationship used for assignment of
3917 // Objective-C pointer types.
3918 bool FromAssignLeft
3919 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3920 bool FromAssignRight
3921 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3922 bool ToAssignLeft
3923 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3924 bool ToAssignRight
3925 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3926
3927 // A conversion to an a non-id object pointer type or qualified 'id'
3928 // type is better than a conversion to 'id'.
3929 if (ToPtr1->isObjCIdType() &&
3930 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3931 return ImplicitConversionSequence::Worse;
3932 if (ToPtr2->isObjCIdType() &&
3933 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3934 return ImplicitConversionSequence::Better;
3935
3936 // A conversion to a non-id object pointer type is better than a
3937 // conversion to a qualified 'id' type
3938 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3939 return ImplicitConversionSequence::Worse;
3940 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3941 return ImplicitConversionSequence::Better;
3942
3943 // A conversion to an a non-Class object pointer type or qualified 'Class'
3944 // type is better than a conversion to 'Class'.
3945 if (ToPtr1->isObjCClassType() &&
3946 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3947 return ImplicitConversionSequence::Worse;
3948 if (ToPtr2->isObjCClassType() &&
3949 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3950 return ImplicitConversionSequence::Better;
3951
3952 // A conversion to a non-Class object pointer type is better than a
3953 // conversion to a qualified 'Class' type.
3954 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3955 return ImplicitConversionSequence::Worse;
3956 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3957 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003958
Douglas Gregor058d3de2011-01-31 18:51:41 +00003959 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3960 if (S.Context.hasSameType(FromType1, FromType2) &&
3961 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3962 (ToAssignLeft != ToAssignRight))
3963 return ToAssignLeft? ImplicitConversionSequence::Worse
3964 : ImplicitConversionSequence::Better;
3965
3966 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3967 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3968 (FromAssignLeft != FromAssignRight))
3969 return FromAssignLeft? ImplicitConversionSequence::Better
3970 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003971 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003972 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003973
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003974 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003975 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3976 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3977 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003978 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003979 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003980 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003981 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003982 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003983 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003984 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003985 ToType2->getAs<MemberPointerType>();
3986 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3987 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3988 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3989 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3990 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3991 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3992 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3993 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003994 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003995 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003996 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003997 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00003998 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003999 return ImplicitConversionSequence::Better;
4000 }
4001 // conversion of B::* to C::* is better than conversion of A::* to C::*
4002 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004003 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004004 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004005 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004006 return ImplicitConversionSequence::Worse;
4007 }
4008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004009
Douglas Gregor5ab11652010-04-17 22:01:05 +00004010 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004011 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004012 // -- binding of an expression of type C to a reference of type
4013 // B& is better than binding an expression of type C to a
4014 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004015 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4016 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004017 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004018 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004019 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004020 return ImplicitConversionSequence::Worse;
4021 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004022
Douglas Gregor2fe98832008-11-03 19:09:14 +00004023 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004024 // -- binding of an expression of type B to a reference of type
4025 // A& is better than binding an expression of type C to a
4026 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004027 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4028 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004029 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004030 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004031 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004032 return ImplicitConversionSequence::Worse;
4033 }
4034 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004035
Douglas Gregor5c407d92008-10-23 00:40:37 +00004036 return ImplicitConversionSequence::Indistinguishable;
4037}
4038
Douglas Gregor45bb4832013-03-26 23:36:30 +00004039/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4040/// C++ class.
4041static bool isTypeValid(QualType T) {
4042 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4043 return !Record->isInvalidDecl();
4044
4045 return true;
4046}
4047
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004048/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4049/// determine whether they are reference-related,
4050/// reference-compatible, reference-compatible with added
4051/// qualification, or incompatible, for use in C++ initialization by
4052/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4053/// type, and the first type (T1) is the pointee type of the reference
4054/// type being initialized.
4055Sema::ReferenceCompareResult
4056Sema::CompareReferenceRelationship(SourceLocation Loc,
4057 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004058 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004059 bool &ObjCConversion,
4060 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004061 assert(!OrigT1->isReferenceType() &&
4062 "T1 must be the pointee type of the reference type");
4063 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4064
4065 QualType T1 = Context.getCanonicalType(OrigT1);
4066 QualType T2 = Context.getCanonicalType(OrigT2);
4067 Qualifiers T1Quals, T2Quals;
4068 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4069 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4070
4071 // C++ [dcl.init.ref]p4:
4072 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4073 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4074 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004075 DerivedToBase = false;
4076 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004077 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004078 if (UnqualT1 == UnqualT2) {
4079 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004080 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004081 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004082 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004083 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004084 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4085 UnqualT2->isObjCObjectOrInterfaceType() &&
4086 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4087 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004088 else
4089 return Ref_Incompatible;
4090
4091 // At this point, we know that T1 and T2 are reference-related (at
4092 // least).
4093
4094 // If the type is an array type, promote the element qualifiers to the type
4095 // for comparison.
4096 if (isa<ArrayType>(T1) && T1Quals)
4097 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4098 if (isa<ArrayType>(T2) && T2Quals)
4099 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4100
4101 // C++ [dcl.init.ref]p4:
4102 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4103 // reference-related to T2 and cv1 is the same cv-qualification
4104 // as, or greater cv-qualification than, cv2. For purposes of
4105 // overload resolution, cases for which cv1 is greater
4106 // cv-qualification than cv2 are identified as
4107 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004108 //
4109 // Note that we also require equivalence of Objective-C GC and address-space
4110 // qualifiers when performing these computations, so that e.g., an int in
4111 // address space 1 is not reference-compatible with an int in address
4112 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004113 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4114 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004115 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4116 ObjCLifetimeConversion = true;
4117
John McCall31168b02011-06-15 23:02:42 +00004118 T1Quals.removeObjCLifetime();
4119 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004120 }
4121
Douglas Gregord517d552011-04-28 17:56:11 +00004122 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004123 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004124 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004125 return Ref_Compatible_With_Added_Qualification;
4126 else
4127 return Ref_Related;
4128}
4129
Douglas Gregor836a7e82010-08-11 02:15:33 +00004130/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004131/// with DeclType. Return true if something definite is found.
4132static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004133FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4134 QualType DeclType, SourceLocation DeclLoc,
4135 Expr *Init, QualType T2, bool AllowRvalues,
4136 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004137 assert(T2->isRecordType() && "Can only find conversions of record types.");
4138 CXXRecordDecl *T2RecordDecl
4139 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4140
Richard Smith100b24a2014-04-17 01:52:14 +00004141 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004142 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4143 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004144 NamedDecl *D = *I;
4145 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4146 if (isa<UsingShadowDecl>(D))
4147 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4148
4149 FunctionTemplateDecl *ConvTemplate
4150 = dyn_cast<FunctionTemplateDecl>(D);
4151 CXXConversionDecl *Conv;
4152 if (ConvTemplate)
4153 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4154 else
4155 Conv = cast<CXXConversionDecl>(D);
4156
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004157 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004158 // explicit conversions, skip it.
4159 if (!AllowExplicit && Conv->isExplicit())
4160 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161
Douglas Gregor836a7e82010-08-11 02:15:33 +00004162 if (AllowRvalues) {
4163 bool DerivedToBase = false;
4164 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004165 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004166
4167 // If we are initializing an rvalue reference, don't permit conversion
4168 // functions that return lvalues.
4169 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4170 const ReferenceType *RefType
4171 = Conv->getConversionType()->getAs<LValueReferenceType>();
4172 if (RefType && !RefType->getPointeeType()->isFunctionType())
4173 continue;
4174 }
4175
Douglas Gregor836a7e82010-08-11 02:15:33 +00004176 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004177 S.CompareReferenceRelationship(
4178 DeclLoc,
4179 Conv->getConversionType().getNonReferenceType()
4180 .getUnqualifiedType(),
4181 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004182 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004183 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004184 continue;
4185 } else {
4186 // If the conversion function doesn't return a reference type,
4187 // it can't be considered for this conversion. An rvalue reference
4188 // is only acceptable if its referencee is a function type.
4189
4190 const ReferenceType *RefType =
4191 Conv->getConversionType()->getAs<ReferenceType>();
4192 if (!RefType ||
4193 (!RefType->isLValueReferenceType() &&
4194 !RefType->getPointeeType()->isFunctionType()))
4195 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197
Douglas Gregor836a7e82010-08-11 02:15:33 +00004198 if (ConvTemplate)
4199 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004200 Init, DeclType, CandidateSet,
4201 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004202 else
4203 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004204 DeclType, CandidateSet,
4205 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004206 }
4207
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004208 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4209
Sebastian Redld92badf2010-06-30 18:13:39 +00004210 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004211 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004212 case OR_Success:
4213 // C++ [over.ics.ref]p1:
4214 //
4215 // [...] If the parameter binds directly to the result of
4216 // applying a conversion function to the argument
4217 // expression, the implicit conversion sequence is a
4218 // user-defined conversion sequence (13.3.3.1.2), with the
4219 // second standard conversion sequence either an identity
4220 // conversion or, if the conversion function returns an
4221 // entity of a type that is a derived class of the parameter
4222 // type, a derived-to-base Conversion.
4223 if (!Best->FinalConversion.DirectBinding)
4224 return false;
4225
4226 ICS.setUserDefined();
4227 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4228 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004229 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004230 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004231 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004232 ICS.UserDefined.EllipsisConversion = false;
4233 assert(ICS.UserDefined.After.ReferenceBinding &&
4234 ICS.UserDefined.After.DirectBinding &&
4235 "Expected a direct reference binding!");
4236 return true;
4237
4238 case OR_Ambiguous:
4239 ICS.setAmbiguous();
4240 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4241 Cand != CandidateSet.end(); ++Cand)
4242 if (Cand->Viable)
4243 ICS.Ambiguous.addConversion(Cand->Function);
4244 return true;
4245
4246 case OR_No_Viable_Function:
4247 case OR_Deleted:
4248 // There was no suitable conversion, or we found a deleted
4249 // conversion; continue with other checks.
4250 return false;
4251 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252
David Blaikie8a40f702012-01-17 06:56:22 +00004253 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004254}
4255
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004256/// \brief Compute an implicit conversion sequence for reference
4257/// initialization.
4258static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004259TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004260 SourceLocation DeclLoc,
4261 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004262 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004263 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4264
4265 // Most paths end in a failed conversion.
4266 ImplicitConversionSequence ICS;
4267 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4268
4269 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4270 QualType T2 = Init->getType();
4271
4272 // If the initializer is the address of an overloaded function, try
4273 // to resolve the overloaded function. If all goes well, T2 is the
4274 // type of the resulting function.
4275 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4276 DeclAccessPair Found;
4277 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4278 false, Found))
4279 T2 = Fn->getType();
4280 }
4281
4282 // Compute some basic properties of the types and the initializer.
4283 bool isRValRef = DeclType->isRValueReferenceType();
4284 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004285 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004286 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004287 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004288 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004289 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004290 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004291
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004292
Sebastian Redld92badf2010-06-30 18:13:39 +00004293 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004294 // A reference to type "cv1 T1" is initialized by an expression
4295 // of type "cv2 T2" as follows:
4296
Sebastian Redld92badf2010-06-30 18:13:39 +00004297 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004298 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004299 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4300 // reference-compatible with "cv2 T2," or
4301 //
4302 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4303 if (InitCategory.isLValue() &&
4304 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004305 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004306 // When a parameter of reference type binds directly (8.5.3)
4307 // to an argument expression, the implicit conversion sequence
4308 // is the identity conversion, unless the argument expression
4309 // has a type that is a derived class of the parameter type,
4310 // in which case the implicit conversion sequence is a
4311 // derived-to-base Conversion (13.3.3.1).
4312 ICS.setStandard();
4313 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004314 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4315 : ObjCConversion? ICK_Compatible_Conversion
4316 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004317 ICS.Standard.Third = ICK_Identity;
4318 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4319 ICS.Standard.setToType(0, T2);
4320 ICS.Standard.setToType(1, T1);
4321 ICS.Standard.setToType(2, T1);
4322 ICS.Standard.ReferenceBinding = true;
4323 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004324 ICS.Standard.IsLvalueReference = !isRValRef;
4325 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4326 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004327 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004328 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004329 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004330 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004331
Sebastian Redld92badf2010-06-30 18:13:39 +00004332 // Nothing more to do: the inaccessibility/ambiguity check for
4333 // derived-to-base conversions is suppressed when we're
4334 // computing the implicit conversion sequence (C++
4335 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004336 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004337 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004338
Sebastian Redld92badf2010-06-30 18:13:39 +00004339 // -- has a class type (i.e., T2 is a class type), where T1 is
4340 // not reference-related to T2, and can be implicitly
4341 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4342 // is reference-compatible with "cv3 T3" 92) (this
4343 // conversion is selected by enumerating the applicable
4344 // conversion functions (13.3.1.6) and choosing the best
4345 // one through overload resolution (13.3)),
4346 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004347 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004348 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004349 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4350 Init, T2, /*AllowRvalues=*/false,
4351 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004352 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004353 }
4354 }
4355
Sebastian Redld92badf2010-06-30 18:13:39 +00004356 // -- Otherwise, the reference shall be an lvalue reference to a
4357 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004358 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004359 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004360 return ICS;
4361
Douglas Gregorf143cd52011-01-24 16:14:37 +00004362 // -- If the initializer expression
4363 //
4364 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004365 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004366 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4367 (InitCategory.isXValue() ||
4368 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4369 (InitCategory.isLValue() && T2->isFunctionType()))) {
4370 ICS.setStandard();
4371 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004373 : ObjCConversion? ICK_Compatible_Conversion
4374 : ICK_Identity;
4375 ICS.Standard.Third = ICK_Identity;
4376 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4377 ICS.Standard.setToType(0, T2);
4378 ICS.Standard.setToType(1, T1);
4379 ICS.Standard.setToType(2, T1);
4380 ICS.Standard.ReferenceBinding = true;
4381 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4382 // binding unless we're binding to a class prvalue.
4383 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4384 // allow the use of rvalue references in C++98/03 for the benefit of
4385 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004386 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004387 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004388 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004389 ICS.Standard.IsLvalueReference = !isRValRef;
4390 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004392 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004393 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004394 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004395 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398
Douglas Gregorf143cd52011-01-24 16:14:37 +00004399 // -- has a class type (i.e., T2 is a class type), where T1 is not
4400 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401 // an xvalue, class prvalue, or function lvalue of type
4402 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004403 // "cv3 T3",
4404 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004406 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004408 // class subobject).
4409 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004410 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004411 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4412 Init, T2, /*AllowRvalues=*/true,
4413 AllowExplicit)) {
4414 // In the second case, if the reference is an rvalue reference
4415 // and the second standard conversion sequence of the
4416 // user-defined conversion sequence includes an lvalue-to-rvalue
4417 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004419 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4420 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4421
Douglas Gregor95273c32011-01-21 16:36:05 +00004422 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424
Richard Smith19172c42014-07-14 02:28:44 +00004425 // A temporary of function type cannot be created; don't even try.
4426 if (T1->isFunctionType())
4427 return ICS;
4428
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004429 // -- Otherwise, a temporary of type "cv1 T1" is created and
4430 // initialized from the initializer expression using the
4431 // rules for a non-reference copy initialization (8.5). The
4432 // reference is then bound to the temporary. If T1 is
4433 // reference-related to T2, cv1 must be the same
4434 // cv-qualification as, or greater cv-qualification than,
4435 // cv2; otherwise, the program is ill-formed.
4436 if (RefRelationship == Sema::Ref_Related) {
4437 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4438 // we would be reference-compatible or reference-compatible with
4439 // added qualification. But that wasn't the case, so the reference
4440 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004441 //
4442 // Note that we only want to check address spaces and cvr-qualifiers here.
4443 // ObjC GC and lifetime qualifiers aren't important.
4444 Qualifiers T1Quals = T1.getQualifiers();
4445 Qualifiers T2Quals = T2.getQualifiers();
4446 T1Quals.removeObjCGCAttr();
4447 T1Quals.removeObjCLifetime();
4448 T2Quals.removeObjCGCAttr();
4449 T2Quals.removeObjCLifetime();
4450 if (!T1Quals.compatiblyIncludes(T2Quals))
4451 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004452 }
4453
4454 // If at least one of the types is a class type, the types are not
4455 // related, and we aren't allowed any user conversions, the
4456 // reference binding fails. This case is important for breaking
4457 // recursion, since TryImplicitConversion below will attempt to
4458 // create a temporary through the use of a copy constructor.
4459 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4460 (T1->isRecordType() || T2->isRecordType()))
4461 return ICS;
4462
Douglas Gregorcba72b12011-01-21 05:18:22 +00004463 // If T1 is reference-related to T2 and the reference is an rvalue
4464 // reference, the initializer expression shall not be an lvalue.
4465 if (RefRelationship >= Sema::Ref_Related &&
4466 isRValRef && Init->Classify(S.Context).isLValue())
4467 return ICS;
4468
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004469 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004470 // When a parameter of reference type is not bound directly to
4471 // an argument expression, the conversion sequence is the one
4472 // required to convert the argument expression to the
4473 // underlying type of the reference according to
4474 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4475 // to copy-initializing a temporary of the underlying type with
4476 // the argument expression. Any difference in top-level
4477 // cv-qualification is subsumed by the initialization itself
4478 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004479 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4480 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004481 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004482 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004483 /*AllowObjCWritebackConversion=*/false,
4484 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004485
4486 // Of course, that's still a reference binding.
4487 if (ICS.isStandard()) {
4488 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004489 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004490 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004491 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004492 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004493 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004494 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004495 const ReferenceType *LValRefType =
4496 ICS.UserDefined.ConversionFunction->getReturnType()
4497 ->getAs<LValueReferenceType>();
4498
4499 // C++ [over.ics.ref]p3:
4500 // Except for an implicit object parameter, for which see 13.3.1, a
4501 // standard conversion sequence cannot be formed if it requires [...]
4502 // binding an rvalue reference to an lvalue other than a function
4503 // lvalue.
4504 // Note that the function case is not possible here.
4505 if (DeclType->isRValueReferenceType() && LValRefType) {
4506 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4507 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4508 // reference to an rvalue!
4509 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4510 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004511 }
Richard Smith19172c42014-07-14 02:28:44 +00004512
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004513 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004514 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004515 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004516 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4517 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004518 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4519 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004520 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004521
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004522 return ICS;
4523}
4524
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004525static ImplicitConversionSequence
4526TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4527 bool SuppressUserConversions,
4528 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004529 bool AllowObjCWritebackConversion,
4530 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004531
4532/// TryListConversion - Try to copy-initialize a value of type ToType from the
4533/// initializer list From.
4534static ImplicitConversionSequence
4535TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4536 bool SuppressUserConversions,
4537 bool InOverloadResolution,
4538 bool AllowObjCWritebackConversion) {
4539 // C++11 [over.ics.list]p1:
4540 // When an argument is an initializer list, it is not an expression and
4541 // special rules apply for converting it to a parameter type.
4542
4543 ImplicitConversionSequence Result;
4544 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4545
Sebastian Redl09edce02012-01-23 22:09:39 +00004546 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004547 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004548 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004549 return Result;
4550
Larisse Voufo19d08672015-01-27 18:47:05 +00004551 // Per DR1467:
4552 // If the parameter type is a class X and the initializer list has a single
4553 // element of type cv U, where U is X or a class derived from X, the
4554 // implicit conversion sequence is the one required to convert the element
4555 // to the parameter type.
4556 //
4557 // Otherwise, if the parameter type is a character array [... ]
4558 // and the initializer list has a single element that is an
4559 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4560 // implicit conversion sequence is the identity conversion.
4561 if (From->getNumInits() == 1) {
4562 if (ToType->isRecordType()) {
4563 QualType InitType = From->getInit(0)->getType();
4564 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004565 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004566 return TryCopyInitialization(S, From->getInit(0), ToType,
4567 SuppressUserConversions,
4568 InOverloadResolution,
4569 AllowObjCWritebackConversion);
4570 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004571 // FIXME: Check the other conditions here: array of character type,
4572 // initializer is a string literal.
4573 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004574 InitializedEntity Entity =
4575 InitializedEntity::InitializeParameter(S.Context, ToType,
4576 /*Consumed=*/false);
4577 if (S.CanPerformCopyInitialization(Entity, From)) {
4578 Result.setStandard();
4579 Result.Standard.setAsIdentityConversion();
4580 Result.Standard.setFromType(ToType);
4581 Result.Standard.setAllToTypes(ToType);
4582 return Result;
4583 }
4584 }
4585 }
4586
4587 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004588 // C++11 [over.ics.list]p2:
4589 // If the parameter type is std::initializer_list<X> or "array of X" and
4590 // all the elements can be implicitly converted to X, the implicit
4591 // conversion sequence is the worst conversion necessary to convert an
4592 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004593 //
4594 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004595 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004596 // list has exactly N elements or if it has fewer than N elements and X is
4597 // default-constructible, and if all the elements of the initializer list
4598 // can be implicitly converted to X, the implicit conversion sequence is
4599 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004600 //
4601 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004602 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004603 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004604 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004605 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004606 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004607 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004608 if (!X.isNull()) {
4609 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4610 Expr *Init = From->getInit(i);
4611 ImplicitConversionSequence ICS =
4612 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4613 InOverloadResolution,
4614 AllowObjCWritebackConversion);
4615 // If a single element isn't convertible, fail.
4616 if (ICS.isBad()) {
4617 Result = ICS;
4618 break;
4619 }
4620 // Otherwise, look for the worst conversion.
4621 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004622 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4623 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004624 ImplicitConversionSequence::Worse)
4625 Result = ICS;
4626 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004627
4628 // For an empty list, we won't have computed any conversion sequence.
4629 // Introduce the identity conversion sequence.
4630 if (From->getNumInits() == 0) {
4631 Result.setStandard();
4632 Result.Standard.setAsIdentityConversion();
4633 Result.Standard.setFromType(ToType);
4634 Result.Standard.setAllToTypes(ToType);
4635 }
4636
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004637 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004638 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004639 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004640
Larisse Voufo19d08672015-01-27 18:47:05 +00004641 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004642 // C++11 [over.ics.list]p3:
4643 // Otherwise, if the parameter is a non-aggregate class X and overload
4644 // resolution chooses a single best constructor [...] the implicit
4645 // conversion sequence is a user-defined conversion sequence. If multiple
4646 // constructors are viable but none is better than the others, the
4647 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004648 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4649 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004650 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4651 /*AllowExplicit=*/false,
4652 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004653 AllowObjCWritebackConversion,
4654 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004655 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004656
Larisse Voufo19d08672015-01-27 18:47:05 +00004657 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004658 // C++11 [over.ics.list]p4:
4659 // Otherwise, if the parameter has an aggregate type which can be
4660 // initialized from the initializer list [...] the implicit conversion
4661 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004662 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004663 // Type is an aggregate, argument is an init list. At this point it comes
4664 // down to checking whether the initialization works.
4665 // FIXME: Find out whether this parameter is consumed or not.
4666 InitializedEntity Entity =
4667 InitializedEntity::InitializeParameter(S.Context, ToType,
4668 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004669 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004670 Result.setUserDefined();
4671 Result.UserDefined.Before.setAsIdentityConversion();
4672 // Initializer lists don't have a type.
4673 Result.UserDefined.Before.setFromType(QualType());
4674 Result.UserDefined.Before.setAllToTypes(QualType());
4675
4676 Result.UserDefined.After.setAsIdentityConversion();
4677 Result.UserDefined.After.setFromType(ToType);
4678 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004679 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004680 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004681 return Result;
4682 }
4683
Larisse Voufo19d08672015-01-27 18:47:05 +00004684 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004685 // C++11 [over.ics.list]p5:
4686 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004687 if (ToType->isReferenceType()) {
4688 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4689 // mention initializer lists in any way. So we go by what list-
4690 // initialization would do and try to extrapolate from that.
4691
4692 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4693
4694 // If the initializer list has a single element that is reference-related
4695 // to the parameter type, we initialize the reference from that.
4696 if (From->getNumInits() == 1) {
4697 Expr *Init = From->getInit(0);
4698
4699 QualType T2 = Init->getType();
4700
4701 // If the initializer is the address of an overloaded function, try
4702 // to resolve the overloaded function. If all goes well, T2 is the
4703 // type of the resulting function.
4704 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4705 DeclAccessPair Found;
4706 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4707 Init, ToType, false, Found))
4708 T2 = Fn->getType();
4709 }
4710
4711 // Compute some basic properties of the types and the initializer.
4712 bool dummy1 = false;
4713 bool dummy2 = false;
4714 bool dummy3 = false;
4715 Sema::ReferenceCompareResult RefRelationship
4716 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4717 dummy2, dummy3);
4718
Richard Smith4d2bbd72013-09-06 01:22:42 +00004719 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004720 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4721 SuppressUserConversions,
4722 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004723 }
Sebastian Redldf888642011-12-03 14:54:30 +00004724 }
4725
4726 // Otherwise, we bind the reference to a temporary created from the
4727 // initializer list.
4728 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4729 InOverloadResolution,
4730 AllowObjCWritebackConversion);
4731 if (Result.isFailure())
4732 return Result;
4733 assert(!Result.isEllipsis() &&
4734 "Sub-initialization cannot result in ellipsis conversion.");
4735
4736 // Can we even bind to a temporary?
4737 if (ToType->isRValueReferenceType() ||
4738 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4739 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4740 Result.UserDefined.After;
4741 SCS.ReferenceBinding = true;
4742 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4743 SCS.BindsToRvalue = true;
4744 SCS.BindsToFunctionLvalue = false;
4745 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4746 SCS.ObjCLifetimeConversionBinding = false;
4747 } else
4748 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4749 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004750 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004751 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004752
Larisse Voufo19d08672015-01-27 18:47:05 +00004753 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004754 // C++11 [over.ics.list]p6:
4755 // Otherwise, if the parameter type is not a class:
4756 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004757 // - if the initializer list has one element that is not itself an
4758 // initializer list, the implicit conversion sequence is the one
4759 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004760 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004761 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004762 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4763 SuppressUserConversions,
4764 InOverloadResolution,
4765 AllowObjCWritebackConversion);
4766 // - if the initializer list has no elements, the implicit conversion
4767 // sequence is the identity conversion.
4768 else if (NumInits == 0) {
4769 Result.setStandard();
4770 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004771 Result.Standard.setFromType(ToType);
4772 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004773 }
4774 return Result;
4775 }
4776
Larisse Voufo19d08672015-01-27 18:47:05 +00004777 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004778 // C++11 [over.ics.list]p7:
4779 // In all cases other than those enumerated above, no conversion is possible
4780 return Result;
4781}
4782
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004783/// TryCopyInitialization - Try to copy-initialize a value of type
4784/// ToType from the expression From. Return the implicit conversion
4785/// sequence required to pass this argument, which may be a bad
4786/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004787/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004788/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004789static ImplicitConversionSequence
4790TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004792 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004793 bool AllowObjCWritebackConversion,
4794 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004795 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4796 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4797 InOverloadResolution,AllowObjCWritebackConversion);
4798
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004799 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004800 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004801 /*FIXME:*/From->getLocStart(),
4802 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004803 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004804
John McCall5c32be02010-08-24 20:38:10 +00004805 return TryImplicitConversion(S, From, ToType,
4806 SuppressUserConversions,
4807 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004808 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004809 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004810 AllowObjCWritebackConversion,
4811 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004812}
4813
Anna Zaks1b068122011-07-28 19:46:48 +00004814static bool TryCopyInitialization(const CanQualType FromQTy,
4815 const CanQualType ToQTy,
4816 Sema &S,
4817 SourceLocation Loc,
4818 ExprValueKind FromVK) {
4819 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4820 ImplicitConversionSequence ICS =
4821 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4822
4823 return !ICS.isBad();
4824}
4825
Douglas Gregor436424c2008-11-18 23:14:02 +00004826/// TryObjectArgumentInitialization - Try to initialize the object
4827/// parameter of the given member function (@c Method) from the
4828/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004829static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004830TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004831 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004832 CXXMethodDecl *Method,
4833 CXXRecordDecl *ActingContext) {
4834 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004835 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4836 // const volatile object.
4837 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4838 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004839 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004840
4841 // Set up the conversion sequence as a "bad" conversion, to allow us
4842 // to exit early.
4843 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004844
4845 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004846 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004847 FromType = PT->getPointeeType();
4848
Douglas Gregor02824322011-01-26 19:30:28 +00004849 // When we had a pointer, it's implicitly dereferenced, so we
4850 // better have an lvalue.
4851 assert(FromClassification.isLValue());
4852 }
4853
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004854 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004855
Douglas Gregor02824322011-01-26 19:30:28 +00004856 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004857 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004858 // parameter is
4859 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004860 // - "lvalue reference to cv X" for functions declared without a
4861 // ref-qualifier or with the & ref-qualifier
4862 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004863 // ref-qualifier
4864 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004866 // cv-qualification on the member function declaration.
4867 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004869 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004870 // (C++ [over.match.funcs]p5). We perform a simplified version of
4871 // reference binding here, that allows class rvalues to bind to
4872 // non-constant references.
4873
Douglas Gregor02824322011-01-26 19:30:28 +00004874 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004875 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004877 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004878 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004879 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004880 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004881 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004882 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004883
4884 // Check that we have either the same type or a derived type. It
4885 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004886 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004887 ImplicitConversionKind SecondKind;
4888 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4889 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004890 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004891 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004892 else {
John McCall65eb8792010-02-25 01:37:24 +00004893 ICS.setBad(BadConversionSequence::unrelated_class,
4894 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004895 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004896 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004897
Douglas Gregor02824322011-01-26 19:30:28 +00004898 // Check the ref-qualifier.
4899 switch (Method->getRefQualifier()) {
4900 case RQ_None:
4901 // Do nothing; we don't care about lvalueness or rvalueness.
4902 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903
Douglas Gregor02824322011-01-26 19:30:28 +00004904 case RQ_LValue:
4905 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4906 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004907 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004908 ImplicitParamType);
4909 return ICS;
4910 }
4911 break;
4912
4913 case RQ_RValue:
4914 if (!FromClassification.isRValue()) {
4915 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004917 ImplicitParamType);
4918 return ICS;
4919 }
4920 break;
4921 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922
Douglas Gregor436424c2008-11-18 23:14:02 +00004923 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004924 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004925 ICS.Standard.setAsIdentityConversion();
4926 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004927 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004928 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004929 ICS.Standard.ReferenceBinding = true;
4930 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004932 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004933 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4934 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4935 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004936 return ICS;
4937}
4938
4939/// PerformObjectArgumentInitialization - Perform initialization of
4940/// the implicit object parameter for the given Method with the given
4941/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004942ExprResult
4943Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004945 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004946 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004947 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004948 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004949 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004950
Douglas Gregor02824322011-01-26 19:30:28 +00004951 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004952 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004953 FromRecordType = PT->getPointeeType();
4954 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004955 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004956 } else {
4957 FromRecordType = From->getType();
4958 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004959 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004960 }
4961
John McCall6e9f8f62009-12-03 04:06:58 +00004962 // Note that we always use the true parent context when performing
4963 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004964 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00004965 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4966 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004967 if (ICS.isBad()) {
4968 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4969 Qualifiers FromQs = FromRecordType.getQualifiers();
4970 Qualifiers ToQs = DestType.getQualifiers();
4971 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4972 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004973 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004974 diag::err_member_function_call_bad_cvr)
4975 << Method->getDeclName() << FromRecordType << (CVR - 1)
4976 << From->getSourceRange();
4977 Diag(Method->getLocation(), diag::note_previous_decl)
4978 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004979 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004980 }
4981 }
4982
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004983 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004984 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004985 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004986 }
Mike Stump11289f42009-09-09 15:08:12 +00004987
John Wiegley01296292011-04-08 18:41:53 +00004988 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4989 ExprResult FromRes =
4990 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4991 if (FromRes.isInvalid())
4992 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004993 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004994 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004995
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004996 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004997 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004998 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004999 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005000}
5001
Douglas Gregor5fb53972009-01-14 15:45:31 +00005002/// TryContextuallyConvertToBool - Attempt to contextually convert the
5003/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005004static ImplicitConversionSequence
5005TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005006 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005007 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005008 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005009 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005010 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005011 /*AllowObjCWritebackConversion=*/false,
5012 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005013}
5014
5015/// PerformContextuallyConvertToBool - Perform a contextual conversion
5016/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005017ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005018 if (checkPlaceholderForOverload(*this, From))
5019 return ExprError();
5020
John McCall5c32be02010-08-24 20:38:10 +00005021 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005022 if (!ICS.isBad())
5023 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005024
Fariborz Jahanian76197412009-11-18 18:26:29 +00005025 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005026 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005027 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005028 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005029 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005030}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005031
Richard Smithf8379a02012-01-18 23:55:52 +00005032/// Check that the specified conversion is permitted in a converted constant
5033/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5034/// is acceptable.
5035static bool CheckConvertedConstantConversions(Sema &S,
5036 StandardConversionSequence &SCS) {
5037 // Since we know that the target type is an integral or unscoped enumeration
5038 // type, most conversion kinds are impossible. All possible First and Third
5039 // conversions are fine.
5040 switch (SCS.Second) {
5041 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005042 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005043 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005044 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005045 return true;
5046
5047 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005048 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005049 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5050 // conversion, so we allow it in a converted constant expression.
5051 //
5052 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5053 // a lot of popular code. We should at least add a warning for this
5054 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005055 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5056 SCS.getToType(2)->isBooleanType();
5057
Richard Smith410cc892014-11-26 03:26:53 +00005058 case ICK_Pointer_Conversion:
5059 case ICK_Pointer_Member:
5060 // C++1z: null pointer conversions and null member pointer conversions are
5061 // only permitted if the source type is std::nullptr_t.
5062 return SCS.getFromType()->isNullPtrType();
5063
5064 case ICK_Floating_Promotion:
5065 case ICK_Complex_Promotion:
5066 case ICK_Floating_Conversion:
5067 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005068 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005069 case ICK_Compatible_Conversion:
5070 case ICK_Derived_To_Base:
5071 case ICK_Vector_Conversion:
5072 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005073 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005074 case ICK_Block_Pointer_Conversion:
5075 case ICK_TransparentUnionConversion:
5076 case ICK_Writeback_Conversion:
5077 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005078 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005079 return false;
5080
5081 case ICK_Lvalue_To_Rvalue:
5082 case ICK_Array_To_Pointer:
5083 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005084 llvm_unreachable("found a first conversion kind in Second");
5085
Richard Smithf8379a02012-01-18 23:55:52 +00005086 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005087 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005088
5089 case ICK_Num_Conversion_Kinds:
5090 break;
5091 }
5092
5093 llvm_unreachable("unknown conversion kind");
5094}
5095
5096/// CheckConvertedConstantExpression - Check that the expression From is a
5097/// converted constant expression of type T, perform the conversion and produce
5098/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005099static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5100 QualType T, APValue &Value,
5101 Sema::CCEKind CCE,
5102 bool RequireInt) {
5103 assert(S.getLangOpts().CPlusPlus11 &&
5104 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005105
Richard Smith410cc892014-11-26 03:26:53 +00005106 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005107 return ExprError();
5108
Richard Smith410cc892014-11-26 03:26:53 +00005109 // C++1z [expr.const]p3:
5110 // A converted constant expression of type T is an expression,
5111 // implicitly converted to type T, where the converted
5112 // expression is a constant expression and the implicit conversion
5113 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005114 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005115 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005116 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005117 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005118 /*AllowObjcWritebackConversion=*/false,
5119 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005120 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005121 switch (ICS.getKind()) {
5122 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005123 SCS = &ICS.Standard;
5124 break;
5125 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005126 // We are converting to a non-class type, so the Before sequence
5127 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005128 SCS = &ICS.UserDefined.After;
5129 break;
5130 case ImplicitConversionSequence::AmbiguousConversion:
5131 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005132 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5133 return S.Diag(From->getLocStart(),
5134 diag::err_typecheck_converted_constant_expression)
5135 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005136 return ExprError();
5137
5138 case ImplicitConversionSequence::EllipsisConversion:
5139 llvm_unreachable("ellipsis conversion in converted constant expression");
5140 }
5141
Richard Smith410cc892014-11-26 03:26:53 +00005142 // Check that we would only use permitted conversions.
5143 if (!CheckConvertedConstantConversions(S, *SCS)) {
5144 return S.Diag(From->getLocStart(),
5145 diag::err_typecheck_converted_constant_expression_disallowed)
5146 << From->getType() << From->getSourceRange() << T;
5147 }
5148 // [...] and where the reference binding (if any) binds directly.
5149 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5150 return S.Diag(From->getLocStart(),
5151 diag::err_typecheck_converted_constant_expression_indirect)
5152 << From->getType() << From->getSourceRange() << T;
5153 }
5154
5155 ExprResult Result =
5156 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005157 if (Result.isInvalid())
5158 return Result;
5159
5160 // Check for a narrowing implicit conversion.
5161 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005162 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005163 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005164 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005165 case NK_Variable_Narrowing:
5166 // Implicit conversion to a narrower type, and the value is not a constant
5167 // expression. We'll diagnose this in a moment.
5168 case NK_Not_Narrowing:
5169 break;
5170
5171 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005172 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005173 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005174 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005175 break;
5176
5177 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005178 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005179 << CCE << /*Constant*/0 << From->getType() << T;
5180 break;
5181 }
5182
5183 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005184 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005185 Expr::EvalResult Eval;
5186 Eval.Diag = &Notes;
5187
Richard Smith410cc892014-11-26 03:26:53 +00005188 if ((T->isReferenceType()
5189 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5190 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5191 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005192 // The expression can't be folded, so we can't keep it at this position in
5193 // the AST.
5194 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005195 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005196 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005197
5198 if (Notes.empty()) {
5199 // It's a constant expression.
5200 return Result;
5201 }
Richard Smithf8379a02012-01-18 23:55:52 +00005202 }
5203
5204 // It's not a constant expression. Produce an appropriate diagnostic.
5205 if (Notes.size() == 1 &&
5206 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005207 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005208 else {
Richard Smith410cc892014-11-26 03:26:53 +00005209 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005210 << CCE << From->getSourceRange();
5211 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005212 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005213 }
Richard Smith410cc892014-11-26 03:26:53 +00005214 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005215}
5216
Richard Smith410cc892014-11-26 03:26:53 +00005217ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5218 APValue &Value, CCEKind CCE) {
5219 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5220}
5221
5222ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5223 llvm::APSInt &Value,
5224 CCEKind CCE) {
5225 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5226
5227 APValue V;
5228 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5229 if (!R.isInvalid())
5230 Value = V.getInt();
5231 return R;
5232}
5233
5234
John McCallfec112d2011-09-09 06:11:02 +00005235/// dropPointerConversions - If the given standard conversion sequence
5236/// involves any pointer conversions, remove them. This may change
5237/// the result type of the conversion sequence.
5238static void dropPointerConversion(StandardConversionSequence &SCS) {
5239 if (SCS.Second == ICK_Pointer_Conversion) {
5240 SCS.Second = ICK_Identity;
5241 SCS.Third = ICK_Identity;
5242 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5243 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005244}
John McCall5c32be02010-08-24 20:38:10 +00005245
John McCallfec112d2011-09-09 06:11:02 +00005246/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5247/// convert the expression From to an Objective-C pointer type.
5248static ImplicitConversionSequence
5249TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5250 // Do an implicit conversion to 'id'.
5251 QualType Ty = S.Context.getObjCIdType();
5252 ImplicitConversionSequence ICS
5253 = TryImplicitConversion(S, From, Ty,
5254 // FIXME: Are these flags correct?
5255 /*SuppressUserConversions=*/false,
5256 /*AllowExplicit=*/true,
5257 /*InOverloadResolution=*/false,
5258 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005259 /*AllowObjCWritebackConversion=*/false,
5260 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005261
5262 // Strip off any final conversions to 'id'.
5263 switch (ICS.getKind()) {
5264 case ImplicitConversionSequence::BadConversion:
5265 case ImplicitConversionSequence::AmbiguousConversion:
5266 case ImplicitConversionSequence::EllipsisConversion:
5267 break;
5268
5269 case ImplicitConversionSequence::UserDefinedConversion:
5270 dropPointerConversion(ICS.UserDefined.After);
5271 break;
5272
5273 case ImplicitConversionSequence::StandardConversion:
5274 dropPointerConversion(ICS.Standard);
5275 break;
5276 }
5277
5278 return ICS;
5279}
5280
5281/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5282/// conversion of the expression From to an Objective-C pointer type.
5283ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005284 if (checkPlaceholderForOverload(*this, From))
5285 return ExprError();
5286
John McCall8b07ec22010-05-15 11:32:37 +00005287 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005288 ImplicitConversionSequence ICS =
5289 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005290 if (!ICS.isBad())
5291 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005292 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005293}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005294
Richard Smith8dd34252012-02-04 07:07:42 +00005295/// Determine whether the provided type is an integral type, or an enumeration
5296/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005297bool Sema::ICEConvertDiagnoser::match(QualType T) {
5298 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5299 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005300}
5301
Larisse Voufo236bec22013-06-10 06:50:24 +00005302static ExprResult
5303diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5304 Sema::ContextualImplicitConverter &Converter,
5305 QualType T, UnresolvedSetImpl &ViableConversions) {
5306
5307 if (Converter.Suppress)
5308 return ExprError();
5309
5310 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5311 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5312 CXXConversionDecl *Conv =
5313 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5314 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5315 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5316 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005317 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005318}
5319
5320static bool
5321diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5322 Sema::ContextualImplicitConverter &Converter,
5323 QualType T, bool HadMultipleCandidates,
5324 UnresolvedSetImpl &ExplicitConversions) {
5325 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5326 DeclAccessPair Found = ExplicitConversions[0];
5327 CXXConversionDecl *Conversion =
5328 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5329
5330 // The user probably meant to invoke the given explicit
5331 // conversion; use it.
5332 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5333 std::string TypeStr;
5334 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5335
5336 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5337 << FixItHint::CreateInsertion(From->getLocStart(),
5338 "static_cast<" + TypeStr + ">(")
5339 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005340 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005341 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5342
5343 // If we aren't in a SFINAE context, build a call to the
5344 // explicit conversion function.
5345 if (SemaRef.isSFINAEContext())
5346 return true;
5347
Craig Topperc3ec1492014-05-26 06:22:03 +00005348 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005349 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5350 HadMultipleCandidates);
5351 if (Result.isInvalid())
5352 return true;
5353 // Record usage of conversion in an implicit cast.
5354 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005355 CK_UserDefinedConversion, Result.get(),
5356 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005357 }
5358 return false;
5359}
5360
5361static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5362 Sema::ContextualImplicitConverter &Converter,
5363 QualType T, bool HadMultipleCandidates,
5364 DeclAccessPair &Found) {
5365 CXXConversionDecl *Conversion =
5366 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005367 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005368
5369 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5370 if (!Converter.SuppressConversion) {
5371 if (SemaRef.isSFINAEContext())
5372 return true;
5373
5374 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5375 << From->getSourceRange();
5376 }
5377
5378 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5379 HadMultipleCandidates);
5380 if (Result.isInvalid())
5381 return true;
5382 // Record usage of conversion in an implicit cast.
5383 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005384 CK_UserDefinedConversion, Result.get(),
5385 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005386 return false;
5387}
5388
5389static ExprResult finishContextualImplicitConversion(
5390 Sema &SemaRef, SourceLocation Loc, Expr *From,
5391 Sema::ContextualImplicitConverter &Converter) {
5392 if (!Converter.match(From->getType()) && !Converter.Suppress)
5393 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5394 << From->getSourceRange();
5395
5396 return SemaRef.DefaultLvalueConversion(From);
5397}
5398
5399static void
5400collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5401 UnresolvedSetImpl &ViableConversions,
5402 OverloadCandidateSet &CandidateSet) {
5403 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5404 DeclAccessPair FoundDecl = ViableConversions[I];
5405 NamedDecl *D = FoundDecl.getDecl();
5406 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5407 if (isa<UsingShadowDecl>(D))
5408 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5409
5410 CXXConversionDecl *Conv;
5411 FunctionTemplateDecl *ConvTemplate;
5412 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5413 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5414 else
5415 Conv = cast<CXXConversionDecl>(D);
5416
5417 if (ConvTemplate)
5418 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005419 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5420 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005421 else
5422 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005423 ToType, CandidateSet,
5424 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005425 }
5426}
5427
Richard Smithccc11812013-05-21 19:05:48 +00005428/// \brief Attempt to convert the given expression to a type which is accepted
5429/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005430///
Richard Smithccc11812013-05-21 19:05:48 +00005431/// This routine will attempt to convert an expression of class type to a
5432/// type accepted by the specified converter. In C++11 and before, the class
5433/// must have a single non-explicit conversion function converting to a matching
5434/// type. In C++1y, there can be multiple such conversion functions, but only
5435/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005436///
Douglas Gregor4799d032010-06-30 00:20:43 +00005437/// \param Loc The source location of the construct that requires the
5438/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005439///
James Dennett18348b62012-06-22 08:52:37 +00005440/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005441///
Richard Smithccc11812013-05-21 19:05:48 +00005442/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005443///
Douglas Gregor4799d032010-06-30 00:20:43 +00005444/// \returns The expression, converted to an integral or enumeration type if
5445/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005446ExprResult Sema::PerformContextualImplicitConversion(
5447 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005448 // We can't perform any more checking for type-dependent expressions.
5449 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005450 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005451
Eli Friedman1da70392012-01-26 00:26:18 +00005452 // Process placeholders immediately.
5453 if (From->hasPlaceholderType()) {
5454 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005455 if (result.isInvalid())
5456 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005457 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005458 }
5459
Richard Smithccc11812013-05-21 19:05:48 +00005460 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005461 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005462 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005463 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005464
5465 // FIXME: Check for missing '()' if T is a function type?
5466
Richard Smithccc11812013-05-21 19:05:48 +00005467 // We can only perform contextual implicit conversions on objects of class
5468 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005469 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005470 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005471 if (!Converter.Suppress)
5472 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005473 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005476 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005477 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005478 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005479 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005480
5481 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005482 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005483
Craig Toppere14c0f82014-03-12 04:55:44 +00005484 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005485 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005486 }
Richard Smithccc11812013-05-21 19:05:48 +00005487 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005488
Richard Smithdb0ac552015-12-18 22:40:25 +00005489 if (Converter.Suppress ? !isCompleteType(Loc, T)
5490 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005491 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005493 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005494 UnresolvedSet<4>
5495 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005496 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005497 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005498 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005499
Larisse Voufo236bec22013-06-10 06:50:24 +00005500 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005501 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005502
Larisse Voufo236bec22013-06-10 06:50:24 +00005503 // To check that there is only one target type, in C++1y:
5504 QualType ToType;
5505 bool HasUniqueTargetType = true;
5506
5507 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005508 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005509 NamedDecl *D = (*I)->getUnderlyingDecl();
5510 CXXConversionDecl *Conversion;
5511 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5512 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005513 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005514 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5515 else
5516 continue; // C++11 does not consider conversion operator templates(?).
5517 } else
5518 Conversion = cast<CXXConversionDecl>(D);
5519
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005520 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005521 "Conversion operator templates are considered potentially "
5522 "viable in C++1y");
5523
5524 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5525 if (Converter.match(CurToType) || ConvTemplate) {
5526
5527 if (Conversion->isExplicit()) {
5528 // FIXME: For C++1y, do we need this restriction?
5529 // cf. diagnoseNoViableConversion()
5530 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005531 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005532 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005533 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005534 if (ToType.isNull())
5535 ToType = CurToType.getUnqualifiedType();
5536 else if (HasUniqueTargetType &&
5537 (CurToType.getUnqualifiedType() != ToType))
5538 HasUniqueTargetType = false;
5539 }
5540 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005541 }
Richard Smith8dd34252012-02-04 07:07:42 +00005542 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005545 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005546 // C++1y [conv]p6:
5547 // ... An expression e of class type E appearing in such a context
5548 // is said to be contextually implicitly converted to a specified
5549 // type T and is well-formed if and only if e can be implicitly
5550 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005551 // for conversion functions whose return type is cv T or reference to
5552 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005553 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005554
Larisse Voufo236bec22013-06-10 06:50:24 +00005555 // If no unique T is found:
5556 if (ToType.isNull()) {
5557 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5558 HadMultipleCandidates,
5559 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005560 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005561 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
Larisse Voufo236bec22013-06-10 06:50:24 +00005564 // If more than one unique Ts are found:
5565 if (!HasUniqueTargetType)
5566 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5567 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005568
Larisse Voufo236bec22013-06-10 06:50:24 +00005569 // If one unique T is found:
5570 // First, build a candidate set from the previously recorded
5571 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005572 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005573 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5574 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575
Larisse Voufo236bec22013-06-10 06:50:24 +00005576 // Then, perform overload resolution over the candidate set.
5577 OverloadCandidateSet::iterator Best;
5578 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5579 case OR_Success: {
5580 // Apply this conversion.
5581 DeclAccessPair Found =
5582 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5583 if (recordConversion(*this, Loc, From, Converter, T,
5584 HadMultipleCandidates, Found))
5585 return ExprError();
5586 break;
5587 }
5588 case OR_Ambiguous:
5589 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5590 ViableConversions);
5591 case OR_No_Viable_Function:
5592 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5593 HadMultipleCandidates,
5594 ExplicitConversions))
5595 return ExprError();
5596 // fall through 'OR_Deleted' case.
5597 case OR_Deleted:
5598 // We'll complain below about a non-integral condition type.
5599 break;
5600 }
5601 } else {
5602 switch (ViableConversions.size()) {
5603 case 0: {
5604 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5605 HadMultipleCandidates,
5606 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005607 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Larisse Voufo236bec22013-06-10 06:50:24 +00005609 // We'll complain below about a non-integral condition type.
5610 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005611 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005612 case 1: {
5613 // Apply this conversion.
5614 DeclAccessPair Found = ViableConversions[0];
5615 if (recordConversion(*this, Loc, From, Converter, T,
5616 HadMultipleCandidates, Found))
5617 return ExprError();
5618 break;
5619 }
5620 default:
5621 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5622 ViableConversions);
5623 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625
Larisse Voufo236bec22013-06-10 06:50:24 +00005626 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005627}
5628
Richard Smith100b24a2014-04-17 01:52:14 +00005629/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5630/// an acceptable non-member overloaded operator for a call whose
5631/// arguments have types T1 (and, if non-empty, T2). This routine
5632/// implements the check in C++ [over.match.oper]p3b2 concerning
5633/// enumeration types.
5634static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5635 FunctionDecl *Fn,
5636 ArrayRef<Expr *> Args) {
5637 QualType T1 = Args[0]->getType();
5638 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5639
5640 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5641 return true;
5642
5643 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5644 return true;
5645
5646 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5647 if (Proto->getNumParams() < 1)
5648 return false;
5649
5650 if (T1->isEnumeralType()) {
5651 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5652 if (Context.hasSameUnqualifiedType(T1, ArgType))
5653 return true;
5654 }
5655
5656 if (Proto->getNumParams() < 2)
5657 return false;
5658
5659 if (!T2.isNull() && T2->isEnumeralType()) {
5660 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5661 if (Context.hasSameUnqualifiedType(T2, ArgType))
5662 return true;
5663 }
5664
5665 return false;
5666}
5667
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005668/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005669/// candidate functions, using the given function call arguments. If
5670/// @p SuppressUserConversions, then don't allow user-defined
5671/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005672///
James Dennett2a4d13c2012-06-15 07:13:21 +00005673/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005674/// based on an incomplete set of function arguments. This feature is used by
5675/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005676void
5677Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005678 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005679 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005680 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005681 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005682 bool PartialOverloading,
5683 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005684 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005685 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005686 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005687 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005688 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005689
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005691 if (!isa<CXXConstructorDecl>(Method)) {
5692 // If we get here, it's because we're calling a member function
5693 // that is named without a member access expression (e.g.,
5694 // "this->f") that was either written explicitly or created
5695 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005696 // function, e.g., X::f(). We use an empty type for the implied
5697 // object argument (C++ [over.call.func]p3), and the acting context
5698 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005699 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005700 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005701 Args, CandidateSet, SuppressUserConversions,
5702 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005703 return;
5704 }
5705 // We treat a constructor like a non-member function, since its object
5706 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005707 }
5708
Douglas Gregorff7028a2009-11-13 23:59:09 +00005709 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005710 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005711
Richard Smith100b24a2014-04-17 01:52:14 +00005712 // C++ [over.match.oper]p3:
5713 // if no operand has a class type, only those non-member functions in the
5714 // lookup set that have a first parameter of type T1 or "reference to
5715 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5716 // is a right operand) a second parameter of type T2 or "reference to
5717 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5718 // candidate functions.
5719 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5720 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5721 return;
5722
Richard Smith8b86f2d2013-11-04 01:48:18 +00005723 // C++11 [class.copy]p11: [DR1402]
5724 // A defaulted move constructor that is defined as deleted is ignored by
5725 // overload resolution.
5726 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5727 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5728 Constructor->isMoveConstructor())
5729 return;
5730
Douglas Gregor27381f32009-11-23 12:27:39 +00005731 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005732 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005733
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005734 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005735 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005736 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005737 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005738 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005739 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005740 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005741 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005742
John McCall578a1f82014-12-14 01:46:53 +00005743 if (Constructor) {
5744 // C++ [class.copy]p3:
5745 // A member function template is never instantiated to perform the copy
5746 // of a class object to an object of its class type.
5747 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005748 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005749 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005750 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5751 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005752 Candidate.Viable = false;
5753 Candidate.FailureKind = ovl_fail_illegal_constructor;
5754 return;
5755 }
5756 }
5757
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005758 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005759
5760 // (C++ 13.3.2p2): A candidate function having fewer than m
5761 // parameters is viable only if it has an ellipsis in its parameter
5762 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005763 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005764 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005765 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005766 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005767 return;
5768 }
5769
5770 // (C++ 13.3.2p2): A candidate function having more than m parameters
5771 // is viable only if the (m+1)st parameter has a default argument
5772 // (8.3.6). For the purposes of overload resolution, the
5773 // parameter list is truncated on the right, so that there are
5774 // exactly m parameters.
5775 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005776 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005777 // Not enough arguments.
5778 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005779 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005780 return;
5781 }
5782
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005783 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005784 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005785 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005786 // Skip the check for callers that are implicit members, because in this
5787 // case we may not yet know what the member's target is; the target is
5788 // inferred for the member automatically, based on the bases and fields of
5789 // the class.
5790 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005791 Candidate.Viable = false;
5792 Candidate.FailureKind = ovl_fail_bad_target;
5793 return;
5794 }
5795
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005796 // Determine the implicit conversion sequences for each of the
5797 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005798 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005799 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005800 // (C++ 13.3.2p3): for F to be a viable function, there shall
5801 // exist for each argument an implicit conversion sequence
5802 // (13.3.3.1) that converts that argument to the corresponding
5803 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005804 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005805 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005806 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005807 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005808 /*InOverloadResolution=*/true,
5809 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005810 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005811 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005812 if (Candidate.Conversions[ArgIdx].isBad()) {
5813 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005814 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005815 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005816 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005817 } else {
5818 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5819 // argument for which there is no corresponding parameter is
5820 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005821 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005822 }
5823 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005824
5825 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5826 Candidate.Viable = false;
5827 Candidate.FailureKind = ovl_fail_enable_if;
5828 Candidate.DeductionFailure.Data = FailedAttr;
5829 return;
5830 }
5831}
5832
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005833ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005834 bool IsInstance) {
5835 SmallVector<ObjCMethodDecl*, 4> Methods;
5836 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5837 return nullptr;
5838
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005839 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5840 bool Match = true;
5841 ObjCMethodDecl *Method = Methods[b];
5842 unsigned NumNamedArgs = Sel.getNumArgs();
5843 // Method might have more arguments than selector indicates. This is due
5844 // to addition of c-style arguments in method.
5845 if (Method->param_size() > NumNamedArgs)
5846 NumNamedArgs = Method->param_size();
5847 if (Args.size() < NumNamedArgs)
5848 continue;
5849
5850 for (unsigned i = 0; i < NumNamedArgs; i++) {
5851 // We can't do any type-checking on a type-dependent argument.
5852 if (Args[i]->isTypeDependent()) {
5853 Match = false;
5854 break;
5855 }
5856
5857 ParmVarDecl *param = Method->parameters()[i];
5858 Expr *argExpr = Args[i];
5859 assert(argExpr && "SelectBestMethod(): missing expression");
5860
5861 // Strip the unbridged-cast placeholder expression off unless it's
5862 // a consumed argument.
5863 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5864 !param->hasAttr<CFConsumedAttr>())
5865 argExpr = stripARCUnbridgedCast(argExpr);
5866
5867 // If the parameter is __unknown_anytype, move on to the next method.
5868 if (param->getType() == Context.UnknownAnyTy) {
5869 Match = false;
5870 break;
5871 }
George Burgess IV45461812015-10-11 20:13:20 +00005872
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005873 ImplicitConversionSequence ConversionState
5874 = TryCopyInitialization(*this, argExpr, param->getType(),
5875 /*SuppressUserConversions*/false,
5876 /*InOverloadResolution=*/true,
5877 /*AllowObjCWritebackConversion=*/
5878 getLangOpts().ObjCAutoRefCount,
5879 /*AllowExplicit*/false);
5880 if (ConversionState.isBad()) {
5881 Match = false;
5882 break;
5883 }
5884 }
5885 // Promote additional arguments to variadic methods.
5886 if (Match && Method->isVariadic()) {
5887 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5888 if (Args[i]->isTypeDependent()) {
5889 Match = false;
5890 break;
5891 }
5892 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5893 nullptr);
5894 if (Arg.isInvalid()) {
5895 Match = false;
5896 break;
5897 }
5898 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005899 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005900 // Check for extra arguments to non-variadic methods.
5901 if (Args.size() != NumNamedArgs)
5902 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005903 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5904 // Special case when selectors have no argument. In this case, select
5905 // one with the most general result type of 'id'.
5906 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5907 QualType ReturnT = Methods[b]->getReturnType();
5908 if (ReturnT->isObjCIdType())
5909 return Methods[b];
5910 }
5911 }
5912 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005913
5914 if (Match)
5915 return Method;
5916 }
5917 return nullptr;
5918}
5919
George Burgess IV2a6150d2015-10-16 01:17:38 +00005920// specific_attr_iterator iterates over enable_if attributes in reverse, and
5921// enable_if is order-sensitive. As a result, we need to reverse things
5922// sometimes. Size of 4 elements is arbitrary.
5923static SmallVector<EnableIfAttr *, 4>
5924getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5925 SmallVector<EnableIfAttr *, 4> Result;
5926 if (!Function->hasAttrs())
5927 return Result;
5928
5929 const auto &FuncAttrs = Function->getAttrs();
5930 for (Attr *Attr : FuncAttrs)
5931 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5932 Result.push_back(EnableIf);
5933
5934 std::reverse(Result.begin(), Result.end());
5935 return Result;
5936}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005937
5938EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5939 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005940 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5941 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005942 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005943
5944 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005945 SmallVector<Expr *, 16> ConvertedArgs;
5946 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005947 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005948
5949 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005950 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5951 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005952 !cast<CXXMethodDecl>(Function)->isStatic() &&
5953 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005954 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5955 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005956 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005957 Method, Method);
5958 if (R.isInvalid()) {
5959 InitializationFailed = true;
5960 break;
5961 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005962 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005963 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005964 } else {
5965 ExprResult R =
5966 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5967 Context,
5968 Function->getParamDecl(i)),
5969 SourceLocation(),
5970 Args[i]);
5971 if (R.isInvalid()) {
5972 InitializationFailed = true;
5973 break;
5974 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005975 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005976 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005977 }
5978 }
5979
5980 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005981 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005982
Nick Lewyckye283c552015-08-25 22:33:16 +00005983 // Push default arguments if needed.
5984 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5985 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5986 ParmVarDecl *P = Function->getParamDecl(i);
5987 ExprResult R = PerformCopyInitialization(
5988 InitializedEntity::InitializeParameter(Context,
5989 Function->getParamDecl(i)),
5990 SourceLocation(),
5991 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5992 : P->getDefaultArg());
5993 if (R.isInvalid()) {
5994 InitializationFailed = true;
5995 break;
5996 }
5997 ContainsValueDependentExpr |= R.get()->isValueDependent();
5998 ConvertedArgs.push_back(R.get());
5999 }
6000
6001 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006002 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006003 }
6004
George Burgess IV2a6150d2015-10-16 01:17:38 +00006005 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006006 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006007 if (EIA->getCond()->isValueDependent()) {
6008 // Don't even try now, we'll examine it after instantiation.
6009 continue;
6010 }
6011
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006012 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006013 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6014 if (!ContainsValueDependentExpr)
6015 return EIA;
6016 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006017 return EIA;
6018 }
6019 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006020 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006021}
6022
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006023/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006024/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006025void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006026 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006027 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006028 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006029 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006030 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006031 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006032 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6033 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006034 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006035 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006036 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006037 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006038 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006039 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006040 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006041 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006042 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006043 } else {
John McCalla0296f72010-03-19 07:35:19 +00006044 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006045 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6046 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006047 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006048 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006049 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006050 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006051 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006052 CandidateSet, SuppressUserConversions,
6053 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006054 else
John McCalla0296f72010-03-19 07:35:19 +00006055 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006056 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006057 CandidateSet, SuppressUserConversions,
6058 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006059 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006060 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006061}
6062
John McCallf0f1cf02009-11-17 07:50:12 +00006063/// AddMethodCandidate - Adds a named decl (which is some kind of
6064/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006065void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006066 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006067 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006068 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006069 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006070 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006071 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006072 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006073
6074 if (isa<UsingShadowDecl>(Decl))
6075 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006076
John McCallf0f1cf02009-11-17 07:50:12 +00006077 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6078 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6079 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006080 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006081 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006082 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006083 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006084 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006085 } else {
John McCalla0296f72010-03-19 07:35:19 +00006086 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006087 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006088 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006089 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006090 }
6091}
6092
Douglas Gregor436424c2008-11-18 23:14:02 +00006093/// AddMethodCandidate - Adds the given C++ member function to the set
6094/// of candidate functions, using the given function call arguments
6095/// and the object argument (@c Object). For example, in a call
6096/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6097/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6098/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006099/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006100void
John McCalla0296f72010-03-19 07:35:19 +00006101Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006102 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006103 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006104 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006105 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006106 bool SuppressUserConversions,
6107 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006108 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006109 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006110 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006111 assert(!isa<CXXConstructorDecl>(Method) &&
6112 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006113
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006114 if (!CandidateSet.isNewCandidate(Method))
6115 return;
6116
Richard Smith8b86f2d2013-11-04 01:48:18 +00006117 // C++11 [class.copy]p23: [DR1402]
6118 // A defaulted move assignment operator that is defined as deleted is
6119 // ignored by overload resolution.
6120 if (Method->isDefaulted() && Method->isDeleted() &&
6121 Method->isMoveAssignmentOperator())
6122 return;
6123
Douglas Gregor27381f32009-11-23 12:27:39 +00006124 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006125 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006126
Douglas Gregor436424c2008-11-18 23:14:02 +00006127 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006128 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006129 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006130 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006131 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006132 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006133 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006134
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006135 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006136
6137 // (C++ 13.3.2p2): A candidate function having fewer than m
6138 // parameters is viable only if it has an ellipsis in its parameter
6139 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006140 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6141 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006142 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006143 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006144 return;
6145 }
6146
6147 // (C++ 13.3.2p2): A candidate function having more than m parameters
6148 // is viable only if the (m+1)st parameter has a default argument
6149 // (8.3.6). For the purposes of overload resolution, the
6150 // parameter list is truncated on the right, so that there are
6151 // exactly m parameters.
6152 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006153 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006154 // Not enough arguments.
6155 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006156 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006157 return;
6158 }
6159
6160 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006161
John McCall6e9f8f62009-12-03 04:06:58 +00006162 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006163 // The implicit object argument is ignored.
6164 Candidate.IgnoreObjectArgument = true;
6165 else {
6166 // Determine the implicit conversion sequence for the object
6167 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006168 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6169 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6170 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006171 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006172 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006173 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006174 return;
6175 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006176 }
6177
Eli Bendersky291a57e2014-09-25 23:59:08 +00006178 // (CUDA B.1): Check for invalid calls between targets.
6179 if (getLangOpts().CUDA)
6180 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6181 if (CheckCUDATarget(Caller, Method)) {
6182 Candidate.Viable = false;
6183 Candidate.FailureKind = ovl_fail_bad_target;
6184 return;
6185 }
6186
Douglas Gregor436424c2008-11-18 23:14:02 +00006187 // Determine the implicit conversion sequences for each of the
6188 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006189 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006190 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006191 // (C++ 13.3.2p3): for F to be a viable function, there shall
6192 // exist for each argument an implicit conversion sequence
6193 // (13.3.3.1) that converts that argument to the corresponding
6194 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006195 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006196 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006197 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006198 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006199 /*InOverloadResolution=*/true,
6200 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006201 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006202 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006203 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006204 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006205 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006206 }
6207 } else {
6208 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6209 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006210 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006211 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006212 }
6213 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006214
6215 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6216 Candidate.Viable = false;
6217 Candidate.FailureKind = ovl_fail_enable_if;
6218 Candidate.DeductionFailure.Data = FailedAttr;
6219 return;
6220 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006221}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006222
Douglas Gregor97628d62009-08-21 00:16:32 +00006223/// \brief Add a C++ member function template as a candidate to the candidate
6224/// set, using template argument deduction to produce an appropriate member
6225/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006226void
Douglas Gregor97628d62009-08-21 00:16:32 +00006227Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006228 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006229 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006230 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006231 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006232 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006233 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006234 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006235 bool SuppressUserConversions,
6236 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006237 if (!CandidateSet.isNewCandidate(MethodTmpl))
6238 return;
6239
Douglas Gregor97628d62009-08-21 00:16:32 +00006240 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006241 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006242 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006243 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006244 // candidate functions in the usual way.113) A given name can refer to one
6245 // or more function templates and also to a set of overloaded non-template
6246 // functions. In such a case, the candidate functions generated from each
6247 // function template are combined with the set of non-template candidate
6248 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006249 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006250 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006251 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006252 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006253 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006254 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006255 Candidate.FoundDecl = FoundDecl;
6256 Candidate.Function = MethodTmpl->getTemplatedDecl();
6257 Candidate.Viable = false;
6258 Candidate.FailureKind = ovl_fail_bad_deduction;
6259 Candidate.IsSurrogate = false;
6260 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006261 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006262 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006263 Info);
6264 return;
6265 }
Mike Stump11289f42009-09-09 15:08:12 +00006266
Douglas Gregor97628d62009-08-21 00:16:32 +00006267 // Add the function template specialization produced by template argument
6268 // deduction as a candidate.
6269 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006270 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006271 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006272 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006273 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006274 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006275}
6276
Douglas Gregor05155d82009-08-21 23:19:43 +00006277/// \brief Add a C++ function template specialization as a candidate
6278/// in the candidate set, using template argument deduction to produce
6279/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006280void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006281Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006282 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006283 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006284 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006285 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006286 bool SuppressUserConversions,
6287 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006288 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6289 return;
6290
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006291 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006292 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006293 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006294 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006295 // candidate functions in the usual way.113) A given name can refer to one
6296 // or more function templates and also to a set of overloaded non-template
6297 // functions. In such a case, the candidate functions generated from each
6298 // function template are combined with the set of non-template candidate
6299 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006300 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006301 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006302 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006303 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006304 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006305 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006306 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006307 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6308 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006309 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006310 Candidate.IsSurrogate = false;
6311 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006312 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006313 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006314 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006315 return;
6316 }
Mike Stump11289f42009-09-09 15:08:12 +00006317
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006318 // Add the function template specialization produced by template argument
6319 // deduction as a candidate.
6320 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006321 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006322 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006323}
Mike Stump11289f42009-09-09 15:08:12 +00006324
Douglas Gregor4b60a152013-11-07 22:34:54 +00006325/// Determine whether this is an allowable conversion from the result
6326/// of an explicit conversion operator to the expected type, per C++
6327/// [over.match.conv]p1 and [over.match.ref]p1.
6328///
6329/// \param ConvType The return type of the conversion function.
6330///
6331/// \param ToType The type we are converting to.
6332///
6333/// \param AllowObjCPointerConversion Allow a conversion from one
6334/// Objective-C pointer to another.
6335///
6336/// \returns true if the conversion is allowable, false otherwise.
6337static bool isAllowableExplicitConversion(Sema &S,
6338 QualType ConvType, QualType ToType,
6339 bool AllowObjCPointerConversion) {
6340 QualType ToNonRefType = ToType.getNonReferenceType();
6341
6342 // Easy case: the types are the same.
6343 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6344 return true;
6345
6346 // Allow qualification conversions.
6347 bool ObjCLifetimeConversion;
6348 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6349 ObjCLifetimeConversion))
6350 return true;
6351
6352 // If we're not allowed to consider Objective-C pointer conversions,
6353 // we're done.
6354 if (!AllowObjCPointerConversion)
6355 return false;
6356
6357 // Is this an Objective-C pointer conversion?
6358 bool IncompatibleObjC = false;
6359 QualType ConvertedType;
6360 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6361 IncompatibleObjC);
6362}
6363
Douglas Gregora1f013e2008-11-07 22:36:19 +00006364/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006365/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006366/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006367/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006368/// (which may or may not be the same type as the type that the
6369/// conversion function produces).
6370void
6371Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006372 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006373 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006374 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006375 OverloadCandidateSet& CandidateSet,
6376 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006377 assert(!Conversion->getDescribedFunctionTemplate() &&
6378 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006379 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006380 if (!CandidateSet.isNewCandidate(Conversion))
6381 return;
6382
Richard Smith2a7d4812013-05-04 07:00:32 +00006383 // If the conversion function has an undeduced return type, trigger its
6384 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006385 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006386 if (DeduceReturnType(Conversion, From->getExprLoc()))
6387 return;
6388 ConvType = Conversion->getConversionType().getNonReferenceType();
6389 }
6390
Richard Smith089c3162013-09-21 21:55:46 +00006391 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6392 // operator is only a candidate if its return type is the target type or
6393 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006394 if (Conversion->isExplicit() &&
6395 !isAllowableExplicitConversion(*this, ConvType, ToType,
6396 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006397 return;
6398
Douglas Gregor27381f32009-11-23 12:27:39 +00006399 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006400 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006401
Douglas Gregora1f013e2008-11-07 22:36:19 +00006402 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006403 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006404 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006405 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006406 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006407 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006408 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006409 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006410 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006411 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006412 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006413
Douglas Gregor6affc782010-08-19 15:37:02 +00006414 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006415 // For conversion functions, the function is considered to be a member of
6416 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006417 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006418 //
6419 // Determine the implicit conversion sequence for the implicit
6420 // object parameter.
6421 QualType ImplicitParamType = From->getType();
6422 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6423 ImplicitParamType = FromPtrType->getPointeeType();
6424 CXXRecordDecl *ConversionContext
6425 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006426
Richard Smith0f59cb32015-12-18 21:45:41 +00006427 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6428 *this, CandidateSet.getLocation(), From->getType(),
6429 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006430
John McCall0d1da222010-01-12 00:44:57 +00006431 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006432 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006433 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006434 return;
6435 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006436
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006437 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006438 // derived to base as such conversions are given Conversion Rank. They only
6439 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6440 QualType FromCanon
6441 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6442 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006443 if (FromCanon == ToCanon ||
6444 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006445 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006446 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006447 return;
6448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449
Douglas Gregora1f013e2008-11-07 22:36:19 +00006450 // To determine what the conversion from the result of calling the
6451 // conversion function to the type we're eventually trying to
6452 // convert to (ToType), we need to synthesize a call to the
6453 // conversion function and attempt copy initialization from it. This
6454 // makes sure that we get the right semantics with respect to
6455 // lvalues/rvalues and the type. Fortunately, we can allocate this
6456 // call on the stack and we don't need its arguments to be
6457 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006458 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006459 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006460 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6461 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006462 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006463 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006464
Richard Smith48d24642011-07-13 22:53:21 +00006465 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006466 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006467 Candidate.Viable = false;
6468 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6469 return;
6470 }
6471
Richard Smith48d24642011-07-13 22:53:21 +00006472 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006473
Mike Stump11289f42009-09-09 15:08:12 +00006474 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006475 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6476 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006477 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006478 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006479 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006480 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006481 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006482 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006483 /*InOverloadResolution=*/false,
6484 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006485
John McCall0d1da222010-01-12 00:44:57 +00006486 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006487 case ImplicitConversionSequence::StandardConversion:
6488 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006489
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006490 // C++ [over.ics.user]p3:
6491 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006492 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006493 // shall have exact match rank.
6494 if (Conversion->getPrimaryTemplate() &&
6495 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6496 Candidate.Viable = false;
6497 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006498 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006500
Douglas Gregorcba72b12011-01-21 05:18:22 +00006501 // C++0x [dcl.init.ref]p5:
6502 // In the second case, if the reference is an rvalue reference and
6503 // the second standard conversion sequence of the user-defined
6504 // conversion sequence includes an lvalue-to-rvalue conversion, the
6505 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006506 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006507 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6508 Candidate.Viable = false;
6509 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006510 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006511 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006512 break;
6513
6514 case ImplicitConversionSequence::BadConversion:
6515 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006516 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006517 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006518
6519 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006520 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006521 "Can only end up with a standard conversion sequence or failure");
6522 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006523
Craig Topper5fc8fc22014-08-27 06:28:36 +00006524 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006525 Candidate.Viable = false;
6526 Candidate.FailureKind = ovl_fail_enable_if;
6527 Candidate.DeductionFailure.Data = FailedAttr;
6528 return;
6529 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006530}
6531
Douglas Gregor05155d82009-08-21 23:19:43 +00006532/// \brief Adds a conversion function template specialization
6533/// candidate to the overload set, using template argument deduction
6534/// to deduce the template arguments of the conversion function
6535/// template from the type that we are converting to (C++
6536/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006537void
Douglas Gregor05155d82009-08-21 23:19:43 +00006538Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006539 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006540 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006541 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006542 OverloadCandidateSet &CandidateSet,
6543 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006544 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6545 "Only conversion function templates permitted here");
6546
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006547 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6548 return;
6549
Craig Toppere6706e42012-09-19 02:26:47 +00006550 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006551 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006552 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006553 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006554 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006555 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006556 Candidate.FoundDecl = FoundDecl;
6557 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6558 Candidate.Viable = false;
6559 Candidate.FailureKind = ovl_fail_bad_deduction;
6560 Candidate.IsSurrogate = false;
6561 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006562 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006563 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006564 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006565 return;
6566 }
Mike Stump11289f42009-09-09 15:08:12 +00006567
Douglas Gregor05155d82009-08-21 23:19:43 +00006568 // Add the conversion function template specialization produced by
6569 // template argument deduction as a candidate.
6570 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006571 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006572 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006573}
6574
Douglas Gregorab7897a2008-11-19 22:57:39 +00006575/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6576/// converts the given @c Object to a function pointer via the
6577/// conversion function @c Conversion, and then attempts to call it
6578/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6579/// the type of function that we'll eventually be calling.
6580void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006581 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006582 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006583 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006584 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006585 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006586 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006587 if (!CandidateSet.isNewCandidate(Conversion))
6588 return;
6589
Douglas Gregor27381f32009-11-23 12:27:39 +00006590 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006591 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006592
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006593 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006594 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006595 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006596 Candidate.Surrogate = Conversion;
6597 Candidate.Viable = true;
6598 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006599 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006600 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006601
6602 // Determine the implicit conversion sequence for the implicit
6603 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006604 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6605 *this, CandidateSet.getLocation(), Object->getType(),
6606 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006607 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006608 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006609 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006610 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006611 return;
6612 }
6613
6614 // The first conversion is actually a user-defined conversion whose
6615 // first conversion is ObjectInit's standard conversion (which is
6616 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006617 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006618 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006619 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006620 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006621 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006622 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006623 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006624 = Candidate.Conversions[0].UserDefined.Before;
6625 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6626
Mike Stump11289f42009-09-09 15:08:12 +00006627 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006628 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006629
6630 // (C++ 13.3.2p2): A candidate function having fewer than m
6631 // parameters is viable only if it has an ellipsis in its parameter
6632 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006633 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006634 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006635 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006636 return;
6637 }
6638
6639 // Function types don't have any default arguments, so just check if
6640 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006641 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006642 // Not enough arguments.
6643 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006644 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006645 return;
6646 }
6647
6648 // Determine the implicit conversion sequences for each of the
6649 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006650 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006651 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006652 // (C++ 13.3.2p3): for F to be a viable function, there shall
6653 // exist for each argument an implicit conversion sequence
6654 // (13.3.3.1) that converts that argument to the corresponding
6655 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006656 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006657 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006658 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006659 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006660 /*InOverloadResolution=*/false,
6661 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006662 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006663 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006664 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006665 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006666 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006667 }
6668 } else {
6669 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6670 // argument for which there is no corresponding parameter is
6671 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006672 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006673 }
6674 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006675
Craig Topper5fc8fc22014-08-27 06:28:36 +00006676 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006677 Candidate.Viable = false;
6678 Candidate.FailureKind = ovl_fail_enable_if;
6679 Candidate.DeductionFailure.Data = FailedAttr;
6680 return;
6681 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006682}
6683
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006684/// \brief Add overload candidates for overloaded operators that are
6685/// member functions.
6686///
6687/// Add the overloaded operator candidates that are member functions
6688/// for the operator Op that was used in an operator expression such
6689/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6690/// CandidateSet will store the added overload candidates. (C++
6691/// [over.match.oper]).
6692void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6693 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006694 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006695 OverloadCandidateSet& CandidateSet,
6696 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006697 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6698
6699 // C++ [over.match.oper]p3:
6700 // For a unary operator @ with an operand of a type whose
6701 // cv-unqualified version is T1, and for a binary operator @ with
6702 // a left operand of a type whose cv-unqualified version is T1 and
6703 // a right operand of a type whose cv-unqualified version is T2,
6704 // three sets of candidate functions, designated member
6705 // candidates, non-member candidates and built-in candidates, are
6706 // constructed as follows:
6707 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006708
Richard Smith0feaf0c2013-04-20 12:41:22 +00006709 // -- If T1 is a complete class type or a class currently being
6710 // defined, the set of member candidates is the result of the
6711 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6712 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006713 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006714 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006715 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006716 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006717 // If the type is neither complete nor being defined, bail out now.
6718 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006719 return;
Mike Stump11289f42009-09-09 15:08:12 +00006720
John McCall27b18f82009-11-17 02:14:36 +00006721 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6722 LookupQualifiedName(Operators, T1Rec->getDecl());
6723 Operators.suppressDiagnostics();
6724
Mike Stump11289f42009-09-09 15:08:12 +00006725 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006726 OperEnd = Operators.end();
6727 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006728 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006729 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006730 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006731 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006732 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006733 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006734 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006735}
6736
Douglas Gregora11693b2008-11-12 17:17:38 +00006737/// AddBuiltinCandidate - Add a candidate for a built-in
6738/// operator. ResultTy and ParamTys are the result and parameter types
6739/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006740/// arguments being passed to the candidate. IsAssignmentOperator
6741/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006742/// operator. NumContextualBoolArguments is the number of arguments
6743/// (at the beginning of the argument list) that will be contextually
6744/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006745void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006746 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006747 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006748 bool IsAssignmentOperator,
6749 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006750 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006751 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006752
Douglas Gregora11693b2008-11-12 17:17:38 +00006753 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006754 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006755 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6756 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006757 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006758 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006759 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006760 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006761 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6762
6763 // Determine the implicit conversion sequences for each of the
6764 // arguments.
6765 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006766 Candidate.ExplicitCallArguments = Args.size();
6767 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006768 // C++ [over.match.oper]p4:
6769 // For the built-in assignment operators, conversions of the
6770 // left operand are restricted as follows:
6771 // -- no temporaries are introduced to hold the left operand, and
6772 // -- no user-defined conversions are applied to the left
6773 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006774 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006775 //
6776 // We block these conversions by turning off user-defined
6777 // conversions, since that is the only way that initialization of
6778 // a reference to a non-class type can occur from something that
6779 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006780 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006781 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006782 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006783 Candidate.Conversions[ArgIdx]
6784 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006785 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006786 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006787 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006788 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006789 /*InOverloadResolution=*/false,
6790 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006791 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006792 }
John McCall0d1da222010-01-12 00:44:57 +00006793 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006794 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006795 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006796 break;
6797 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006798 }
6799}
6800
Craig Toppercd7b0332013-07-01 06:29:40 +00006801namespace {
6802
Douglas Gregora11693b2008-11-12 17:17:38 +00006803/// BuiltinCandidateTypeSet - A set of types that will be used for the
6804/// candidate operator functions for built-in operators (C++
6805/// [over.built]). The types are separated into pointer types and
6806/// enumeration types.
6807class BuiltinCandidateTypeSet {
6808 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006809 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006810
6811 /// PointerTypes - The set of pointer types that will be used in the
6812 /// built-in candidates.
6813 TypeSet PointerTypes;
6814
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006815 /// MemberPointerTypes - The set of member pointer types that will be
6816 /// used in the built-in candidates.
6817 TypeSet MemberPointerTypes;
6818
Douglas Gregora11693b2008-11-12 17:17:38 +00006819 /// EnumerationTypes - The set of enumeration types that will be
6820 /// used in the built-in candidates.
6821 TypeSet EnumerationTypes;
6822
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006824 /// candidates.
6825 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006826
6827 /// \brief A flag indicating non-record types are viable candidates
6828 bool HasNonRecordTypes;
6829
6830 /// \brief A flag indicating whether either arithmetic or enumeration types
6831 /// were present in the candidate set.
6832 bool HasArithmeticOrEnumeralTypes;
6833
Douglas Gregor80af3132011-05-21 23:15:46 +00006834 /// \brief A flag indicating whether the nullptr type was present in the
6835 /// candidate set.
6836 bool HasNullPtrType;
6837
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006838 /// Sema - The semantic analysis instance where we are building the
6839 /// candidate type set.
6840 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006841
Douglas Gregora11693b2008-11-12 17:17:38 +00006842 /// Context - The AST context in which we will build the type sets.
6843 ASTContext &Context;
6844
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006845 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6846 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006847 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006848
6849public:
6850 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006851 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006852
Mike Stump11289f42009-09-09 15:08:12 +00006853 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006854 : HasNonRecordTypes(false),
6855 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006856 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006857 SemaRef(SemaRef),
6858 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006859
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006861 SourceLocation Loc,
6862 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006863 bool AllowExplicitConversions,
6864 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006865
6866 /// pointer_begin - First pointer type found;
6867 iterator pointer_begin() { return PointerTypes.begin(); }
6868
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006869 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006870 iterator pointer_end() { return PointerTypes.end(); }
6871
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006872 /// member_pointer_begin - First member pointer type found;
6873 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6874
6875 /// member_pointer_end - Past the last member pointer type found;
6876 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6877
Douglas Gregora11693b2008-11-12 17:17:38 +00006878 /// enumeration_begin - First enumeration type found;
6879 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6880
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006881 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006882 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006883
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006884 iterator vector_begin() { return VectorTypes.begin(); }
6885 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006886
6887 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6888 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006889 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006890};
6891
Craig Toppercd7b0332013-07-01 06:29:40 +00006892} // end anonymous namespace
6893
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006894/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006895/// the set of pointer types along with any more-qualified variants of
6896/// that type. For example, if @p Ty is "int const *", this routine
6897/// will add "int const *", "int const volatile *", "int const
6898/// restrict *", and "int const volatile restrict *" to the set of
6899/// pointer types. Returns true if the add of @p Ty itself succeeded,
6900/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006901///
6902/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006903bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006904BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6905 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006906
Douglas Gregora11693b2008-11-12 17:17:38 +00006907 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006908 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006909 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006910
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006911 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006912 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006913 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006914 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006915 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6916 PointeeTy = PTy->getPointeeType();
6917 buildObjCPtr = true;
6918 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006919 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006920 }
6921
Sebastian Redl4990a632009-11-18 20:39:26 +00006922 // Don't add qualified variants of arrays. For one, they're not allowed
6923 // (the qualifier would sink to the element type), and for another, the
6924 // only overload situation where it matters is subscript or pointer +- int,
6925 // and those shouldn't have qualifier variants anyway.
6926 if (PointeeTy->isArrayType())
6927 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006928
John McCall8ccfcb52009-09-24 19:53:00 +00006929 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006930 bool hasVolatile = VisibleQuals.hasVolatile();
6931 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006932
John McCall8ccfcb52009-09-24 19:53:00 +00006933 // Iterate through all strict supersets of BaseCVR.
6934 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6935 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006936 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006937 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006938
6939 // Skip over restrict if no restrict found anywhere in the types, or if
6940 // the type cannot be restrict-qualified.
6941 if ((CVR & Qualifiers::Restrict) &&
6942 (!hasRestrict ||
6943 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6944 continue;
6945
6946 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006947 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006948
6949 // Build qualified pointer type.
6950 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006951 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006952 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006953 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006954 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6955
6956 // Insert qualified pointer type.
6957 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006958 }
6959
6960 return true;
6961}
6962
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006963/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6964/// to the set of pointer types along with any more-qualified variants of
6965/// that type. For example, if @p Ty is "int const *", this routine
6966/// will add "int const *", "int const volatile *", "int const
6967/// restrict *", and "int const volatile restrict *" to the set of
6968/// pointer types. Returns true if the add of @p Ty itself succeeded,
6969/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006970///
6971/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006972bool
6973BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6974 QualType Ty) {
6975 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006976 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006977 return false;
6978
John McCall8ccfcb52009-09-24 19:53:00 +00006979 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6980 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006981
John McCall8ccfcb52009-09-24 19:53:00 +00006982 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006983 // Don't add qualified variants of arrays. For one, they're not allowed
6984 // (the qualifier would sink to the element type), and for another, the
6985 // only overload situation where it matters is subscript or pointer +- int,
6986 // and those shouldn't have qualifier variants anyway.
6987 if (PointeeTy->isArrayType())
6988 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006989 const Type *ClassTy = PointerTy->getClass();
6990
6991 // Iterate through all strict supersets of the pointee type's CVR
6992 // qualifiers.
6993 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6994 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6995 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006996
John McCall8ccfcb52009-09-24 19:53:00 +00006997 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006998 MemberPointerTypes.insert(
6999 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007000 }
7001
7002 return true;
7003}
7004
Douglas Gregora11693b2008-11-12 17:17:38 +00007005/// AddTypesConvertedFrom - Add each of the types to which the type @p
7006/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007007/// primarily interested in pointer types and enumeration types. We also
7008/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007009/// AllowUserConversions is true if we should look at the conversion
7010/// functions of a class type, and AllowExplicitConversions if we
7011/// should also include the explicit conversion functions of a class
7012/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007013void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007014BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007015 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007016 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007017 bool AllowExplicitConversions,
7018 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007019 // Only deal with canonical types.
7020 Ty = Context.getCanonicalType(Ty);
7021
7022 // Look through reference types; they aren't part of the type of an
7023 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007024 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007025 Ty = RefTy->getPointeeType();
7026
John McCall33ddac02011-01-19 10:06:00 +00007027 // If we're dealing with an array type, decay to the pointer.
7028 if (Ty->isArrayType())
7029 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7030
7031 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007032 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007033
Chandler Carruth00a38332010-12-13 01:44:01 +00007034 // Flag if we ever add a non-record type.
7035 const RecordType *TyRec = Ty->getAs<RecordType>();
7036 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7037
Chandler Carruth00a38332010-12-13 01:44:01 +00007038 // Flag if we encounter an arithmetic type.
7039 HasArithmeticOrEnumeralTypes =
7040 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7041
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007042 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7043 PointerTypes.insert(Ty);
7044 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007045 // Insert our type, and its more-qualified variants, into the set
7046 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007047 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007048 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007049 } else if (Ty->isMemberPointerType()) {
7050 // Member pointers are far easier, since the pointee can't be converted.
7051 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7052 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007053 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007054 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007055 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007056 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007057 // We treat vector types as arithmetic types in many contexts as an
7058 // extension.
7059 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007060 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007061 } else if (Ty->isNullPtrType()) {
7062 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007063 } else if (AllowUserConversions && TyRec) {
7064 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007065 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007066 return;
Mike Stump11289f42009-09-09 15:08:12 +00007067
Chandler Carruth00a38332010-12-13 01:44:01 +00007068 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007069 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007070 if (isa<UsingShadowDecl>(D))
7071 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007072
Chandler Carruth00a38332010-12-13 01:44:01 +00007073 // Skip conversion function templates; they don't tell us anything
7074 // about which builtin types we can convert to.
7075 if (isa<FunctionTemplateDecl>(D))
7076 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007077
Chandler Carruth00a38332010-12-13 01:44:01 +00007078 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7079 if (AllowExplicitConversions || !Conv->isExplicit()) {
7080 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7081 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007082 }
7083 }
7084 }
7085}
7086
Douglas Gregor84605ae2009-08-24 13:43:27 +00007087/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7088/// the volatile- and non-volatile-qualified assignment operators for the
7089/// given type to the candidate set.
7090static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7091 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007092 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007093 OverloadCandidateSet &CandidateSet) {
7094 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007095
Douglas Gregor84605ae2009-08-24 13:43:27 +00007096 // T& operator=(T&, T)
7097 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7098 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007100 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007101
Douglas Gregor84605ae2009-08-24 13:43:27 +00007102 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7103 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007104 ParamTypes[0]
7105 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007106 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007107 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007108 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007109 }
7110}
Mike Stump11289f42009-09-09 15:08:12 +00007111
Sebastian Redl1054fae2009-10-25 17:03:50 +00007112/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7113/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007114static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7115 Qualifiers VRQuals;
7116 const RecordType *TyRec;
7117 if (const MemberPointerType *RHSMPType =
7118 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007119 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007120 else
7121 TyRec = ArgExpr->getType()->getAs<RecordType>();
7122 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007123 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007124 VRQuals.addVolatile();
7125 VRQuals.addRestrict();
7126 return VRQuals;
7127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007129 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007130 if (!ClassDecl->hasDefinition())
7131 return VRQuals;
7132
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007133 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007134 if (isa<UsingShadowDecl>(D))
7135 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7136 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007137 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7138 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7139 CanTy = ResTypeRef->getPointeeType();
7140 // Need to go down the pointer/mempointer chain and add qualifiers
7141 // as see them.
7142 bool done = false;
7143 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007144 if (CanTy.isRestrictQualified())
7145 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007146 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7147 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007148 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007149 CanTy->getAs<MemberPointerType>())
7150 CanTy = ResTypeMPtr->getPointeeType();
7151 else
7152 done = true;
7153 if (CanTy.isVolatileQualified())
7154 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007155 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7156 return VRQuals;
7157 }
7158 }
7159 }
7160 return VRQuals;
7161}
John McCall52872982010-11-13 05:51:15 +00007162
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007163namespace {
John McCall52872982010-11-13 05:51:15 +00007164
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007165/// \brief Helper class to manage the addition of builtin operator overload
7166/// candidates. It provides shared state and utility methods used throughout
7167/// the process, as well as a helper method to add each group of builtin
7168/// operator overloads from the standard to a candidate set.
7169class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007170 // Common instance state available to all overload candidate addition methods.
7171 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007172 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007173 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007174 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007175 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007176 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007177
Chandler Carruthc6586e52010-12-12 10:35:00 +00007178 // Define some constants used to index and iterate over the arithemetic types
7179 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007180 // The "promoted arithmetic types" are the arithmetic
7181 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007182 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007183 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007184 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007185 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007186 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007187 LastPromotedArithmeticType = 11;
7188 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007189
Chandler Carruthc6586e52010-12-12 10:35:00 +00007190 /// \brief Get the canonical type for a given arithmetic type index.
7191 CanQualType getArithmeticType(unsigned index) {
7192 assert(index < NumArithmeticTypes);
7193 static CanQualType ASTContext::* const
7194 ArithmeticTypes[NumArithmeticTypes] = {
7195 // Start of promoted types.
7196 &ASTContext::FloatTy,
7197 &ASTContext::DoubleTy,
7198 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007199
Chandler Carruthc6586e52010-12-12 10:35:00 +00007200 // Start of integral types.
7201 &ASTContext::IntTy,
7202 &ASTContext::LongTy,
7203 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007204 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007205 &ASTContext::UnsignedIntTy,
7206 &ASTContext::UnsignedLongTy,
7207 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007208 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007209 // End of promoted types.
7210
7211 &ASTContext::BoolTy,
7212 &ASTContext::CharTy,
7213 &ASTContext::WCharTy,
7214 &ASTContext::Char16Ty,
7215 &ASTContext::Char32Ty,
7216 &ASTContext::SignedCharTy,
7217 &ASTContext::ShortTy,
7218 &ASTContext::UnsignedCharTy,
7219 &ASTContext::UnsignedShortTy,
7220 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007221 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007222 };
7223 return S.Context.*ArithmeticTypes[index];
7224 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007225
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007226 /// \brief Gets the canonical type resulting from the usual arithemetic
7227 /// converions for the given arithmetic types.
7228 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7229 // Accelerator table for performing the usual arithmetic conversions.
7230 // The rules are basically:
7231 // - if either is floating-point, use the wider floating-point
7232 // - if same signedness, use the higher rank
7233 // - if same size, use unsigned of the higher rank
7234 // - use the larger type
7235 // These rules, together with the axiom that higher ranks are
7236 // never smaller, are sufficient to precompute all of these results
7237 // *except* when dealing with signed types of higher rank.
7238 // (we could precompute SLL x UI for all known platforms, but it's
7239 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007240 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007241 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007242 Dep=-1,
7243 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007244 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007245 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007246 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007247/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7248/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7249/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7250/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7251/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7252/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7253/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7254/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7255/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7256/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7257/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007258 };
7259
7260 assert(L < LastPromotedArithmeticType);
7261 assert(R < LastPromotedArithmeticType);
7262 int Idx = ConversionsTable[L][R];
7263
7264 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007265 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007266
7267 // Slow path: we need to compare widths.
7268 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007269 CanQualType LT = getArithmeticType(L),
7270 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007271 unsigned LW = S.Context.getIntWidth(LT),
7272 RW = S.Context.getIntWidth(RT);
7273
7274 // If they're different widths, use the signed type.
7275 if (LW > RW) return LT;
7276 else if (LW < RW) return RT;
7277
7278 // Otherwise, use the unsigned type of the signed type's rank.
7279 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7280 assert(L == SLL || R == SLL);
7281 return S.Context.UnsignedLongLongTy;
7282 }
7283
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007284 /// \brief Helper method to factor out the common pattern of adding overloads
7285 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007286 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007287 bool HasVolatile,
7288 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007289 QualType ParamTypes[2] = {
7290 S.Context.getLValueReferenceType(CandidateTy),
7291 S.Context.IntTy
7292 };
7293
7294 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007295 if (Args.size() == 1)
7296 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007297 else
Richard Smithe54c3072013-05-05 15:51:06 +00007298 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007299
7300 // Use a heuristic to reduce number of builtin candidates in the set:
7301 // add volatile version only if there are conversions to a volatile type.
7302 if (HasVolatile) {
7303 ParamTypes[0] =
7304 S.Context.getLValueReferenceType(
7305 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007306 if (Args.size() == 1)
7307 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007308 else
Richard Smithe54c3072013-05-05 15:51:06 +00007309 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007310 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007311
7312 // Add restrict version only if there are conversions to a restrict type
7313 // and our candidate type is a non-restrict-qualified pointer.
7314 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7315 !CandidateTy.isRestrictQualified()) {
7316 ParamTypes[0]
7317 = S.Context.getLValueReferenceType(
7318 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007319 if (Args.size() == 1)
7320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007321 else
Richard Smithe54c3072013-05-05 15:51:06 +00007322 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007323
7324 if (HasVolatile) {
7325 ParamTypes[0]
7326 = S.Context.getLValueReferenceType(
7327 S.Context.getCVRQualifiedType(CandidateTy,
7328 (Qualifiers::Volatile |
7329 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007330 if (Args.size() == 1)
7331 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007332 else
Richard Smithe54c3072013-05-05 15:51:06 +00007333 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007334 }
7335 }
7336
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007337 }
7338
7339public:
7340 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007341 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007342 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007343 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007344 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007345 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007346 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007347 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007348 HasArithmeticOrEnumeralCandidateType(
7349 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007350 CandidateTypes(CandidateTypes),
7351 CandidateSet(CandidateSet) {
7352 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007353 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007354 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007355 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007356 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007357 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007358 assert(getArithmeticType(FirstPromotedArithmeticType)
7359 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007360 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007361 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007362 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007363 "Invalid last promoted arithmetic type");
7364 }
7365
7366 // C++ [over.built]p3:
7367 //
7368 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7369 // is either volatile or empty, there exist candidate operator
7370 // functions of the form
7371 //
7372 // VQ T& operator++(VQ T&);
7373 // T operator++(VQ T&, int);
7374 //
7375 // C++ [over.built]p4:
7376 //
7377 // For every pair (T, VQ), where T is an arithmetic type other
7378 // than bool, and VQ is either volatile or empty, there exist
7379 // candidate operator functions of the form
7380 //
7381 // VQ T& operator--(VQ T&);
7382 // T operator--(VQ T&, int);
7383 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007384 if (!HasArithmeticOrEnumeralCandidateType)
7385 return;
7386
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007387 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7388 Arith < NumArithmeticTypes; ++Arith) {
7389 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007390 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007391 VisibleTypeConversionsQuals.hasVolatile(),
7392 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007393 }
7394 }
7395
7396 // C++ [over.built]p5:
7397 //
7398 // For every pair (T, VQ), where T is a cv-qualified or
7399 // cv-unqualified object type, and VQ is either volatile or
7400 // empty, there exist candidate operator functions of the form
7401 //
7402 // T*VQ& operator++(T*VQ&);
7403 // T*VQ& operator--(T*VQ&);
7404 // T* operator++(T*VQ&, int);
7405 // T* operator--(T*VQ&, int);
7406 void addPlusPlusMinusMinusPointerOverloads() {
7407 for (BuiltinCandidateTypeSet::iterator
7408 Ptr = CandidateTypes[0].pointer_begin(),
7409 PtrEnd = CandidateTypes[0].pointer_end();
7410 Ptr != PtrEnd; ++Ptr) {
7411 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007412 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007413 continue;
7414
7415 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007416 (!(*Ptr).isVolatileQualified() &&
7417 VisibleTypeConversionsQuals.hasVolatile()),
7418 (!(*Ptr).isRestrictQualified() &&
7419 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007420 }
7421 }
7422
7423 // C++ [over.built]p6:
7424 // For every cv-qualified or cv-unqualified object type T, there
7425 // exist candidate operator functions of the form
7426 //
7427 // T& operator*(T*);
7428 //
7429 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007430 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007431 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007432 // T& operator*(T*);
7433 void addUnaryStarPointerOverloads() {
7434 for (BuiltinCandidateTypeSet::iterator
7435 Ptr = CandidateTypes[0].pointer_begin(),
7436 PtrEnd = CandidateTypes[0].pointer_end();
7437 Ptr != PtrEnd; ++Ptr) {
7438 QualType ParamTy = *Ptr;
7439 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007440 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7441 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007442
Douglas Gregor02824322011-01-26 19:30:28 +00007443 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7444 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7445 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007446
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007447 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007448 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007449 }
7450 }
7451
7452 // C++ [over.built]p9:
7453 // For every promoted arithmetic type T, there exist candidate
7454 // operator functions of the form
7455 //
7456 // T operator+(T);
7457 // T operator-(T);
7458 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007459 if (!HasArithmeticOrEnumeralCandidateType)
7460 return;
7461
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007462 for (unsigned Arith = FirstPromotedArithmeticType;
7463 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007464 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007465 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007466 }
7467
7468 // Extension: We also add these operators for vector types.
7469 for (BuiltinCandidateTypeSet::iterator
7470 Vec = CandidateTypes[0].vector_begin(),
7471 VecEnd = CandidateTypes[0].vector_end();
7472 Vec != VecEnd; ++Vec) {
7473 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007474 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007475 }
7476 }
7477
7478 // C++ [over.built]p8:
7479 // For every type T, there exist candidate operator functions of
7480 // the form
7481 //
7482 // T* operator+(T*);
7483 void addUnaryPlusPointerOverloads() {
7484 for (BuiltinCandidateTypeSet::iterator
7485 Ptr = CandidateTypes[0].pointer_begin(),
7486 PtrEnd = CandidateTypes[0].pointer_end();
7487 Ptr != PtrEnd; ++Ptr) {
7488 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007489 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007490 }
7491 }
7492
7493 // C++ [over.built]p10:
7494 // For every promoted integral type T, there exist candidate
7495 // operator functions of the form
7496 //
7497 // T operator~(T);
7498 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007499 if (!HasArithmeticOrEnumeralCandidateType)
7500 return;
7501
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007502 for (unsigned Int = FirstPromotedIntegralType;
7503 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007504 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007505 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007506 }
7507
7508 // Extension: We also add this operator for vector types.
7509 for (BuiltinCandidateTypeSet::iterator
7510 Vec = CandidateTypes[0].vector_begin(),
7511 VecEnd = CandidateTypes[0].vector_end();
7512 Vec != VecEnd; ++Vec) {
7513 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007514 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007515 }
7516 }
7517
7518 // C++ [over.match.oper]p16:
7519 // For every pointer to member type T, there exist candidate operator
7520 // functions of the form
7521 //
7522 // bool operator==(T,T);
7523 // bool operator!=(T,T);
7524 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7525 /// Set of (canonical) types that we've already handled.
7526 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7527
Richard Smithe54c3072013-05-05 15:51:06 +00007528 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007529 for (BuiltinCandidateTypeSet::iterator
7530 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7531 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7532 MemPtr != MemPtrEnd;
7533 ++MemPtr) {
7534 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007535 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007536 continue;
7537
7538 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007539 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007540 }
7541 }
7542 }
7543
7544 // C++ [over.built]p15:
7545 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007546 // For every T, where T is an enumeration type, a pointer type, or
7547 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007548 //
7549 // bool operator<(T, T);
7550 // bool operator>(T, T);
7551 // bool operator<=(T, T);
7552 // bool operator>=(T, T);
7553 // bool operator==(T, T);
7554 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007555 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007556 // C++ [over.match.oper]p3:
7557 // [...]the built-in candidates include all of the candidate operator
7558 // functions defined in 13.6 that, compared to the given operator, [...]
7559 // do not have the same parameter-type-list as any non-template non-member
7560 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007561 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007562 // Note that in practice, this only affects enumeration types because there
7563 // aren't any built-in candidates of record type, and a user-defined operator
7564 // must have an operand of record or enumeration type. Also, the only other
7565 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007566 // cannot be overloaded for enumeration types, so this is the only place
7567 // where we must suppress candidates like this.
7568 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7569 UserDefinedBinaryOperators;
7570
Richard Smithe54c3072013-05-05 15:51:06 +00007571 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007572 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7573 CandidateTypes[ArgIdx].enumeration_end()) {
7574 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7575 CEnd = CandidateSet.end();
7576 C != CEnd; ++C) {
7577 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7578 continue;
7579
Eli Friedman14f082b2012-09-18 21:52:24 +00007580 if (C->Function->isFunctionTemplateSpecialization())
7581 continue;
7582
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007583 QualType FirstParamType =
7584 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7585 QualType SecondParamType =
7586 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7587
7588 // Skip if either parameter isn't of enumeral type.
7589 if (!FirstParamType->isEnumeralType() ||
7590 !SecondParamType->isEnumeralType())
7591 continue;
7592
7593 // Add this operator to the set of known user-defined operators.
7594 UserDefinedBinaryOperators.insert(
7595 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7596 S.Context.getCanonicalType(SecondParamType)));
7597 }
7598 }
7599 }
7600
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007601 /// Set of (canonical) types that we've already handled.
7602 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7603
Richard Smithe54c3072013-05-05 15:51:06 +00007604 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007605 for (BuiltinCandidateTypeSet::iterator
7606 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7607 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7608 Ptr != PtrEnd; ++Ptr) {
7609 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007610 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007611 continue;
7612
7613 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007614 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007615 }
7616 for (BuiltinCandidateTypeSet::iterator
7617 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7618 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7619 Enum != EnumEnd; ++Enum) {
7620 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7621
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007622 // Don't add the same builtin candidate twice, or if a user defined
7623 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007624 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007625 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7626 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 continue;
7628
7629 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007630 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007631 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007632
7633 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7634 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007635 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007636 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007637 NullPtrTy))) {
7638 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007639 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007640 CandidateSet);
7641 }
7642 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007643 }
7644 }
7645
7646 // C++ [over.built]p13:
7647 //
7648 // For every cv-qualified or cv-unqualified object type T
7649 // there exist candidate operator functions of the form
7650 //
7651 // T* operator+(T*, ptrdiff_t);
7652 // T& operator[](T*, ptrdiff_t); [BELOW]
7653 // T* operator-(T*, ptrdiff_t);
7654 // T* operator+(ptrdiff_t, T*);
7655 // T& operator[](ptrdiff_t, T*); [BELOW]
7656 //
7657 // C++ [over.built]p14:
7658 //
7659 // For every T, where T is a pointer to object type, there
7660 // exist candidate operator functions of the form
7661 //
7662 // ptrdiff_t operator-(T, T);
7663 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7664 /// Set of (canonical) types that we've already handled.
7665 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7666
7667 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007668 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007669 S.Context.getPointerDiffType(),
7670 S.Context.getPointerDiffType(),
7671 };
7672 for (BuiltinCandidateTypeSet::iterator
7673 Ptr = CandidateTypes[Arg].pointer_begin(),
7674 PtrEnd = CandidateTypes[Arg].pointer_end();
7675 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007676 QualType PointeeTy = (*Ptr)->getPointeeType();
7677 if (!PointeeTy->isObjectType())
7678 continue;
7679
Eric Christopher9207a522015-08-21 16:24:01 +00007680 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007681 if (Arg == 0 || Op == OO_Plus) {
7682 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7683 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007684 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007685 }
7686 if (Op == OO_Minus) {
7687 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007688 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007689 continue;
7690
7691 QualType ParamTypes[2] = { *Ptr, *Ptr };
7692 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007693 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007694 }
7695 }
7696 }
7697 }
7698
7699 // C++ [over.built]p12:
7700 //
7701 // For every pair of promoted arithmetic types L and R, there
7702 // exist candidate operator functions of the form
7703 //
7704 // LR operator*(L, R);
7705 // LR operator/(L, R);
7706 // LR operator+(L, R);
7707 // LR operator-(L, R);
7708 // bool operator<(L, R);
7709 // bool operator>(L, R);
7710 // bool operator<=(L, R);
7711 // bool operator>=(L, R);
7712 // bool operator==(L, R);
7713 // bool operator!=(L, R);
7714 //
7715 // where LR is the result of the usual arithmetic conversions
7716 // between types L and R.
7717 //
7718 // C++ [over.built]p24:
7719 //
7720 // For every pair of promoted arithmetic types L and R, there exist
7721 // candidate operator functions of the form
7722 //
7723 // LR operator?(bool, L, R);
7724 //
7725 // where LR is the result of the usual arithmetic conversions
7726 // between types L and R.
7727 // Our candidates ignore the first parameter.
7728 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007729 if (!HasArithmeticOrEnumeralCandidateType)
7730 return;
7731
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007732 for (unsigned Left = FirstPromotedArithmeticType;
7733 Left < LastPromotedArithmeticType; ++Left) {
7734 for (unsigned Right = FirstPromotedArithmeticType;
7735 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007736 QualType LandR[2] = { getArithmeticType(Left),
7737 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007738 QualType Result =
7739 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007740 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007741 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007742 }
7743 }
7744
7745 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7746 // conditional operator for vector types.
7747 for (BuiltinCandidateTypeSet::iterator
7748 Vec1 = CandidateTypes[0].vector_begin(),
7749 Vec1End = CandidateTypes[0].vector_end();
7750 Vec1 != Vec1End; ++Vec1) {
7751 for (BuiltinCandidateTypeSet::iterator
7752 Vec2 = CandidateTypes[1].vector_begin(),
7753 Vec2End = CandidateTypes[1].vector_end();
7754 Vec2 != Vec2End; ++Vec2) {
7755 QualType LandR[2] = { *Vec1, *Vec2 };
7756 QualType Result = S.Context.BoolTy;
7757 if (!isComparison) {
7758 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7759 Result = *Vec1;
7760 else
7761 Result = *Vec2;
7762 }
7763
Richard Smithe54c3072013-05-05 15:51:06 +00007764 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007765 }
7766 }
7767 }
7768
7769 // C++ [over.built]p17:
7770 //
7771 // For every pair of promoted integral types L and R, there
7772 // exist candidate operator functions of the form
7773 //
7774 // LR operator%(L, R);
7775 // LR operator&(L, R);
7776 // LR operator^(L, R);
7777 // LR operator|(L, R);
7778 // L operator<<(L, R);
7779 // L operator>>(L, R);
7780 //
7781 // where LR is the result of the usual arithmetic conversions
7782 // between types L and R.
7783 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007784 if (!HasArithmeticOrEnumeralCandidateType)
7785 return;
7786
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007787 for (unsigned Left = FirstPromotedIntegralType;
7788 Left < LastPromotedIntegralType; ++Left) {
7789 for (unsigned Right = FirstPromotedIntegralType;
7790 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007791 QualType LandR[2] = { getArithmeticType(Left),
7792 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007793 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7794 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007795 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007796 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007797 }
7798 }
7799 }
7800
7801 // C++ [over.built]p20:
7802 //
7803 // For every pair (T, VQ), where T is an enumeration or
7804 // pointer to member type and VQ is either volatile or
7805 // empty, there exist candidate operator functions of the form
7806 //
7807 // VQ T& operator=(VQ T&, T);
7808 void addAssignmentMemberPointerOrEnumeralOverloads() {
7809 /// Set of (canonical) types that we've already handled.
7810 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7811
7812 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7813 for (BuiltinCandidateTypeSet::iterator
7814 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7815 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7816 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007817 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007818 continue;
7819
Richard Smithe54c3072013-05-05 15:51:06 +00007820 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007821 }
7822
7823 for (BuiltinCandidateTypeSet::iterator
7824 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7825 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7826 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007827 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007828 continue;
7829
Richard Smithe54c3072013-05-05 15:51:06 +00007830 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007831 }
7832 }
7833 }
7834
7835 // C++ [over.built]p19:
7836 //
7837 // For every pair (T, VQ), where T is any type and VQ is either
7838 // volatile or empty, there exist candidate operator functions
7839 // of the form
7840 //
7841 // T*VQ& operator=(T*VQ&, T*);
7842 //
7843 // C++ [over.built]p21:
7844 //
7845 // For every pair (T, VQ), where T is a cv-qualified or
7846 // cv-unqualified object type and VQ is either volatile or
7847 // empty, there exist candidate operator functions of the form
7848 //
7849 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7850 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7851 void addAssignmentPointerOverloads(bool isEqualOp) {
7852 /// Set of (canonical) types that we've already handled.
7853 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7854
7855 for (BuiltinCandidateTypeSet::iterator
7856 Ptr = CandidateTypes[0].pointer_begin(),
7857 PtrEnd = CandidateTypes[0].pointer_end();
7858 Ptr != PtrEnd; ++Ptr) {
7859 // If this is operator=, keep track of the builtin candidates we added.
7860 if (isEqualOp)
7861 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007862 else if (!(*Ptr)->getPointeeType()->isObjectType())
7863 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007864
7865 // non-volatile version
7866 QualType ParamTypes[2] = {
7867 S.Context.getLValueReferenceType(*Ptr),
7868 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7869 };
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
Douglas Gregor5bee2582012-06-04 00:15:09 +00007873 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7874 VisibleTypeConversionsQuals.hasVolatile();
7875 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007876 // volatile version
7877 ParamTypes[0] =
7878 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007879 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 /*IsAssigmentOperator=*/isEqualOp);
7881 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007882
7883 if (!(*Ptr).isRestrictQualified() &&
7884 VisibleTypeConversionsQuals.hasRestrict()) {
7885 // restrict version
7886 ParamTypes[0]
7887 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007888 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007889 /*IsAssigmentOperator=*/isEqualOp);
7890
7891 if (NeedVolatile) {
7892 // volatile restrict version
7893 ParamTypes[0]
7894 = S.Context.getLValueReferenceType(
7895 S.Context.getCVRQualifiedType(*Ptr,
7896 (Qualifiers::Volatile |
7897 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007898 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007899 /*IsAssigmentOperator=*/isEqualOp);
7900 }
7901 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007902 }
7903
7904 if (isEqualOp) {
7905 for (BuiltinCandidateTypeSet::iterator
7906 Ptr = CandidateTypes[1].pointer_begin(),
7907 PtrEnd = CandidateTypes[1].pointer_end();
7908 Ptr != PtrEnd; ++Ptr) {
7909 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007910 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007911 continue;
7912
Chandler Carruth8e543b32010-12-12 08:17:55 +00007913 QualType ParamTypes[2] = {
7914 S.Context.getLValueReferenceType(*Ptr),
7915 *Ptr,
7916 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007917
7918 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007919 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007920 /*IsAssigmentOperator=*/true);
7921
Douglas Gregor5bee2582012-06-04 00:15:09 +00007922 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7923 VisibleTypeConversionsQuals.hasVolatile();
7924 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007925 // volatile version
7926 ParamTypes[0] =
7927 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007928 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7929 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007930 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007931
7932 if (!(*Ptr).isRestrictQualified() &&
7933 VisibleTypeConversionsQuals.hasRestrict()) {
7934 // restrict version
7935 ParamTypes[0]
7936 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007937 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7938 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007939
7940 if (NeedVolatile) {
7941 // volatile restrict version
7942 ParamTypes[0]
7943 = S.Context.getLValueReferenceType(
7944 S.Context.getCVRQualifiedType(*Ptr,
7945 (Qualifiers::Volatile |
7946 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007947 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7948 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007949 }
7950 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007951 }
7952 }
7953 }
7954
7955 // C++ [over.built]p18:
7956 //
7957 // For every triple (L, VQ, R), where L is an arithmetic type,
7958 // VQ is either volatile or empty, and R is a promoted
7959 // arithmetic type, there exist candidate operator functions of
7960 // the form
7961 //
7962 // VQ L& operator=(VQ L&, R);
7963 // VQ L& operator*=(VQ L&, R);
7964 // VQ L& operator/=(VQ L&, R);
7965 // VQ L& operator+=(VQ L&, R);
7966 // VQ L& operator-=(VQ L&, R);
7967 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007968 if (!HasArithmeticOrEnumeralCandidateType)
7969 return;
7970
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007971 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7972 for (unsigned Right = FirstPromotedArithmeticType;
7973 Right < LastPromotedArithmeticType; ++Right) {
7974 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007975 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007976
7977 // Add this built-in operator as a candidate (VQ is empty).
7978 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007979 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007980 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007981 /*IsAssigmentOperator=*/isEqualOp);
7982
7983 // Add this built-in operator as a candidate (VQ is 'volatile').
7984 if (VisibleTypeConversionsQuals.hasVolatile()) {
7985 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007986 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007987 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007988 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007989 /*IsAssigmentOperator=*/isEqualOp);
7990 }
7991 }
7992 }
7993
7994 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7995 for (BuiltinCandidateTypeSet::iterator
7996 Vec1 = CandidateTypes[0].vector_begin(),
7997 Vec1End = CandidateTypes[0].vector_end();
7998 Vec1 != Vec1End; ++Vec1) {
7999 for (BuiltinCandidateTypeSet::iterator
8000 Vec2 = CandidateTypes[1].vector_begin(),
8001 Vec2End = CandidateTypes[1].vector_end();
8002 Vec2 != Vec2End; ++Vec2) {
8003 QualType ParamTypes[2];
8004 ParamTypes[1] = *Vec2;
8005 // Add this built-in operator as a candidate (VQ is empty).
8006 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008007 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008008 /*IsAssigmentOperator=*/isEqualOp);
8009
8010 // Add this built-in operator as a candidate (VQ is 'volatile').
8011 if (VisibleTypeConversionsQuals.hasVolatile()) {
8012 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8013 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008014 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008015 /*IsAssigmentOperator=*/isEqualOp);
8016 }
8017 }
8018 }
8019 }
8020
8021 // C++ [over.built]p22:
8022 //
8023 // For every triple (L, VQ, R), where L is an integral type, VQ
8024 // is either volatile or empty, and R is a promoted integral
8025 // type, there exist candidate operator functions of the form
8026 //
8027 // VQ L& operator%=(VQ L&, R);
8028 // VQ L& operator<<=(VQ L&, R);
8029 // VQ L& operator>>=(VQ L&, R);
8030 // VQ L& operator&=(VQ L&, R);
8031 // VQ L& operator^=(VQ L&, R);
8032 // VQ L& operator|=(VQ L&, R);
8033 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008034 if (!HasArithmeticOrEnumeralCandidateType)
8035 return;
8036
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008037 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8038 for (unsigned Right = FirstPromotedIntegralType;
8039 Right < LastPromotedIntegralType; ++Right) {
8040 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008041 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008042
8043 // Add this built-in operator as a candidate (VQ is empty).
8044 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008045 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008046 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008047 if (VisibleTypeConversionsQuals.hasVolatile()) {
8048 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008049 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008050 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8051 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008052 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008053 }
8054 }
8055 }
8056 }
8057
8058 // C++ [over.operator]p23:
8059 //
8060 // There also exist candidate operator functions of the form
8061 //
8062 // bool operator!(bool);
8063 // bool operator&&(bool, bool);
8064 // bool operator||(bool, bool);
8065 void addExclaimOverload() {
8066 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008067 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008068 /*IsAssignmentOperator=*/false,
8069 /*NumContextualBoolArguments=*/1);
8070 }
8071 void addAmpAmpOrPipePipeOverload() {
8072 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008073 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008074 /*IsAssignmentOperator=*/false,
8075 /*NumContextualBoolArguments=*/2);
8076 }
8077
8078 // C++ [over.built]p13:
8079 //
8080 // For every cv-qualified or cv-unqualified object type T there
8081 // exist candidate operator functions of the form
8082 //
8083 // T* operator+(T*, ptrdiff_t); [ABOVE]
8084 // T& operator[](T*, ptrdiff_t);
8085 // T* operator-(T*, ptrdiff_t); [ABOVE]
8086 // T* operator+(ptrdiff_t, T*); [ABOVE]
8087 // T& operator[](ptrdiff_t, T*);
8088 void addSubscriptOverloads() {
8089 for (BuiltinCandidateTypeSet::iterator
8090 Ptr = CandidateTypes[0].pointer_begin(),
8091 PtrEnd = CandidateTypes[0].pointer_end();
8092 Ptr != PtrEnd; ++Ptr) {
8093 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8094 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008095 if (!PointeeType->isObjectType())
8096 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008097
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008098 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8099
8100 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008101 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008102 }
8103
8104 for (BuiltinCandidateTypeSet::iterator
8105 Ptr = CandidateTypes[1].pointer_begin(),
8106 PtrEnd = CandidateTypes[1].pointer_end();
8107 Ptr != PtrEnd; ++Ptr) {
8108 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8109 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008110 if (!PointeeType->isObjectType())
8111 continue;
8112
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008113 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8114
8115 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008116 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008117 }
8118 }
8119
8120 // C++ [over.built]p11:
8121 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8122 // C1 is the same type as C2 or is a derived class of C2, T is an object
8123 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8124 // there exist candidate operator functions of the form
8125 //
8126 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8127 //
8128 // where CV12 is the union of CV1 and CV2.
8129 void addArrowStarOverloads() {
8130 for (BuiltinCandidateTypeSet::iterator
8131 Ptr = CandidateTypes[0].pointer_begin(),
8132 PtrEnd = CandidateTypes[0].pointer_end();
8133 Ptr != PtrEnd; ++Ptr) {
8134 QualType C1Ty = (*Ptr);
8135 QualType C1;
8136 QualifierCollector Q1;
8137 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8138 if (!isa<RecordType>(C1))
8139 continue;
8140 // heuristic to reduce number of builtin candidates in the set.
8141 // Add volatile/restrict version only if there are conversions to a
8142 // volatile/restrict type.
8143 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8144 continue;
8145 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8146 continue;
8147 for (BuiltinCandidateTypeSet::iterator
8148 MemPtr = CandidateTypes[1].member_pointer_begin(),
8149 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8150 MemPtr != MemPtrEnd; ++MemPtr) {
8151 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8152 QualType C2 = QualType(mptr->getClass(), 0);
8153 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008154 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008155 break;
8156 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8157 // build CV12 T&
8158 QualType T = mptr->getPointeeType();
8159 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8160 T.isVolatileQualified())
8161 continue;
8162 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8163 T.isRestrictQualified())
8164 continue;
8165 T = Q1.apply(S.Context, T);
8166 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008167 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008168 }
8169 }
8170 }
8171
8172 // Note that we don't consider the first argument, since it has been
8173 // contextually converted to bool long ago. The candidates below are
8174 // therefore added as binary.
8175 //
8176 // C++ [over.built]p25:
8177 // For every type T, where T is a pointer, pointer-to-member, or scoped
8178 // enumeration type, there exist candidate operator functions of the form
8179 //
8180 // T operator?(bool, T, T);
8181 //
8182 void addConditionalOperatorOverloads() {
8183 /// Set of (canonical) types that we've already handled.
8184 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8185
8186 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8187 for (BuiltinCandidateTypeSet::iterator
8188 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8189 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8190 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008191 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008192 continue;
8193
8194 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008195 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008196 }
8197
8198 for (BuiltinCandidateTypeSet::iterator
8199 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8200 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8201 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008202 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008203 continue;
8204
8205 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008206 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008207 }
8208
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008209 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008210 for (BuiltinCandidateTypeSet::iterator
8211 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8212 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8213 Enum != EnumEnd; ++Enum) {
8214 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8215 continue;
8216
David Blaikie82e95a32014-11-19 07:49:47 +00008217 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008218 continue;
8219
8220 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008221 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008222 }
8223 }
8224 }
8225 }
8226};
8227
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008228} // end anonymous namespace
8229
8230/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8231/// operator overloads to the candidate set (C++ [over.built]), based
8232/// on the operator @p Op and the arguments given. For example, if the
8233/// operator is a binary '+', this routine might add "int
8234/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008235void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8236 SourceLocation OpLoc,
8237 ArrayRef<Expr *> Args,
8238 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008239 // Find all of the types that the arguments can convert to, but only
8240 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008241 // that make use of these types. Also record whether we encounter non-record
8242 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008243 Qualifiers VisibleTypeConversionsQuals;
8244 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008245 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008246 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008247
8248 bool HasNonRecordCandidateType = false;
8249 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008250 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008251 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008252 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008253 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8254 OpLoc,
8255 true,
8256 (Op == OO_Exclaim ||
8257 Op == OO_AmpAmp ||
8258 Op == OO_PipePipe),
8259 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008260 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8261 CandidateTypes[ArgIdx].hasNonRecordTypes();
8262 HasArithmeticOrEnumeralCandidateType =
8263 HasArithmeticOrEnumeralCandidateType ||
8264 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008265 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008266
Chandler Carruth00a38332010-12-13 01:44:01 +00008267 // Exit early when no non-record types have been added to the candidate set
8268 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008269 //
8270 // We can't exit early for !, ||, or &&, since there we have always have
8271 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008272 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008273 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008274 return;
8275
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008276 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008277 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008278 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008279 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008280 CandidateTypes, CandidateSet);
8281
8282 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008283 switch (Op) {
8284 case OO_None:
8285 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008286 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008287
Chandler Carruth5184de02010-12-12 08:51:33 +00008288 case OO_New:
8289 case OO_Delete:
8290 case OO_Array_New:
8291 case OO_Array_Delete:
8292 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008293 llvm_unreachable(
8294 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008295
8296 case OO_Comma:
8297 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008298 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008299 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008300 // -- For the operator ',', the unary operator '&', the
8301 // operator '->', or the operator 'co_await', the
8302 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008303 break;
8304
8305 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008306 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008307 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008308 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008309
8310 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008311 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008312 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008313 } else {
8314 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8315 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8316 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008317 break;
8318
Chandler Carruth5184de02010-12-12 08:51:33 +00008319 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008320 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008321 OpBuilder.addUnaryStarPointerOverloads();
8322 else
8323 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8324 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008325
Chandler Carruth5184de02010-12-12 08:51:33 +00008326 case OO_Slash:
8327 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008328 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008329
8330 case OO_PlusPlus:
8331 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008332 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8333 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008334 break;
8335
Douglas Gregor84605ae2009-08-24 13:43:27 +00008336 case OO_EqualEqual:
8337 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008338 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008339 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008340
Douglas Gregora11693b2008-11-12 17:17:38 +00008341 case OO_Less:
8342 case OO_Greater:
8343 case OO_LessEqual:
8344 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008345 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008346 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8347 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008348
Douglas Gregora11693b2008-11-12 17:17:38 +00008349 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008350 case OO_Caret:
8351 case OO_Pipe:
8352 case OO_LessLess:
8353 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008354 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008355 break;
8356
Chandler Carruth5184de02010-12-12 08:51:33 +00008357 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008358 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008359 // C++ [over.match.oper]p3:
8360 // -- For the operator ',', the unary operator '&', or the
8361 // operator '->', the built-in candidates set is empty.
8362 break;
8363
8364 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8365 break;
8366
8367 case OO_Tilde:
8368 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8369 break;
8370
Douglas Gregora11693b2008-11-12 17:17:38 +00008371 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008372 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008373 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008374
8375 case OO_PlusEqual:
8376 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008377 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008378 // Fall through.
8379
8380 case OO_StarEqual:
8381 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008382 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008383 break;
8384
8385 case OO_PercentEqual:
8386 case OO_LessLessEqual:
8387 case OO_GreaterGreaterEqual:
8388 case OO_AmpEqual:
8389 case OO_CaretEqual:
8390 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008391 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008392 break;
8393
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008394 case OO_Exclaim:
8395 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008396 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008397
Douglas Gregora11693b2008-11-12 17:17:38 +00008398 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008399 case OO_PipePipe:
8400 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008401 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008402
8403 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008404 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008405 break;
8406
8407 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008408 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008409 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008410
8411 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008412 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008413 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8414 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008415 }
8416}
8417
Douglas Gregore254f902009-02-04 00:32:51 +00008418/// \brief Add function candidates found via argument-dependent lookup
8419/// to the set of overloading candidates.
8420///
8421/// This routine performs argument-dependent name lookup based on the
8422/// given function name (which may also be an operator name) and adds
8423/// all of the overload candidates found by ADL to the overload
8424/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008425void
Douglas Gregore254f902009-02-04 00:32:51 +00008426Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008427 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008428 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008429 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008430 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008431 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008432 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008433
John McCall91f61fc2010-01-26 06:04:06 +00008434 // FIXME: This approach for uniquing ADL results (and removing
8435 // redundant candidates from the set) relies on pointer-equality,
8436 // which means we need to key off the canonical decl. However,
8437 // always going back to the canonical decl might not get us the
8438 // right set of default arguments. What default arguments are
8439 // we supposed to consider on ADL candidates, anyway?
8440
Douglas Gregorcabea402009-09-22 15:41:20 +00008441 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008442 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008443
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008444 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008445 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8446 CandEnd = CandidateSet.end();
8447 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008448 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008449 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008450 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008451 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008452 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008453
8454 // For each of the ADL candidates we found, add it to the overload
8455 // set.
John McCall8fe68082010-01-26 07:16:45 +00008456 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008457 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008458 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008459 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008460 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008461
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008462 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8463 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008464 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008465 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008466 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008467 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008468 }
Douglas Gregore254f902009-02-04 00:32:51 +00008469}
8470
George Burgess IV2a6150d2015-10-16 01:17:38 +00008471// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8472// Cand2 for overloading. This function assumes that all of the enable_if attrs
8473// on Cand1 and Cand2 have conditions that evaluate to true.
8474//
8475// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8476// Cand1's first N enable_if attributes have precisely the same conditions as
8477// Cand2's first N enable_if attributes (where N = the number of enable_if
8478// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8479static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8480 const FunctionDecl *Cand2) {
8481
8482 // FIXME: The next several lines are just
8483 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8484 // instead of reverse order which is how they're stored in the AST.
8485 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8486 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8487
8488 // Candidate 1 is better if it has strictly more attributes and
8489 // the common sequence is identical.
8490 if (Cand1Attrs.size() <= Cand2Attrs.size())
8491 return false;
8492
8493 auto Cand1I = Cand1Attrs.begin();
8494 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8495 for (auto &Cand2A : Cand2Attrs) {
8496 Cand1ID.clear();
8497 Cand2ID.clear();
8498
8499 auto &Cand1A = *Cand1I++;
8500 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8501 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8502 if (Cand1ID != Cand2ID)
8503 return false;
8504 }
8505
8506 return true;
8507}
8508
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008509/// isBetterOverloadCandidate - Determines whether the first overload
8510/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008511bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8512 const OverloadCandidate &Cand2,
8513 SourceLocation Loc,
8514 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008515 // Define viable functions to be better candidates than non-viable
8516 // functions.
8517 if (!Cand2.Viable)
8518 return Cand1.Viable;
8519 else if (!Cand1.Viable)
8520 return false;
8521
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008522 // C++ [over.match.best]p1:
8523 //
8524 // -- if F is a static member function, ICS1(F) is defined such
8525 // that ICS1(F) is neither better nor worse than ICS1(G) for
8526 // any function G, and, symmetrically, ICS1(G) is neither
8527 // better nor worse than ICS1(F).
8528 unsigned StartArg = 0;
8529 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8530 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008531
Douglas Gregord3cb3562009-07-07 23:38:56 +00008532 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008533 // A viable function F1 is defined to be a better function than another
8534 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008535 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008536 unsigned NumArgs = Cand1.NumConversions;
8537 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008538 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008539 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008540 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008541 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008542 Cand2.Conversions[ArgIdx])) {
8543 case ImplicitConversionSequence::Better:
8544 // Cand1 has a better conversion sequence.
8545 HasBetterConversion = true;
8546 break;
8547
8548 case ImplicitConversionSequence::Worse:
8549 // Cand1 can't be better than Cand2.
8550 return false;
8551
8552 case ImplicitConversionSequence::Indistinguishable:
8553 // Do nothing.
8554 break;
8555 }
8556 }
8557
Mike Stump11289f42009-09-09 15:08:12 +00008558 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008559 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008560 if (HasBetterConversion)
8561 return true;
8562
Douglas Gregora1f013e2008-11-07 22:36:19 +00008563 // -- the context is an initialization by user-defined conversion
8564 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8565 // from the return type of F1 to the destination type (i.e.,
8566 // the type of the entity being initialized) is a better
8567 // conversion sequence than the standard conversion sequence
8568 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008569 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008570 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008571 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008572 // First check whether we prefer one of the conversion functions over the
8573 // other. This only distinguishes the results in non-standard, extension
8574 // cases such as the conversion from a lambda closure type to a function
8575 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008576 ImplicitConversionSequence::CompareKind Result =
8577 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8578 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008579 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008580 Cand1.FinalConversion,
8581 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008582
Richard Smithec2748a2014-05-17 04:36:39 +00008583 if (Result != ImplicitConversionSequence::Indistinguishable)
8584 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008585
8586 // FIXME: Compare kind of reference binding if conversion functions
8587 // convert to a reference type used in direct reference binding, per
8588 // C++14 [over.match.best]p1 section 2 bullet 3.
8589 }
8590
8591 // -- F1 is a non-template function and F2 is a function template
8592 // specialization, or, if not that,
8593 bool Cand1IsSpecialization = Cand1.Function &&
8594 Cand1.Function->getPrimaryTemplate();
8595 bool Cand2IsSpecialization = Cand2.Function &&
8596 Cand2.Function->getPrimaryTemplate();
8597 if (Cand1IsSpecialization != Cand2IsSpecialization)
8598 return Cand2IsSpecialization;
8599
8600 // -- F1 and F2 are function template specializations, and the function
8601 // template for F1 is more specialized than the template for F2
8602 // according to the partial ordering rules described in 14.5.5.2, or,
8603 // if not that,
8604 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8605 if (FunctionTemplateDecl *BetterTemplate
8606 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8607 Cand2.Function->getPrimaryTemplate(),
8608 Loc,
8609 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8610 : TPOC_Call,
8611 Cand1.ExplicitCallArguments,
8612 Cand2.ExplicitCallArguments))
8613 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008614 }
8615
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008616 // Check for enable_if value-based overload resolution.
8617 if (Cand1.Function && Cand2.Function &&
8618 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008619 Cand2.Function->hasAttr<EnableIfAttr>()))
8620 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008621
Artem Belevich94a55e82015-09-22 17:22:59 +00008622 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8623 Cand1.Function && Cand2.Function) {
8624 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8625 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8626 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8627 }
8628
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008629 bool HasPS1 = Cand1.Function != nullptr &&
8630 functionHasPassObjectSizeParams(Cand1.Function);
8631 bool HasPS2 = Cand2.Function != nullptr &&
8632 functionHasPassObjectSizeParams(Cand2.Function);
8633 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008634}
8635
Richard Smith2dbe4042015-11-04 19:26:32 +00008636/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008637/// name lookup and overload resolution. This applies when the same internal/no
8638/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008639/// the same header). In such a case, we don't consider the declarations to
8640/// declare the same entity, but we also don't want lookups with both
8641/// declarations visible to be ambiguous in some cases (this happens when using
8642/// a modularized libstdc++).
8643bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8644 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008645 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8646 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8647 if (!VA || !VB)
8648 return false;
8649
8650 // The declarations must be declaring the same name as an internal linkage
8651 // entity in different modules.
8652 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8653 VB->getDeclContext()->getRedeclContext()) ||
8654 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8655 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8656 VA->isExternallyVisible() || VB->isExternallyVisible())
8657 return false;
8658
8659 // Check that the declarations appear to be equivalent.
8660 //
8661 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8662 // For constants and functions, we should check the initializer or body is
8663 // the same. For non-constant variables, we shouldn't allow it at all.
8664 if (Context.hasSameType(VA->getType(), VB->getType()))
8665 return true;
8666
8667 // Enum constants within unnamed enumerations will have different types, but
8668 // may still be similar enough to be interchangeable for our purposes.
8669 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8670 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8671 // Only handle anonymous enums. If the enumerations were named and
8672 // equivalent, they would have been merged to the same type.
8673 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8674 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8675 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8676 !Context.hasSameType(EnumA->getIntegerType(),
8677 EnumB->getIntegerType()))
8678 return false;
8679 // Allow this only if the value is the same for both enumerators.
8680 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8681 }
8682 }
8683
8684 // Nothing else is sufficiently similar.
8685 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008686}
8687
8688void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8689 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8690 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8691
8692 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8693 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8694 << !M << (M ? M->getFullModuleName() : "");
8695
8696 for (auto *E : Equiv) {
8697 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8698 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8699 << !M << (M ? M->getFullModuleName() : "");
8700 }
Richard Smith896c66e2015-10-21 07:13:52 +00008701}
8702
Mike Stump11289f42009-09-09 15:08:12 +00008703/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008704/// within an overload candidate set.
8705///
James Dennettffad8b72012-06-22 08:10:18 +00008706/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008707/// which overload resolution occurs.
8708///
James Dennettffad8b72012-06-22 08:10:18 +00008709/// \param Best If overload resolution was successful or found a deleted
8710/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008711///
8712/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008713OverloadingResult
8714OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008715 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008716 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008717 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008718 Best = end();
8719 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8720 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008721 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008722 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008723 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008724 }
8725
8726 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008727 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008728 return OR_No_Viable_Function;
8729
Richard Smith2dbe4042015-11-04 19:26:32 +00008730 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008731
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008732 // Make sure that this function is better than every other viable
8733 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008734 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008735 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008736 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008737 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008738 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008739 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8740 Cand->Function)) {
8741 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008742 continue;
8743 }
8744
John McCall5c32be02010-08-24 20:38:10 +00008745 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008746 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008747 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008748 }
Mike Stump11289f42009-09-09 15:08:12 +00008749
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008750 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008751 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008752 (Best->Function->isDeleted() ||
8753 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008754 return OR_Deleted;
8755
Richard Smith2dbe4042015-11-04 19:26:32 +00008756 if (!EquivalentCands.empty())
8757 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8758 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008759
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008760 return OR_Success;
8761}
8762
John McCall53262c92010-01-12 02:15:36 +00008763namespace {
8764
8765enum OverloadCandidateKind {
8766 oc_function,
8767 oc_method,
8768 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008769 oc_function_template,
8770 oc_method_template,
8771 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008772 oc_implicit_default_constructor,
8773 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008774 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008775 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008776 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008777 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008778};
8779
John McCalle1ac8d12010-01-13 00:25:19 +00008780OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8781 FunctionDecl *Fn,
8782 std::string &Description) {
8783 bool isTemplate = false;
8784
8785 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8786 isTemplate = true;
8787 Description = S.getTemplateArgumentBindingsText(
8788 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8789 }
John McCallfd0b2f82010-01-06 09:43:14 +00008790
8791 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008792 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008793 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008794
Sebastian Redl08905022011-02-05 19:23:19 +00008795 if (Ctor->getInheritedConstructor())
8796 return oc_implicit_inherited_constructor;
8797
Alexis Hunt119c10e2011-05-25 23:16:36 +00008798 if (Ctor->isDefaultConstructor())
8799 return oc_implicit_default_constructor;
8800
8801 if (Ctor->isMoveConstructor())
8802 return oc_implicit_move_constructor;
8803
8804 assert(Ctor->isCopyConstructor() &&
8805 "unexpected sort of implicit constructor");
8806 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008807 }
8808
8809 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8810 // This actually gets spelled 'candidate function' for now, but
8811 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008812 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008813 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008814
Alexis Hunt119c10e2011-05-25 23:16:36 +00008815 if (Meth->isMoveAssignmentOperator())
8816 return oc_implicit_move_assignment;
8817
Douglas Gregor12695102012-02-10 08:36:38 +00008818 if (Meth->isCopyAssignmentOperator())
8819 return oc_implicit_copy_assignment;
8820
8821 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8822 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008823 }
8824
John McCalle1ac8d12010-01-13 00:25:19 +00008825 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008826}
8827
Larisse Voufo98b20f12013-07-19 23:00:19 +00008828void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008829 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8830 if (!Ctor) return;
8831
8832 Ctor = Ctor->getInheritedConstructor();
8833 if (!Ctor) return;
8834
8835 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8836}
8837
John McCall53262c92010-01-12 02:15:36 +00008838} // end anonymous namespace
8839
George Burgess IV5f21c712015-10-12 19:57:04 +00008840static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8841 const FunctionDecl *FD) {
8842 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8843 bool AlwaysTrue;
8844 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8845 return false;
8846 if (!AlwaysTrue)
8847 return false;
8848 }
8849 return true;
8850}
8851
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008852/// \brief Returns true if we can take the address of the function.
8853///
8854/// \param Complain - If true, we'll emit a diagnostic
8855/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8856/// we in overload resolution?
8857/// \param Loc - The location of the statement we're complaining about. Ignored
8858/// if we're not complaining, or if we're in overload resolution.
8859static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8860 bool Complain,
8861 bool InOverloadResolution,
8862 SourceLocation Loc) {
8863 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8864 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008865 if (InOverloadResolution)
8866 S.Diag(FD->getLocStart(),
8867 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8868 else
8869 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8870 }
8871 return false;
8872 }
8873
8874 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8875 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8876 if (I == FD->param_end())
8877 return true;
8878
8879 if (Complain) {
8880 // Add one to ParamNo because it's user-facing
8881 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8882 if (InOverloadResolution)
8883 S.Diag(FD->getLocation(),
8884 diag::note_ovl_candidate_has_pass_object_size_params)
8885 << ParamNo;
8886 else
8887 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8888 << FD << ParamNo;
8889 }
8890 return false;
8891}
8892
8893static bool checkAddressOfCandidateIsAvailable(Sema &S,
8894 const FunctionDecl *FD) {
8895 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8896 /*InOverloadResolution=*/true,
8897 /*Loc=*/SourceLocation());
8898}
8899
8900bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8901 bool Complain,
8902 SourceLocation Loc) {
8903 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8904 /*InOverloadResolution=*/false,
8905 Loc);
8906}
8907
John McCall53262c92010-01-12 02:15:36 +00008908// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008909void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8910 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008911 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8912 return;
8913
John McCalle1ac8d12010-01-13 00:25:19 +00008914 std::string FnDesc;
8915 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008916 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8917 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008918
8919 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008920 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008921 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008922}
8923
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008924// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008925// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008926void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8927 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008928 assert(OverloadedExpr->getType() == Context.OverloadTy);
8929
8930 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8931 OverloadExpr *OvlExpr = Ovl.Expression;
8932
8933 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8934 IEnd = OvlExpr->decls_end();
8935 I != IEnd; ++I) {
8936 if (FunctionTemplateDecl *FunTmpl =
8937 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008938 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8939 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008940 } else if (FunctionDecl *Fun
8941 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008942 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008943 }
8944 }
8945}
8946
John McCall0d1da222010-01-12 00:44:57 +00008947/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8948/// "lead" diagnostic; it will be given two arguments, the source and
8949/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008950void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8951 Sema &S,
8952 SourceLocation CaretLoc,
8953 const PartialDiagnostic &PDiag) const {
8954 S.Diag(CaretLoc, PDiag)
8955 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008956 // FIXME: The note limiting machinery is borrowed from
8957 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8958 // refactoring here.
8959 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8960 unsigned CandsShown = 0;
8961 AmbiguousConversionSequence::const_iterator I, E;
8962 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8963 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8964 break;
8965 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008966 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008967 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008968 if (I != E)
8969 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008970}
8971
Richard Smith17c00b42014-11-12 01:24:00 +00008972static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008973 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00008974 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8975 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008976 assert(Cand->Function && "for now, candidate must be a function");
8977 FunctionDecl *Fn = Cand->Function;
8978
8979 // There's a conversion slot for the object argument if this is a
8980 // non-constructor method. Note that 'I' corresponds the
8981 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008982 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008983 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008984 if (I == 0)
8985 isObjectArgument = true;
8986 else
8987 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008988 }
8989
John McCalle1ac8d12010-01-13 00:25:19 +00008990 std::string FnDesc;
8991 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8992
John McCall6a61b522010-01-13 09:16:55 +00008993 Expr *FromExpr = Conv.Bad.FromExpr;
8994 QualType FromTy = Conv.Bad.getFromType();
8995 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008996
John McCallfb7ad0f2010-02-02 02:42:52 +00008997 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008998 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008999 Expr *E = FromExpr->IgnoreParens();
9000 if (isa<UnaryOperator>(E))
9001 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009002 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009003
9004 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9005 << (unsigned) FnKind << FnDesc
9006 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9007 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009008 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00009009 return;
9010 }
9011
John McCall6d174642010-01-23 08:10:49 +00009012 // Do some hand-waving analysis to see if the non-viability is due
9013 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009014 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9015 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9016 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9017 CToTy = RT->getPointeeType();
9018 else {
9019 // TODO: detect and diagnose the full richness of const mismatches.
9020 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9021 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
9022 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
9023 }
9024
9025 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9026 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009027 Qualifiers FromQs = CFromTy.getQualifiers();
9028 Qualifiers ToQs = CToTy.getQualifiers();
9029
9030 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9031 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9032 << (unsigned) FnKind << FnDesc
9033 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9034 << FromTy
9035 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9036 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009037 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009038 return;
9039 }
9040
John McCall31168b02011-06-15 23:02:42 +00009041 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009042 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009043 << (unsigned) FnKind << FnDesc
9044 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9045 << FromTy
9046 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9047 << (unsigned) isObjectArgument << I+1;
9048 MaybeEmitInheritedConstructorNote(S, Fn);
9049 return;
9050 }
9051
Douglas Gregoraec25842011-04-26 23:16:46 +00009052 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9053 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9054 << (unsigned) FnKind << FnDesc
9055 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9056 << FromTy
9057 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9058 << (unsigned) isObjectArgument << I+1;
9059 MaybeEmitInheritedConstructorNote(S, Fn);
9060 return;
9061 }
9062
John McCall47000992010-01-14 03:28:57 +00009063 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9064 assert(CVR && "unexpected qualifiers mismatch");
9065
9066 if (isObjectArgument) {
9067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9068 << (unsigned) FnKind << FnDesc
9069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9070 << FromTy << (CVR - 1);
9071 } else {
9072 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9073 << (unsigned) FnKind << FnDesc
9074 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9075 << FromTy << (CVR - 1) << I+1;
9076 }
Sebastian Redl08905022011-02-05 19:23:19 +00009077 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009078 return;
9079 }
9080
Sebastian Redla72462c2011-09-24 17:48:32 +00009081 // Special diagnostic for failure to convert an initializer list, since
9082 // telling the user that it has type void is not useful.
9083 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9084 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9085 << (unsigned) FnKind << FnDesc
9086 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9087 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9088 MaybeEmitInheritedConstructorNote(S, Fn);
9089 return;
9090 }
9091
John McCall6d174642010-01-23 08:10:49 +00009092 // Diagnose references or pointers to incomplete types differently,
9093 // since it's far from impossible that the incompleteness triggered
9094 // the failure.
9095 QualType TempFromTy = FromTy.getNonReferenceType();
9096 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9097 TempFromTy = PTy->getPointeeType();
9098 if (TempFromTy->isIncompleteType()) {
9099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9100 << (unsigned) FnKind << FnDesc
9101 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9102 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009103 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009104 return;
9105 }
9106
Douglas Gregor56f2e342010-06-30 23:01:39 +00009107 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009108 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009109 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9110 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9111 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9112 FromPtrTy->getPointeeType()) &&
9113 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9114 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009115 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009116 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009117 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009118 }
9119 } else if (const ObjCObjectPointerType *FromPtrTy
9120 = FromTy->getAs<ObjCObjectPointerType>()) {
9121 if (const ObjCObjectPointerType *ToPtrTy
9122 = ToTy->getAs<ObjCObjectPointerType>())
9123 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9124 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9125 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9126 FromPtrTy->getPointeeType()) &&
9127 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009128 BaseToDerivedConversion = 2;
9129 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009130 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9131 !FromTy->isIncompleteType() &&
9132 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009133 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009134 BaseToDerivedConversion = 3;
9135 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9136 ToTy.getNonReferenceType().getCanonicalType() ==
9137 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009138 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9139 << (unsigned) FnKind << FnDesc
9140 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9141 << (unsigned) isObjectArgument << I + 1;
9142 MaybeEmitInheritedConstructorNote(S, Fn);
9143 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009144 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009146
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009147 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009148 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009149 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009150 << (unsigned) FnKind << FnDesc
9151 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009152 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009153 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009154 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009155 return;
9156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009157
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009158 if (isa<ObjCObjectPointerType>(CFromTy) &&
9159 isa<PointerType>(CToTy)) {
9160 Qualifiers FromQs = CFromTy.getQualifiers();
9161 Qualifiers ToQs = CToTy.getQualifiers();
9162 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9164 << (unsigned) FnKind << FnDesc
9165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9166 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9167 MaybeEmitInheritedConstructorNote(S, Fn);
9168 return;
9169 }
9170 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009171
9172 if (TakingCandidateAddress &&
9173 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9174 return;
9175
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009176 // Emit the generic diagnostic and, optionally, add the hints to it.
9177 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9178 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009179 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009180 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9181 << (unsigned) (Cand->Fix.Kind);
9182
9183 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009184 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9185 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009186 FDiag << *HI;
9187 S.Diag(Fn->getLocation(), FDiag);
9188
Sebastian Redl08905022011-02-05 19:23:19 +00009189 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009190}
9191
Larisse Voufo98b20f12013-07-19 23:00:19 +00009192/// Additional arity mismatch diagnosis specific to a function overload
9193/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9194/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009195static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9196 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009197 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009198 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009199
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009200 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009201 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009202 // right number of arguments, because only overloaded operators have
9203 // the weird behavior of overloading member and non-member functions.
9204 // Just don't report anything.
9205 if (Fn->isInvalidDecl() &&
9206 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009207 return true;
9208
9209 if (NumArgs < MinParams) {
9210 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9211 (Cand->FailureKind == ovl_fail_bad_deduction &&
9212 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9213 } else {
9214 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9215 (Cand->FailureKind == ovl_fail_bad_deduction &&
9216 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9217 }
9218
9219 return false;
9220}
9221
9222/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009223static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009224 assert(isa<FunctionDecl>(D) &&
9225 "The templated declaration should at least be a function"
9226 " when diagnosing bad template argument deduction due to too many"
9227 " or too few arguments");
9228
9229 FunctionDecl *Fn = cast<FunctionDecl>(D);
9230
9231 // TODO: treat calls to a missing default constructor as a special case
9232 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9233 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009234
John McCall6a61b522010-01-13 09:16:55 +00009235 // at least / at most / exactly
9236 unsigned mode, modeCount;
9237 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009238 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9239 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009240 mode = 0; // "at least"
9241 else
9242 mode = 2; // "exactly"
9243 modeCount = MinParams;
9244 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009245 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009246 mode = 1; // "at most"
9247 else
9248 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009249 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009250 }
9251
9252 std::string Description;
9253 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9254
Richard Smith10ff50d2012-05-11 05:16:41 +00009255 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9256 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009257 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9258 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009259 else
9260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009261 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9262 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009263 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009264}
9265
Larisse Voufo98b20f12013-07-19 23:00:19 +00009266/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009267static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9268 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009269 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9270 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9271}
Larisse Voufo47c08452013-07-19 22:53:23 +00009272
Richard Smith17c00b42014-11-12 01:24:00 +00009273static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009274 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9275 return FD->getDescribedFunctionTemplate();
9276 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9277 return RD->getDescribedClassTemplate();
9278
9279 llvm_unreachable("Unsupported: Getting the described template declaration"
9280 " for bad deduction diagnosis");
9281}
9282
9283/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009284static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9285 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009286 unsigned NumArgs,
9287 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009288 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009289 NamedDecl *ParamD;
9290 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9291 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9292 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009293 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009294 case Sema::TDK_Success:
9295 llvm_unreachable("TDK_success while diagnosing bad deduction");
9296
9297 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009298 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009299 S.Diag(Templated->getLocation(),
9300 diag::note_ovl_candidate_incomplete_deduction)
9301 << ParamD->getDeclName();
9302 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009303 return;
9304 }
9305
John McCall42d7d192010-08-05 09:05:08 +00009306 case Sema::TDK_Underqualified: {
9307 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9308 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9309
Larisse Voufo98b20f12013-07-19 23:00:19 +00009310 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009311
9312 // Param will have been canonicalized, but it should just be a
9313 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009314 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009315 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009316 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009317 assert(S.Context.hasSameType(Param, NonCanonParam));
9318
9319 // Arg has also been canonicalized, but there's nothing we can do
9320 // about that. It also doesn't matter as much, because it won't
9321 // have any template parameters in it (because deduction isn't
9322 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009323 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009324
Larisse Voufo98b20f12013-07-19 23:00:19 +00009325 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9326 << ParamD->getDeclName() << Arg << NonCanonParam;
9327 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009328 return;
9329 }
9330
9331 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009332 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009333 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009334 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009335 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009336 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009337 which = 1;
9338 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009339 which = 2;
9340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009341
Larisse Voufo98b20f12013-07-19 23:00:19 +00009342 S.Diag(Templated->getLocation(),
9343 diag::note_ovl_candidate_inconsistent_deduction)
9344 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9345 << *DeductionFailure.getSecondArg();
9346 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009347 return;
9348 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009349
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009350 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009351 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009352 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009353 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009354 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009355 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009356 else {
9357 int index = 0;
9358 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9359 index = TTP->getIndex();
9360 else if (NonTypeTemplateParmDecl *NTTP
9361 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9362 index = NTTP->getIndex();
9363 else
9364 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009365 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009366 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009367 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009368 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009369 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009370 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009371
Douglas Gregor02eb4832010-05-08 18:13:28 +00009372 case Sema::TDK_TooManyArguments:
9373 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009374 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009375 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009376
9377 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009378 S.Diag(Templated->getLocation(),
9379 diag::note_ovl_candidate_instantiation_depth);
9380 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009381 return;
9382
9383 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009384 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009385 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009386 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009387 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009388 TemplateArgString = " ";
9389 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009390 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009391 }
9392
Richard Smith6f8d2c62012-05-09 05:17:00 +00009393 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009394 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009395 if (PDiag && PDiag->second.getDiagID() ==
9396 diag::err_typename_nested_not_found_enable_if) {
9397 // FIXME: Use the source range of the condition, and the fully-qualified
9398 // name of the enable_if template. These are both present in PDiag.
9399 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9400 << "'enable_if'" << TemplateArgString;
9401 return;
9402 }
9403
Richard Smith9ca64612012-05-07 09:03:25 +00009404 // Format the SFINAE diagnostic into the argument string.
9405 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9406 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009407 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009408 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009409 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009410 SFINAEArgString = ": ";
9411 R = SourceRange(PDiag->first, PDiag->first);
9412 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9413 }
9414
Larisse Voufo98b20f12013-07-19 23:00:19 +00009415 S.Diag(Templated->getLocation(),
9416 diag::note_ovl_candidate_substitution_failure)
9417 << TemplateArgString << SFINAEArgString << R;
9418 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009419 return;
9420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009421
Richard Smith8c6eeb92013-01-31 04:03:12 +00009422 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009423 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9424 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009425 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009426 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009427 return;
9428 }
9429
Richard Smith9b534542015-12-31 02:02:54 +00009430 case Sema::TDK_DeducedMismatch: {
9431 // Format the template argument list into the argument string.
9432 SmallString<128> TemplateArgString;
9433 if (TemplateArgumentList *Args =
9434 DeductionFailure.getTemplateArgumentList()) {
9435 TemplateArgString = " ";
9436 TemplateArgString += S.getTemplateArgumentBindingsText(
9437 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9438 }
9439
9440 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9441 << (*DeductionFailure.getCallArgIndex() + 1)
9442 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9443 << TemplateArgString;
9444 break;
9445 }
9446
Richard Trieue3732352013-04-08 21:11:40 +00009447 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009448 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009449 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9450 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009451 if (FirstTA.getKind() == TemplateArgument::Template &&
9452 SecondTA.getKind() == TemplateArgument::Template) {
9453 TemplateName FirstTN = FirstTA.getAsTemplate();
9454 TemplateName SecondTN = SecondTA.getAsTemplate();
9455 if (FirstTN.getKind() == TemplateName::Template &&
9456 SecondTN.getKind() == TemplateName::Template) {
9457 if (FirstTN.getAsTemplateDecl()->getName() ==
9458 SecondTN.getAsTemplateDecl()->getName()) {
9459 // FIXME: This fixes a bad diagnostic where both templates are named
9460 // the same. This particular case is a bit difficult since:
9461 // 1) It is passed as a string to the diagnostic printer.
9462 // 2) The diagnostic printer only attempts to find a better
9463 // name for types, not decls.
9464 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009465 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009466 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9467 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9468 return;
9469 }
9470 }
9471 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009472
9473 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9474 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9475 return;
9476
Faisal Vali2b391ab2013-09-26 19:54:12 +00009477 // FIXME: For generic lambda parameters, check if the function is a lambda
9478 // call operator, and if so, emit a prettier and more informative
9479 // diagnostic that mentions 'auto' and lambda in addition to
9480 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009481 S.Diag(Templated->getLocation(),
9482 diag::note_ovl_candidate_non_deduced_mismatch)
9483 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009484 return;
Richard Trieue3732352013-04-08 21:11:40 +00009485 }
John McCall8b9ed552010-02-01 18:53:26 +00009486 // TODO: diagnose these individually, then kill off
9487 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009488 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009489 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9490 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009491 return;
9492 }
9493}
9494
Larisse Voufo98b20f12013-07-19 23:00:19 +00009495/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009496static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009497 unsigned NumArgs,
9498 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009499 unsigned TDK = Cand->DeductionFailure.Result;
9500 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9501 if (CheckArityMismatch(S, Cand, NumArgs))
9502 return;
9503 }
9504 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009505 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009506}
9507
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009508/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009509static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009510 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9511 FunctionDecl *Callee = Cand->Function;
9512
9513 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9514 CalleeTarget = S.IdentifyCUDATarget(Callee);
9515
9516 std::string FnDesc;
9517 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9518
9519 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009520 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9521
9522 // This could be an implicit constructor for which we could not infer the
9523 // target due to a collsion. Diagnose that case.
9524 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9525 if (Meth != nullptr && Meth->isImplicit()) {
9526 CXXRecordDecl *ParentClass = Meth->getParent();
9527 Sema::CXXSpecialMember CSM;
9528
9529 switch (FnKind) {
9530 default:
9531 return;
9532 case oc_implicit_default_constructor:
9533 CSM = Sema::CXXDefaultConstructor;
9534 break;
9535 case oc_implicit_copy_constructor:
9536 CSM = Sema::CXXCopyConstructor;
9537 break;
9538 case oc_implicit_move_constructor:
9539 CSM = Sema::CXXMoveConstructor;
9540 break;
9541 case oc_implicit_copy_assignment:
9542 CSM = Sema::CXXCopyAssignment;
9543 break;
9544 case oc_implicit_move_assignment:
9545 CSM = Sema::CXXMoveAssignment;
9546 break;
9547 };
9548
9549 bool ConstRHS = false;
9550 if (Meth->getNumParams()) {
9551 if (const ReferenceType *RT =
9552 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9553 ConstRHS = RT->getPointeeType().isConstQualified();
9554 }
9555 }
9556
9557 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9558 /* ConstRHS */ ConstRHS,
9559 /* Diagnose */ true);
9560 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009561}
9562
Richard Smith17c00b42014-11-12 01:24:00 +00009563static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009564 FunctionDecl *Callee = Cand->Function;
9565 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9566
9567 S.Diag(Callee->getLocation(),
9568 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9569 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9570}
9571
John McCall8b9ed552010-02-01 18:53:26 +00009572/// Generates a 'note' diagnostic for an overload candidate. We've
9573/// already generated a primary error at the call site.
9574///
9575/// It really does need to be a single diagnostic with its caret
9576/// pointed at the candidate declaration. Yes, this creates some
9577/// major challenges of technical writing. Yes, this makes pointing
9578/// out problems with specific arguments quite awkward. It's still
9579/// better than generating twenty screens of text for every failed
9580/// overload.
9581///
9582/// It would be great to be able to express per-candidate problems
9583/// more richly for those diagnostic clients that cared, but we'd
9584/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009585static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009586 unsigned NumArgs,
9587 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009588 FunctionDecl *Fn = Cand->Function;
9589
John McCall12f97bc2010-01-08 04:41:39 +00009590 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009591 if (Cand->Viable && (Fn->isDeleted() ||
9592 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009593 std::string FnDesc;
9594 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009595
9596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009597 << FnKind << FnDesc
9598 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009599 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009600 return;
John McCall12f97bc2010-01-08 04:41:39 +00009601 }
9602
John McCalle1ac8d12010-01-13 00:25:19 +00009603 // We don't really have anything else to say about viable candidates.
9604 if (Cand->Viable) {
9605 S.NoteOverloadCandidate(Fn);
9606 return;
9607 }
John McCall0d1da222010-01-12 00:44:57 +00009608
John McCall6a61b522010-01-13 09:16:55 +00009609 switch (Cand->FailureKind) {
9610 case ovl_fail_too_many_arguments:
9611 case ovl_fail_too_few_arguments:
9612 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009613
John McCall6a61b522010-01-13 09:16:55 +00009614 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009615 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009616
John McCall578a1f82014-12-14 01:46:53 +00009617 case ovl_fail_illegal_constructor: {
9618 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9619 << (Fn->getPrimaryTemplate() ? 1 : 0);
9620 MaybeEmitInheritedConstructorNote(S, Fn);
9621 return;
9622 }
9623
John McCallfe796dd2010-01-23 05:17:32 +00009624 case ovl_fail_trivial_conversion:
9625 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009626 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009627 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009628
John McCall65eb8792010-02-25 01:37:24 +00009629 case ovl_fail_bad_conversion: {
9630 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009631 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009632 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009633 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009634
John McCall6a61b522010-01-13 09:16:55 +00009635 // FIXME: this currently happens when we're called from SemaInit
9636 // when user-conversion overload fails. Figure out how to handle
9637 // those conditions and diagnose them well.
9638 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009639 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009640
9641 case ovl_fail_bad_target:
9642 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009643
9644 case ovl_fail_enable_if:
9645 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009646
9647 case ovl_fail_addr_not_available: {
9648 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9649 (void)Available;
9650 assert(!Available);
9651 break;
9652 }
John McCall65eb8792010-02-25 01:37:24 +00009653 }
John McCalld3224162010-01-08 00:58:21 +00009654}
9655
Richard Smith17c00b42014-11-12 01:24:00 +00009656static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009657 // Desugar the type of the surrogate down to a function type,
9658 // retaining as many typedefs as possible while still showing
9659 // the function type (and, therefore, its parameter types).
9660 QualType FnType = Cand->Surrogate->getConversionType();
9661 bool isLValueReference = false;
9662 bool isRValueReference = false;
9663 bool isPointer = false;
9664 if (const LValueReferenceType *FnTypeRef =
9665 FnType->getAs<LValueReferenceType>()) {
9666 FnType = FnTypeRef->getPointeeType();
9667 isLValueReference = true;
9668 } else if (const RValueReferenceType *FnTypeRef =
9669 FnType->getAs<RValueReferenceType>()) {
9670 FnType = FnTypeRef->getPointeeType();
9671 isRValueReference = true;
9672 }
9673 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9674 FnType = FnTypePtr->getPointeeType();
9675 isPointer = true;
9676 }
9677 // Desugar down to a function type.
9678 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9679 // Reconstruct the pointer/reference as appropriate.
9680 if (isPointer) FnType = S.Context.getPointerType(FnType);
9681 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9682 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9683
9684 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9685 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009686 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009687}
9688
Richard Smith17c00b42014-11-12 01:24:00 +00009689static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9690 SourceLocation OpLoc,
9691 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009692 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009693 std::string TypeStr("operator");
9694 TypeStr += Opc;
9695 TypeStr += "(";
9696 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009697 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009698 TypeStr += ")";
9699 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9700 } else {
9701 TypeStr += ", ";
9702 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9703 TypeStr += ")";
9704 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9705 }
9706}
9707
Richard Smith17c00b42014-11-12 01:24:00 +00009708static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9709 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009710 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009711 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9712 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009713 if (ICS.isBad()) break; // all meaningless after first invalid
9714 if (!ICS.isAmbiguous()) continue;
9715
John McCall5c32be02010-08-24 20:38:10 +00009716 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009717 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009718 }
9719}
9720
Larisse Voufo98b20f12013-07-19 23:00:19 +00009721static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009722 if (Cand->Function)
9723 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009724 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009725 return Cand->Surrogate->getLocation();
9726 return SourceLocation();
9727}
9728
Larisse Voufo98b20f12013-07-19 23:00:19 +00009729static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009730 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009731 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009732 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009733
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009734 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009735 case Sema::TDK_Incomplete:
9736 return 1;
9737
9738 case Sema::TDK_Underqualified:
9739 case Sema::TDK_Inconsistent:
9740 return 2;
9741
9742 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009743 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009744 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009745 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009746 return 3;
9747
9748 case Sema::TDK_InstantiationDepth:
9749 case Sema::TDK_FailedOverloadResolution:
9750 return 4;
9751
9752 case Sema::TDK_InvalidExplicitArguments:
9753 return 5;
9754
9755 case Sema::TDK_TooManyArguments:
9756 case Sema::TDK_TooFewArguments:
9757 return 6;
9758 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009759 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009760}
9761
Richard Smith17c00b42014-11-12 01:24:00 +00009762namespace {
John McCallad2587a2010-01-12 00:48:53 +00009763struct CompareOverloadCandidatesForDisplay {
9764 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009765 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009766 size_t NumArgs;
9767
Richard Smith0f59cb32015-12-18 21:45:41 +00009768 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009769 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009770
9771 bool operator()(const OverloadCandidate *L,
9772 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009773 // Fast-path this check.
9774 if (L == R) return false;
9775
John McCall12f97bc2010-01-08 04:41:39 +00009776 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009777 if (L->Viable) {
9778 if (!R->Viable) return true;
9779
9780 // TODO: introduce a tri-valued comparison for overload
9781 // candidates. Would be more worthwhile if we had a sort
9782 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009783 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9784 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009785 } else if (R->Viable)
9786 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009787
John McCall3712d9e2010-01-15 23:32:50 +00009788 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009789
John McCall3712d9e2010-01-15 23:32:50 +00009790 // Criteria by which we can sort non-viable candidates:
9791 if (!L->Viable) {
9792 // 1. Arity mismatches come after other candidates.
9793 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009794 L->FailureKind == ovl_fail_too_few_arguments) {
9795 if (R->FailureKind == ovl_fail_too_many_arguments ||
9796 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009797 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9798 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9799 if (LDist == RDist) {
9800 if (L->FailureKind == R->FailureKind)
9801 // Sort non-surrogates before surrogates.
9802 return !L->IsSurrogate && R->IsSurrogate;
9803 // Sort candidates requiring fewer parameters than there were
9804 // arguments given after candidates requiring more parameters
9805 // than there were arguments given.
9806 return L->FailureKind == ovl_fail_too_many_arguments;
9807 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009808 return LDist < RDist;
9809 }
John McCall3712d9e2010-01-15 23:32:50 +00009810 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009811 }
John McCall3712d9e2010-01-15 23:32:50 +00009812 if (R->FailureKind == ovl_fail_too_many_arguments ||
9813 R->FailureKind == ovl_fail_too_few_arguments)
9814 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009815
John McCallfe796dd2010-01-23 05:17:32 +00009816 // 2. Bad conversions come first and are ordered by the number
9817 // of bad conversions and quality of good conversions.
9818 if (L->FailureKind == ovl_fail_bad_conversion) {
9819 if (R->FailureKind != ovl_fail_bad_conversion)
9820 return true;
9821
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009822 // The conversion that can be fixed with a smaller number of changes,
9823 // comes first.
9824 unsigned numLFixes = L->Fix.NumConversionsFixed;
9825 unsigned numRFixes = R->Fix.NumConversionsFixed;
9826 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9827 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009828 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009829 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009830 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009831
John McCallfe796dd2010-01-23 05:17:32 +00009832 // If there's any ordering between the defined conversions...
9833 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009834 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009835
9836 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009837 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009838 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009839 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009840 L->Conversions[I],
9841 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009842 case ImplicitConversionSequence::Better:
9843 leftBetter++;
9844 break;
9845
9846 case ImplicitConversionSequence::Worse:
9847 leftBetter--;
9848 break;
9849
9850 case ImplicitConversionSequence::Indistinguishable:
9851 break;
9852 }
9853 }
9854 if (leftBetter > 0) return true;
9855 if (leftBetter < 0) return false;
9856
9857 } else if (R->FailureKind == ovl_fail_bad_conversion)
9858 return false;
9859
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009860 if (L->FailureKind == ovl_fail_bad_deduction) {
9861 if (R->FailureKind != ovl_fail_bad_deduction)
9862 return true;
9863
9864 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9865 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009866 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009867 } else if (R->FailureKind == ovl_fail_bad_deduction)
9868 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009869
John McCall3712d9e2010-01-15 23:32:50 +00009870 // TODO: others?
9871 }
9872
9873 // Sort everything else by location.
9874 SourceLocation LLoc = GetLocationForCandidate(L);
9875 SourceLocation RLoc = GetLocationForCandidate(R);
9876
9877 // Put candidates without locations (e.g. builtins) at the end.
9878 if (LLoc.isInvalid()) return false;
9879 if (RLoc.isInvalid()) return true;
9880
9881 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009882 }
9883};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009884}
John McCall12f97bc2010-01-08 04:41:39 +00009885
John McCallfe796dd2010-01-23 05:17:32 +00009886/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009887/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009888static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9889 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009890 assert(!Cand->Viable);
9891
9892 // Don't do anything on failures other than bad conversion.
9893 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9894
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009895 // We only want the FixIts if all the arguments can be corrected.
9896 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009897 // Use a implicit copy initialization to check conversion fixes.
9898 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009899
John McCallfe796dd2010-01-23 05:17:32 +00009900 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009901 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009902 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009903 while (true) {
9904 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9905 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009906 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009907 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009908 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009909 }
John McCallfe796dd2010-01-23 05:17:32 +00009910 }
9911
9912 if (ConvIdx == ConvCount)
9913 return;
9914
John McCall65eb8792010-02-25 01:37:24 +00009915 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9916 "remaining conversion is initialized?");
9917
Douglas Gregoradc7a702010-04-16 17:45:54 +00009918 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009919 // operation somehow.
9920 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009921
9922 const FunctionProtoType* Proto;
9923 unsigned ArgIdx = ConvIdx;
9924
9925 if (Cand->IsSurrogate) {
9926 QualType ConvType
9927 = Cand->Surrogate->getConversionType().getNonReferenceType();
9928 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9929 ConvType = ConvPtrType->getPointeeType();
9930 Proto = ConvType->getAs<FunctionProtoType>();
9931 ArgIdx--;
9932 } else if (Cand->Function) {
9933 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9934 if (isa<CXXMethodDecl>(Cand->Function) &&
9935 !isa<CXXConstructorDecl>(Cand->Function))
9936 ArgIdx--;
9937 } else {
9938 // Builtin binary operator with a bad first conversion.
9939 assert(ConvCount <= 3);
9940 for (; ConvIdx != ConvCount; ++ConvIdx)
9941 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009942 = TryCopyInitialization(S, Args[ConvIdx],
9943 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009944 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009945 /*InOverloadResolution*/ true,
9946 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009947 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009948 return;
9949 }
9950
9951 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009952 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009953 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009954 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009955 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9956 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9957 /*InOverloadResolution=*/true,
9958 /*AllowObjCWritebackConversion=*/
9959 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009960 // Store the FixIt in the candidate if it exists.
9961 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009962 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009963 }
John McCallfe796dd2010-01-23 05:17:32 +00009964 else
9965 Cand->Conversions[ConvIdx].setEllipsis();
9966 }
9967}
9968
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009969/// PrintOverloadCandidates - When overload resolution fails, prints
9970/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009971/// set.
John McCall5c32be02010-08-24 20:38:10 +00009972void OverloadCandidateSet::NoteCandidates(Sema &S,
9973 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009974 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009975 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009976 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009977 // Sort the candidates by viability and position. Sorting directly would
9978 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009979 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009980 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9981 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009982 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009983 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009984 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009985 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009986 if (Cand->Function || Cand->IsSurrogate)
9987 Cands.push_back(Cand);
9988 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9989 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009990 }
9991 }
9992
John McCallad2587a2010-01-12 00:48:53 +00009993 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +00009994 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009995
John McCall0d1da222010-01-12 00:44:57 +00009996 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009997
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009998 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009999 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010000 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010001 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10002 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010003
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010004 // Set an arbitrary limit on the number of candidate functions we'll spam
10005 // the user with. FIXME: This limit should depend on details of the
10006 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010007 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010008 break;
10009 }
10010 ++CandsShown;
10011
John McCalld3224162010-01-08 00:58:21 +000010012 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010013 NoteFunctionCandidate(S, Cand, Args.size(),
10014 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010015 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010016 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010017 else {
10018 assert(Cand->Viable &&
10019 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010020 // Generally we only see ambiguities including viable builtin
10021 // operators if overload resolution got screwed up by an
10022 // ambiguous user-defined conversion.
10023 //
10024 // FIXME: It's quite possible for different conversions to see
10025 // different ambiguities, though.
10026 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010027 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010028 ReportedAmbiguousConversions = true;
10029 }
John McCalld3224162010-01-08 00:58:21 +000010030
John McCall0d1da222010-01-12 00:44:57 +000010031 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010032 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010033 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010034 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010035
10036 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010037 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010038}
10039
Larisse Voufo98b20f12013-07-19 23:00:19 +000010040static SourceLocation
10041GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10042 return Cand->Specialization ? Cand->Specialization->getLocation()
10043 : SourceLocation();
10044}
10045
Richard Smith17c00b42014-11-12 01:24:00 +000010046namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010047struct CompareTemplateSpecCandidatesForDisplay {
10048 Sema &S;
10049 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10050
10051 bool operator()(const TemplateSpecCandidate *L,
10052 const TemplateSpecCandidate *R) {
10053 // Fast-path this check.
10054 if (L == R)
10055 return false;
10056
10057 // Assuming that both candidates are not matches...
10058
10059 // Sort by the ranking of deduction failures.
10060 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10061 return RankDeductionFailure(L->DeductionFailure) <
10062 RankDeductionFailure(R->DeductionFailure);
10063
10064 // Sort everything else by location.
10065 SourceLocation LLoc = GetLocationForCandidate(L);
10066 SourceLocation RLoc = GetLocationForCandidate(R);
10067
10068 // Put candidates without locations (e.g. builtins) at the end.
10069 if (LLoc.isInvalid())
10070 return false;
10071 if (RLoc.isInvalid())
10072 return true;
10073
10074 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10075 }
10076};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010077}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010078
10079/// Diagnose a template argument deduction failure.
10080/// We are treating these failures as overload failures due to bad
10081/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010082void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10083 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010084 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010085 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010086}
10087
10088void TemplateSpecCandidateSet::destroyCandidates() {
10089 for (iterator i = begin(), e = end(); i != e; ++i) {
10090 i->DeductionFailure.Destroy();
10091 }
10092}
10093
10094void TemplateSpecCandidateSet::clear() {
10095 destroyCandidates();
10096 Candidates.clear();
10097}
10098
10099/// NoteCandidates - When no template specialization match is found, prints
10100/// diagnostic messages containing the non-matching specializations that form
10101/// the candidate set.
10102/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10103/// OCD == OCD_AllCandidates and Cand->Viable == false.
10104void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10105 // Sort the candidates by position (assuming no candidate is a match).
10106 // Sorting directly would be prohibitive, so we make a set of pointers
10107 // and sort those.
10108 SmallVector<TemplateSpecCandidate *, 32> Cands;
10109 Cands.reserve(size());
10110 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10111 if (Cand->Specialization)
10112 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010113 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010114 // in general, want to list every possible builtin candidate.
10115 }
10116
10117 std::sort(Cands.begin(), Cands.end(),
10118 CompareTemplateSpecCandidatesForDisplay(S));
10119
10120 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10121 // for generalization purposes (?).
10122 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10123
10124 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10125 unsigned CandsShown = 0;
10126 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10127 TemplateSpecCandidate *Cand = *I;
10128
10129 // Set an arbitrary limit on the number of candidates we'll spam
10130 // the user with. FIXME: This limit should depend on details of the
10131 // candidate list.
10132 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10133 break;
10134 ++CandsShown;
10135
10136 assert(Cand->Specialization &&
10137 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010138 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010139 }
10140
10141 if (I != E)
10142 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10143}
10144
Douglas Gregorb491ed32011-02-19 21:32:49 +000010145// [PossiblyAFunctionType] --> [Return]
10146// NonFunctionType --> NonFunctionType
10147// R (A) --> R(A)
10148// R (*)(A) --> R (A)
10149// R (&)(A) --> R (A)
10150// R (S::*)(A) --> R (A)
10151QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10152 QualType Ret = PossiblyAFunctionType;
10153 if (const PointerType *ToTypePtr =
10154 PossiblyAFunctionType->getAs<PointerType>())
10155 Ret = ToTypePtr->getPointeeType();
10156 else if (const ReferenceType *ToTypeRef =
10157 PossiblyAFunctionType->getAs<ReferenceType>())
10158 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010159 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010160 PossiblyAFunctionType->getAs<MemberPointerType>())
10161 Ret = MemTypePtr->getPointeeType();
10162 Ret =
10163 Context.getCanonicalType(Ret).getUnqualifiedType();
10164 return Ret;
10165}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010166
Richard Smith17c00b42014-11-12 01:24:00 +000010167namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010168// A helper class to help with address of function resolution
10169// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010170class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010171 Sema& S;
10172 Expr* SourceExpr;
10173 const QualType& TargetType;
10174 QualType TargetFunctionType; // Extracted function type from target type
10175
10176 bool Complain;
10177 //DeclAccessPair& ResultFunctionAccessPair;
10178 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010179
Douglas Gregorb491ed32011-02-19 21:32:49 +000010180 bool TargetTypeIsNonStaticMemberFunction;
10181 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010182 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010183 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010184
Douglas Gregorb491ed32011-02-19 21:32:49 +000010185 OverloadExpr::FindResult OvlExprInfo;
10186 OverloadExpr *OvlExpr;
10187 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010188 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010189 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010190
Douglas Gregorb491ed32011-02-19 21:32:49 +000010191public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010192 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10193 const QualType &TargetType, bool Complain)
10194 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10195 Complain(Complain), Context(S.getASTContext()),
10196 TargetTypeIsNonStaticMemberFunction(
10197 !!TargetType->getAs<MemberPointerType>()),
10198 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010199 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010200 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010201 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10202 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010203 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010204 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010205
David Majnemera4f7c7a2013-08-01 06:13:59 +000010206 if (TargetFunctionType->isFunctionType()) {
10207 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10208 if (!UME->isImplicitAccess() &&
10209 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10210 StaticMemberFunctionFromBoundPointer = true;
10211 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10212 DeclAccessPair dap;
10213 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10214 OvlExpr, false, &dap)) {
10215 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10216 if (!Method->isStatic()) {
10217 // If the target type is a non-function type and the function found
10218 // is a non-static member function, pretend as if that was the
10219 // target, it's the only possible type to end up with.
10220 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010221
David Majnemera4f7c7a2013-08-01 06:13:59 +000010222 // And skip adding the function if its not in the proper form.
10223 // We'll diagnose this due to an empty set of functions.
10224 if (!OvlExprInfo.HasFormOfMemberPointer)
10225 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010226 }
10227
David Majnemera4f7c7a2013-08-01 06:13:59 +000010228 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010229 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010230 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010231 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010232
10233 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010234 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010235
Douglas Gregorb491ed32011-02-19 21:32:49 +000010236 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10237 // C++ [over.over]p4:
10238 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010239 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010240 if (FoundNonTemplateFunction)
10241 EliminateAllTemplateMatches();
10242 else
10243 EliminateAllExceptMostSpecializedTemplate();
10244 }
10245 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010246
10247 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10248 Matches.size() > 1)
10249 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010250 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010251
10252 bool hasComplained() const { return HasComplained; }
10253
Douglas Gregorb491ed32011-02-19 21:32:49 +000010254private:
George Burgess IV2a6150d2015-10-16 01:17:38 +000010255 // Is A considered a better overload candidate for the desired type than B?
10256 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10257 return hasBetterEnableIfAttrs(S, A, B);
10258 }
10259
10260 // Returns true if we've eliminated any (read: all but one) candidates, false
10261 // otherwise.
10262 bool eliminiateSuboptimalOverloadCandidates() {
10263 // Same algorithm as overload resolution -- one pass to pick the "best",
10264 // another pass to be sure that nothing is better than the best.
10265 auto Best = Matches.begin();
10266 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10267 if (isBetterCandidate(I->second, Best->second))
10268 Best = I;
10269
10270 const FunctionDecl *BestFn = Best->second;
10271 auto IsBestOrInferiorToBest = [this, BestFn](
10272 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10273 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10274 };
10275
10276 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10277 // option, so we can potentially give the user a better error
10278 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10279 return false;
10280 Matches[0] = *Best;
10281 Matches.resize(1);
10282 return true;
10283 }
10284
Douglas Gregorb491ed32011-02-19 21:32:49 +000010285 bool isTargetTypeAFunction() const {
10286 return TargetFunctionType->isFunctionType();
10287 }
10288
10289 // [ToType] [Return]
10290
10291 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10292 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10293 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10294 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10295 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10296 }
10297
10298 // return true if any matching specializations were found
10299 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10300 const DeclAccessPair& CurAccessFunPair) {
10301 if (CXXMethodDecl *Method
10302 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10303 // Skip non-static function templates when converting to pointer, and
10304 // static when converting to member pointer.
10305 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10306 return false;
10307 }
10308 else if (TargetTypeIsNonStaticMemberFunction)
10309 return false;
10310
10311 // C++ [over.over]p2:
10312 // If the name is a function template, template argument deduction is
10313 // done (14.8.2.2), and if the argument deduction succeeds, the
10314 // resulting template argument list is used to generate a single
10315 // function template specialization, which is added to the set of
10316 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010317 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010318 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010319 if (Sema::TemplateDeductionResult Result
10320 = S.DeduceTemplateArguments(FunctionTemplate,
10321 &OvlExplicitTemplateArgs,
10322 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010323 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010324 // Make a note of the failed deduction for diagnostics.
10325 FailedCandidates.addCandidate()
10326 .set(FunctionTemplate->getTemplatedDecl(),
10327 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010328 return false;
10329 }
10330
Douglas Gregor19a41f12013-04-17 08:45:07 +000010331 // Template argument deduction ensures that we have an exact match or
10332 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010333 // This function template specicalization works.
10334 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +000010335 assert(S.isSameOrCompatibleFunctionType(
10336 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010337 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010338
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010339 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010340 return false;
10341
Douglas Gregorb491ed32011-02-19 21:32:49 +000010342 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10343 return true;
10344 }
10345
10346 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10347 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010348 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010349 // Skip non-static functions when converting to pointer, and static
10350 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010351 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10352 return false;
10353 }
10354 else if (TargetTypeIsNonStaticMemberFunction)
10355 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010356
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010357 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010358 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010359 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010360 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010361 return false;
10362
Richard Smith2a7d4812013-05-04 07:00:32 +000010363 // If any candidate has a placeholder return type, trigger its deduction
10364 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010365 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010366 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010367 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10368 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010369 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010370 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010371
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010372 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010373 return false;
10374
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010375 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010376 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10377 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010378 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
George Burgess IV5f21c712015-10-12 19:57:04 +000010379 ResultTy) ||
10380 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10381 Matches.push_back(std::make_pair(
10382 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010383 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010384 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010385 }
Mike Stump11289f42009-09-09 15:08:12 +000010386 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010387
10388 return false;
10389 }
10390
10391 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10392 bool Ret = false;
10393
10394 // If the overload expression doesn't have the form of a pointer to
10395 // member, don't try to convert it to a pointer-to-member type.
10396 if (IsInvalidFormOfPointerToMemberFunction())
10397 return false;
10398
10399 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10400 E = OvlExpr->decls_end();
10401 I != E; ++I) {
10402 // Look through any using declarations to find the underlying function.
10403 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10404
10405 // C++ [over.over]p3:
10406 // Non-member functions and static member functions match
10407 // targets of type "pointer-to-function" or "reference-to-function."
10408 // Nonstatic member functions match targets of
10409 // type "pointer-to-member-function."
10410 // Note that according to DR 247, the containing class does not matter.
10411 if (FunctionTemplateDecl *FunctionTemplate
10412 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10413 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10414 Ret = true;
10415 }
10416 // If we have explicit template arguments supplied, skip non-templates.
10417 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10418 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10419 Ret = true;
10420 }
10421 assert(Ret || Matches.empty());
10422 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010423 }
10424
Douglas Gregorb491ed32011-02-19 21:32:49 +000010425 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010426 // [...] and any given function template specialization F1 is
10427 // eliminated if the set contains a second function template
10428 // specialization whose function template is more specialized
10429 // than the function template of F1 according to the partial
10430 // ordering rules of 14.5.5.2.
10431
10432 // The algorithm specified above is quadratic. We instead use a
10433 // two-pass algorithm (similar to the one used to identify the
10434 // best viable function in an overload set) that identifies the
10435 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010436
10437 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10438 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10439 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010440
Larisse Voufo98b20f12013-07-19 23:00:19 +000010441 // TODO: It looks like FailedCandidates does not serve much purpose
10442 // here, since the no_viable diagnostic has index 0.
10443 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010444 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010445 SourceExpr->getLocStart(), S.PDiag(),
10446 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10447 .second->getDeclName(),
10448 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10449 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010450
Douglas Gregorb491ed32011-02-19 21:32:49 +000010451 if (Result != MatchesCopy.end()) {
10452 // Make it the first and only element
10453 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10454 Matches[0].second = cast<FunctionDecl>(*Result);
10455 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010456 } else
10457 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010459
Douglas Gregorb491ed32011-02-19 21:32:49 +000010460 void EliminateAllTemplateMatches() {
10461 // [...] any function template specializations in the set are
10462 // eliminated if the set also contains a non-template function, [...]
10463 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010464 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010465 ++I;
10466 else {
10467 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010468 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010469 }
10470 }
10471 }
10472
Artem Belevich94a55e82015-09-22 17:22:59 +000010473 void EliminateSuboptimalCudaMatches() {
10474 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10475 }
10476
Douglas Gregorb491ed32011-02-19 21:32:49 +000010477public:
10478 void ComplainNoMatchesFound() const {
10479 assert(Matches.empty());
10480 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10481 << OvlExpr->getName() << TargetFunctionType
10482 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010483 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010484 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10485 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010486 else {
10487 // We have some deduction failure messages. Use them to diagnose
10488 // the function templates, and diagnose the non-template candidates
10489 // normally.
10490 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10491 IEnd = OvlExpr->decls_end();
10492 I != IEnd; ++I)
10493 if (FunctionDecl *Fun =
10494 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010495 if (!functionHasPassObjectSizeParams(Fun))
10496 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10497 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010498 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10499 }
10500 }
10501
Douglas Gregorb491ed32011-02-19 21:32:49 +000010502 bool IsInvalidFormOfPointerToMemberFunction() const {
10503 return TargetTypeIsNonStaticMemberFunction &&
10504 !OvlExprInfo.HasFormOfMemberPointer;
10505 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010506
Douglas Gregorb491ed32011-02-19 21:32:49 +000010507 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10508 // TODO: Should we condition this on whether any functions might
10509 // have matched, or is it more appropriate to do that in callers?
10510 // TODO: a fixit wouldn't hurt.
10511 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10512 << TargetType << OvlExpr->getSourceRange();
10513 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010514
10515 bool IsStaticMemberFunctionFromBoundPointer() const {
10516 return StaticMemberFunctionFromBoundPointer;
10517 }
10518
10519 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10520 S.Diag(OvlExpr->getLocStart(),
10521 diag::err_invalid_form_pointer_member_function)
10522 << OvlExpr->getSourceRange();
10523 }
10524
Douglas Gregorb491ed32011-02-19 21:32:49 +000010525 void ComplainOfInvalidConversion() const {
10526 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10527 << OvlExpr->getName() << TargetType;
10528 }
10529
10530 void ComplainMultipleMatchesFound() const {
10531 assert(Matches.size() > 1);
10532 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10533 << OvlExpr->getName()
10534 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010535 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10536 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010537 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010538
10539 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10540
Douglas Gregorb491ed32011-02-19 21:32:49 +000010541 int getNumMatches() const { return Matches.size(); }
10542
10543 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010544 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010545 return Matches[0].second;
10546 }
10547
10548 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010549 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010550 return &Matches[0].first;
10551 }
10552};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010553}
Richard Smith17c00b42014-11-12 01:24:00 +000010554
Douglas Gregorb491ed32011-02-19 21:32:49 +000010555/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10556/// an overloaded function (C++ [over.over]), where @p From is an
10557/// expression with overloaded function type and @p ToType is the type
10558/// we're trying to resolve to. For example:
10559///
10560/// @code
10561/// int f(double);
10562/// int f(int);
10563///
10564/// int (*pfd)(double) = f; // selects f(double)
10565/// @endcode
10566///
10567/// This routine returns the resulting FunctionDecl if it could be
10568/// resolved, and NULL otherwise. When @p Complain is true, this
10569/// routine will emit diagnostics if there is an error.
10570FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010571Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10572 QualType TargetType,
10573 bool Complain,
10574 DeclAccessPair &FoundResult,
10575 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010576 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010577
10578 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10579 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010580 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010581 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010582 bool ShouldComplain = Complain && !Resolver.hasComplained();
10583 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010584 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10585 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10586 else
10587 Resolver.ComplainNoMatchesFound();
10588 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010589 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010590 Resolver.ComplainMultipleMatchesFound();
10591 else if (NumMatches == 1) {
10592 Fn = Resolver.getMatchingFunctionDecl();
10593 assert(Fn);
10594 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010595 if (Complain) {
10596 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10597 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10598 else
10599 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10600 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010601 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010602
10603 if (pHadMultipleCandidates)
10604 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010605 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010606}
10607
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010608/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010609/// resolve that overloaded function expression down to a single function.
10610///
10611/// This routine can only resolve template-ids that refer to a single function
10612/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010613/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010614/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010615///
10616/// If no template-ids are found, no diagnostics are emitted and NULL is
10617/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010618FunctionDecl *
10619Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10620 bool Complain,
10621 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010622 // C++ [over.over]p1:
10623 // [...] [Note: any redundant set of parentheses surrounding the
10624 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010625 // C++ [over.over]p1:
10626 // [...] The overloaded function name can be preceded by the &
10627 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010628
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010629 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010630 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010631 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010632
10633 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010634 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010635 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010636
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010637 // Look through all of the overloaded functions, searching for one
10638 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010639 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010640 for (UnresolvedSetIterator I = ovl->decls_begin(),
10641 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010642 // C++0x [temp.arg.explicit]p3:
10643 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010644 // where deduction is not done, if a template argument list is
10645 // specified and it, along with any default template arguments,
10646 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010647 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010648 FunctionTemplateDecl *FunctionTemplate
10649 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010650
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010651 // C++ [over.over]p2:
10652 // If the name is a function template, template argument deduction is
10653 // done (14.8.2.2), and if the argument deduction succeeds, the
10654 // resulting template argument list is used to generate a single
10655 // function template specialization, which is added to the set of
10656 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010657 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010658 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010659 if (TemplateDeductionResult Result
10660 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010661 Specialization, Info,
10662 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010663 // Make a note of the failed deduction for diagnostics.
10664 // TODO: Actually use the failed-deduction info?
10665 FailedCandidates.addCandidate()
10666 .set(FunctionTemplate->getTemplatedDecl(),
10667 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010668 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010669 }
10670
John McCall0009fcc2011-04-26 20:42:42 +000010671 assert(Specialization && "no specialization and no error?");
10672
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010673 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010674 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010675 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010676 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10677 << ovl->getName();
10678 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010679 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010680 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010681 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010682
John McCall0009fcc2011-04-26 20:42:42 +000010683 Matched = Specialization;
10684 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010686
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010687 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010688 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010689 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010690 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010691
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010692 return Matched;
10693}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010694
Douglas Gregor1beec452011-03-12 01:48:56 +000010695
10696
10697
John McCall50a2c2c2011-10-11 23:14:30 +000010698// Resolve and fix an overloaded expression that can be resolved
10699// because it identifies a single function template specialization.
10700//
Douglas Gregor1beec452011-03-12 01:48:56 +000010701// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010702//
10703// Return true if it was logically possible to so resolve the
10704// expression, regardless of whether or not it succeeded. Always
10705// returns true if 'complain' is set.
10706bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10707 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010708 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010709 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010710 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010711 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010712
John McCall50a2c2c2011-10-11 23:14:30 +000010713 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010714
John McCall0009fcc2011-04-26 20:42:42 +000010715 DeclAccessPair found;
10716 ExprResult SingleFunctionExpression;
10717 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10718 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010719 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010720 SrcExpr = ExprError();
10721 return true;
10722 }
John McCall0009fcc2011-04-26 20:42:42 +000010723
10724 // It is only correct to resolve to an instance method if we're
10725 // resolving a form that's permitted to be a pointer to member.
10726 // Otherwise we'll end up making a bound member expression, which
10727 // is illegal in all the contexts we resolve like this.
10728 if (!ovl.HasFormOfMemberPointer &&
10729 isa<CXXMethodDecl>(fn) &&
10730 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010731 if (!complain) return false;
10732
10733 Diag(ovl.Expression->getExprLoc(),
10734 diag::err_bound_member_function)
10735 << 0 << ovl.Expression->getSourceRange();
10736
10737 // TODO: I believe we only end up here if there's a mix of
10738 // static and non-static candidates (otherwise the expression
10739 // would have 'bound member' type, not 'overload' type).
10740 // Ideally we would note which candidate was chosen and why
10741 // the static candidates were rejected.
10742 SrcExpr = ExprError();
10743 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010744 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010745
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010746 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010747 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010748 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010749
10750 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010751 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010752 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010753 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010754 if (SingleFunctionExpression.isInvalid()) {
10755 SrcExpr = ExprError();
10756 return true;
10757 }
10758 }
John McCall0009fcc2011-04-26 20:42:42 +000010759 }
10760
10761 if (!SingleFunctionExpression.isUsable()) {
10762 if (complain) {
10763 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10764 << ovl.Expression->getName()
10765 << DestTypeForComplaining
10766 << OpRangeForComplaining
10767 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010768 NoteAllOverloadCandidates(SrcExpr.get());
10769
10770 SrcExpr = ExprError();
10771 return true;
10772 }
10773
10774 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010775 }
10776
John McCall50a2c2c2011-10-11 23:14:30 +000010777 SrcExpr = SingleFunctionExpression;
10778 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010779}
10780
Douglas Gregorcabea402009-09-22 15:41:20 +000010781/// \brief Add a single candidate to the overload set.
10782static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010783 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010784 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010785 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010786 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010787 bool PartialOverloading,
10788 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010789 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010790 if (isa<UsingShadowDecl>(Callee))
10791 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10792
Douglas Gregorcabea402009-09-22 15:41:20 +000010793 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010794 if (ExplicitTemplateArgs) {
10795 assert(!KnownValid && "Explicit template arguments?");
10796 return;
10797 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010798 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10799 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010800 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010801 return;
John McCalld14a8642009-11-21 08:51:07 +000010802 }
10803
10804 if (FunctionTemplateDecl *FuncTemplate
10805 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010806 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010807 ExplicitTemplateArgs, Args, CandidateSet,
10808 /*SuppressUsedConversions=*/false,
10809 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010810 return;
10811 }
10812
Richard Smith95ce4f62011-06-26 22:19:54 +000010813 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010814}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010815
Douglas Gregorcabea402009-09-22 15:41:20 +000010816/// \brief Add the overload candidates named by callee and/or found by argument
10817/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010818void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010819 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010820 OverloadCandidateSet &CandidateSet,
10821 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010822
10823#ifndef NDEBUG
10824 // Verify that ArgumentDependentLookup is consistent with the rules
10825 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010826 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010827 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10828 // and let Y be the lookup set produced by argument dependent
10829 // lookup (defined as follows). If X contains
10830 //
10831 // -- a declaration of a class member, or
10832 //
10833 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010834 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010835 //
10836 // -- a declaration that is neither a function or a function
10837 // template
10838 //
10839 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010840
John McCall57500772009-12-16 12:17:52 +000010841 if (ULE->requiresADL()) {
10842 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10843 E = ULE->decls_end(); I != E; ++I) {
10844 assert(!(*I)->getDeclContext()->isRecord());
10845 assert(isa<UsingShadowDecl>(*I) ||
10846 !(*I)->getDeclContext()->isFunctionOrMethod());
10847 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010848 }
10849 }
10850#endif
10851
John McCall57500772009-12-16 12:17:52 +000010852 // It would be nice to avoid this copy.
10853 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010854 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010855 if (ULE->hasExplicitTemplateArgs()) {
10856 ULE->copyTemplateArgumentsInto(TABuffer);
10857 ExplicitTemplateArgs = &TABuffer;
10858 }
10859
10860 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10861 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010862 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10863 CandidateSet, PartialOverloading,
10864 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010865
John McCall57500772009-12-16 12:17:52 +000010866 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010867 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010868 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010869 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010870}
John McCalld681c392009-12-16 08:11:27 +000010871
Richard Smith0603bbb2013-06-12 22:56:54 +000010872/// Determine whether a declaration with the specified name could be moved into
10873/// a different namespace.
10874static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10875 switch (Name.getCXXOverloadedOperator()) {
10876 case OO_New: case OO_Array_New:
10877 case OO_Delete: case OO_Array_Delete:
10878 return false;
10879
10880 default:
10881 return true;
10882 }
10883}
10884
Richard Smith998a5912011-06-05 22:42:48 +000010885/// Attempt to recover from an ill-formed use of a non-dependent name in a
10886/// template, where the non-dependent name was declared after the template
10887/// was defined. This is common in code written for a compilers which do not
10888/// correctly implement two-stage name lookup.
10889///
10890/// Returns true if a viable candidate was found and a diagnostic was issued.
10891static bool
10892DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10893 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010894 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010895 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010896 ArrayRef<Expr *> Args,
10897 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010898 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10899 return false;
10900
10901 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010902 if (DC->isTransparentContext())
10903 continue;
10904
Richard Smith998a5912011-06-05 22:42:48 +000010905 SemaRef.LookupQualifiedName(R, DC);
10906
10907 if (!R.empty()) {
10908 R.suppressDiagnostics();
10909
10910 if (isa<CXXRecordDecl>(DC)) {
10911 // Don't diagnose names we find in classes; we get much better
10912 // diagnostics for these from DiagnoseEmptyLookup.
10913 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010914 if (DoDiagnoseEmptyLookup)
10915 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010916 return false;
10917 }
10918
Richard Smith100b24a2014-04-17 01:52:14 +000010919 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010920 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10921 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010922 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010923 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010924
10925 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010926 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010927 // No viable functions. Don't bother the user with notes for functions
10928 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010929 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010930 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010931 }
Richard Smith998a5912011-06-05 22:42:48 +000010932
10933 // Find the namespaces where ADL would have looked, and suggest
10934 // declaring the function there instead.
10935 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10936 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010937 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010938 AssociatedNamespaces,
10939 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010940 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010941 if (canBeDeclaredInNamespace(R.getLookupName())) {
10942 DeclContext *Std = SemaRef.getStdNamespace();
10943 for (Sema::AssociatedNamespaceSet::iterator
10944 it = AssociatedNamespaces.begin(),
10945 end = AssociatedNamespaces.end(); it != end; ++it) {
10946 // Never suggest declaring a function within namespace 'std'.
10947 if (Std && Std->Encloses(*it))
10948 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010949
Richard Smith0603bbb2013-06-12 22:56:54 +000010950 // Never suggest declaring a function within a namespace with a
10951 // reserved name, like __gnu_cxx.
10952 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10953 if (NS &&
10954 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10955 continue;
10956
10957 SuggestedNamespaces.insert(*it);
10958 }
Richard Smith998a5912011-06-05 22:42:48 +000010959 }
10960
10961 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10962 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010963 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010964 SemaRef.Diag(Best->Function->getLocation(),
10965 diag::note_not_found_by_two_phase_lookup)
10966 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010967 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010968 SemaRef.Diag(Best->Function->getLocation(),
10969 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010970 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010971 } else {
10972 // FIXME: It would be useful to list the associated namespaces here,
10973 // but the diagnostics infrastructure doesn't provide a way to produce
10974 // a localized representation of a list of items.
10975 SemaRef.Diag(Best->Function->getLocation(),
10976 diag::note_not_found_by_two_phase_lookup)
10977 << R.getLookupName() << 2;
10978 }
10979
10980 // Try to recover by calling this function.
10981 return true;
10982 }
10983
10984 R.clear();
10985 }
10986
10987 return false;
10988}
10989
10990/// Attempt to recover from ill-formed use of a non-dependent operator in a
10991/// template, where the non-dependent operator was declared after the template
10992/// was defined.
10993///
10994/// Returns true if a viable candidate was found and a diagnostic was issued.
10995static bool
10996DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10997 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010998 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010999 DeclarationName OpName =
11000 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11001 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11002 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011003 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011004 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011005}
11006
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011007namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011008class BuildRecoveryCallExprRAII {
11009 Sema &SemaRef;
11010public:
11011 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11012 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11013 SemaRef.IsBuildingRecoveryCallExpr = true;
11014 }
11015
11016 ~BuildRecoveryCallExprRAII() {
11017 SemaRef.IsBuildingRecoveryCallExpr = false;
11018 }
11019};
11020
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011021}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011022
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011023static std::unique_ptr<CorrectionCandidateCallback>
11024MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11025 bool HasTemplateArgs, bool AllowTypoCorrection) {
11026 if (!AllowTypoCorrection)
11027 return llvm::make_unique<NoTypoCorrectionCCC>();
11028 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11029 HasTemplateArgs, ME);
11030}
11031
John McCalld681c392009-12-16 08:11:27 +000011032/// Attempts to recover from a call where no functions were found.
11033///
11034/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011035static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011036BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011037 UnresolvedLookupExpr *ULE,
11038 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011039 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011040 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011041 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011042 // Do not try to recover if it is already building a recovery call.
11043 // This stops infinite loops for template instantiations like
11044 //
11045 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11046 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11047 //
11048 if (SemaRef.IsBuildingRecoveryCallExpr)
11049 return ExprError();
11050 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011051
11052 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011053 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011054 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011055
John McCall57500772009-12-16 12:17:52 +000011056 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011057 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011058 if (ULE->hasExplicitTemplateArgs()) {
11059 ULE->copyTemplateArgumentsInto(TABuffer);
11060 ExplicitTemplateArgs = &TABuffer;
11061 }
11062
John McCalld681c392009-12-16 08:11:27 +000011063 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11064 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011065 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011066 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011067 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011068 ExplicitTemplateArgs, Args,
11069 &DoDiagnoseEmptyLookup) &&
11070 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11071 S, SS, R,
11072 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11073 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11074 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011075 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011076
John McCall57500772009-12-16 12:17:52 +000011077 assert(!R.empty() && "lookup results empty despite recovery");
11078
11079 // Build an implicit member call if appropriate. Just drop the
11080 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011081 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011082 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011083 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11084 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011085 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011086 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011087 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011088 else
11089 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11090
11091 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011092 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011093
11094 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011095 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011096 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011097 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011098 MultiExprArg(Args.data(), Args.size()),
11099 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011100}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011101
Sam Panzer0f384432012-08-21 00:52:01 +000011102/// \brief Constructs and populates an OverloadedCandidateSet from
11103/// the given function.
11104/// \returns true when an the ExprResult output parameter has been set.
11105bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11106 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011107 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011108 SourceLocation RParenLoc,
11109 OverloadCandidateSet *CandidateSet,
11110 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011111#ifndef NDEBUG
11112 if (ULE->requiresADL()) {
11113 // To do ADL, we must have found an unqualified name.
11114 assert(!ULE->getQualifier() && "qualified name with ADL");
11115
11116 // We don't perform ADL for implicit declarations of builtins.
11117 // Verify that this was correctly set up.
11118 FunctionDecl *F;
11119 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11120 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11121 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011122 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011123
John McCall57500772009-12-16 12:17:52 +000011124 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011125 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011126 }
John McCall57500772009-12-16 12:17:52 +000011127#endif
11128
John McCall4124c492011-10-17 18:40:02 +000011129 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011130 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011131 *Result = ExprError();
11132 return true;
11133 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011134
John McCall57500772009-12-16 12:17:52 +000011135 // Add the functions denoted by the callee to the set of candidate
11136 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011137 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011138
Hans Wennborgb2747382015-06-12 21:23:23 +000011139 if (getLangOpts().MSVCCompat &&
11140 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011141 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11142
11143 OverloadCandidateSet::iterator Best;
11144 if (CandidateSet->empty() ||
11145 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11146 OR_No_Viable_Function) {
11147 // In Microsoft mode, if we are inside a template class member function then
11148 // create a type dependent CallExpr. The goal is to postpone name lookup
11149 // to instantiation time to be able to search into type dependent base
11150 // classes.
11151 CallExpr *CE = new (Context) CallExpr(
11152 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011153 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011154 CE->setValueDependent(true);
11155 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011156 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011157 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011158 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011159 }
John McCalld681c392009-12-16 08:11:27 +000011160
Hans Wennborg64937c62015-06-11 21:21:57 +000011161 if (CandidateSet->empty())
11162 return false;
11163
John McCall4124c492011-10-17 18:40:02 +000011164 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011165 return false;
11166}
John McCall4124c492011-10-17 18:40:02 +000011167
Sam Panzer0f384432012-08-21 00:52:01 +000011168/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11169/// the completed call expression. If overload resolution fails, emits
11170/// diagnostics and returns ExprError()
11171static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11172 UnresolvedLookupExpr *ULE,
11173 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011174 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011175 SourceLocation RParenLoc,
11176 Expr *ExecConfig,
11177 OverloadCandidateSet *CandidateSet,
11178 OverloadCandidateSet::iterator *Best,
11179 OverloadingResult OverloadResult,
11180 bool AllowTypoCorrection) {
11181 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011182 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011183 RParenLoc, /*EmptyLookup=*/true,
11184 AllowTypoCorrection);
11185
11186 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011187 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011188 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011189 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011190 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11191 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011192 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011193 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11194 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011195 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011196
Richard Smith998a5912011-06-05 22:42:48 +000011197 case OR_No_Viable_Function: {
11198 // Try to recover by looking for viable functions which the user might
11199 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011200 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011201 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011202 /*EmptyLookup=*/false,
11203 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011204 if (!Recovery.isInvalid())
11205 return Recovery;
11206
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011207 // If the user passes in a function that we can't take the address of, we
11208 // generally end up emitting really bad error messages. Here, we attempt to
11209 // emit better ones.
11210 for (const Expr *Arg : Args) {
11211 if (!Arg->getType()->isFunctionType())
11212 continue;
11213 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11214 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11215 if (FD &&
11216 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11217 Arg->getExprLoc()))
11218 return ExprError();
11219 }
11220 }
11221
11222 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11223 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011224 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011225 break;
Richard Smith998a5912011-06-05 22:42:48 +000011226 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011227
11228 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011229 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011230 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011231 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011232 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011233
Sam Panzer0f384432012-08-21 00:52:01 +000011234 case OR_Deleted: {
11235 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11236 << (*Best)->Function->isDeleted()
11237 << ULE->getName()
11238 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11239 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011240 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011241
Sam Panzer0f384432012-08-21 00:52:01 +000011242 // We emitted an error for the unvailable/deleted function call but keep
11243 // the call in the AST.
11244 FunctionDecl *FDecl = (*Best)->Function;
11245 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011246 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11247 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011248 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011249 }
11250
Douglas Gregorb412e172010-07-25 18:17:45 +000011251 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011252 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011253}
11254
George Burgess IV7204ed92016-01-07 02:26:57 +000011255static void markUnaddressableCandidatesUnviable(Sema &S,
11256 OverloadCandidateSet &CS) {
11257 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11258 if (I->Viable &&
11259 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11260 I->Viable = false;
11261 I->FailureKind = ovl_fail_addr_not_available;
11262 }
11263 }
11264}
11265
Sam Panzer0f384432012-08-21 00:52:01 +000011266/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11267/// (which eventually refers to the declaration Func) and the call
11268/// arguments Args/NumArgs, attempt to resolve the function call down
11269/// to a specific function. If overload resolution succeeds, returns
11270/// the call expression produced by overload resolution.
11271/// Otherwise, emits diagnostics and returns ExprError.
11272ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11273 UnresolvedLookupExpr *ULE,
11274 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011275 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011276 SourceLocation RParenLoc,
11277 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011278 bool AllowTypoCorrection,
11279 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011280 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11281 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011282 ExprResult result;
11283
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011284 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11285 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011286 return result;
11287
George Burgess IV7204ed92016-01-07 02:26:57 +000011288 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11289 // functions that aren't addressible are considered unviable.
11290 if (CalleesAddressIsTaken)
11291 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11292
Sam Panzer0f384432012-08-21 00:52:01 +000011293 OverloadCandidateSet::iterator Best;
11294 OverloadingResult OverloadResult =
11295 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11296
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011297 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011298 RParenLoc, ExecConfig, &CandidateSet,
11299 &Best, OverloadResult,
11300 AllowTypoCorrection);
11301}
11302
John McCall4c4c1df2010-01-26 03:27:55 +000011303static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011304 return Functions.size() > 1 ||
11305 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11306}
11307
Douglas Gregor084d8552009-03-13 23:49:33 +000011308/// \brief Create a unary operation that may resolve to an overloaded
11309/// operator.
11310///
11311/// \param OpLoc The location of the operator itself (e.g., '*').
11312///
Craig Toppera92ffb02015-12-10 08:51:49 +000011313/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011314///
James Dennett18348b62012-06-22 08:52:37 +000011315/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011316/// considered by overload resolution. The caller needs to build this
11317/// set based on the context using, e.g.,
11318/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11319/// set should not contain any member functions; those will be added
11320/// by CreateOverloadedUnaryOp().
11321///
James Dennett91738ff2012-06-22 10:32:46 +000011322/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011323ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011324Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011325 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011326 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011327 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11328 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11329 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011330 // TODO: provide better source location info.
11331 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011332
John McCall4124c492011-10-17 18:40:02 +000011333 if (checkPlaceholderForOverload(*this, Input))
11334 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011335
Craig Topperc3ec1492014-05-26 06:22:03 +000011336 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011337 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011338
Douglas Gregor084d8552009-03-13 23:49:33 +000011339 // For post-increment and post-decrement, add the implicit '0' as
11340 // the second argument, so that we know this is a post-increment or
11341 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011342 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011343 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011344 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11345 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011346 NumArgs = 2;
11347 }
11348
Richard Smithe54c3072013-05-05 15:51:06 +000011349 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11350
Douglas Gregor084d8552009-03-13 23:49:33 +000011351 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011352 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011353 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11354 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011355
Craig Topperc3ec1492014-05-26 06:22:03 +000011356 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011357 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011358 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011359 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011360 /*ADL*/ true, IsOverloaded(Fns),
11361 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011362 return new (Context)
11363 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11364 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011365 }
11366
11367 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011368 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011369
11370 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011371 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011372
11373 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011374 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011375
John McCall4c4c1df2010-01-26 03:27:55 +000011376 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011377 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011378 /*ExplicitTemplateArgs*/nullptr,
11379 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011380
Douglas Gregor084d8552009-03-13 23:49:33 +000011381 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011382 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011383
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011384 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11385
Douglas Gregor084d8552009-03-13 23:49:33 +000011386 // Perform overload resolution.
11387 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011388 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011389 case OR_Success: {
11390 // We found a built-in operator or an overloaded operator.
11391 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011392
Douglas Gregor084d8552009-03-13 23:49:33 +000011393 if (FnDecl) {
11394 // We matched an overloaded operator. Build a call to that
11395 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011396
Douglas Gregor084d8552009-03-13 23:49:33 +000011397 // Convert the arguments.
11398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011399 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011400
John Wiegley01296292011-04-08 18:41:53 +000011401 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011402 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011403 Best->FoundDecl, Method);
11404 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011405 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011406 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011407 } else {
11408 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011409 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011410 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011411 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011412 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011413 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011414 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011415 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011416 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011417 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011418 }
11419
Douglas Gregor084d8552009-03-13 23:49:33 +000011420 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011421 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011422 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011423 if (FnExpr.isInvalid())
11424 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011425
Richard Smithc1564702013-11-15 02:58:23 +000011426 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011427 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011428 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11429 ResultTy = ResultTy.getNonLValueExprType(Context);
11430
Eli Friedman030eee42009-11-18 03:58:17 +000011431 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011432 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011433 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011434 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011435
Alp Toker314cc812014-01-25 16:55:45 +000011436 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011437 return ExprError();
11438
John McCallb268a282010-08-23 23:25:46 +000011439 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011440 } else {
11441 // We matched a built-in operator. Convert the arguments, then
11442 // break out so that we will build the appropriate built-in
11443 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011444 ExprResult InputRes =
11445 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11446 Best->Conversions[0], AA_Passing);
11447 if (InputRes.isInvalid())
11448 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011449 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011450 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011451 }
John Wiegley01296292011-04-08 18:41:53 +000011452 }
11453
11454 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011455 // This is an erroneous use of an operator which can be overloaded by
11456 // a non-member function. Check for non-member operators which were
11457 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011458 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011459 // FIXME: Recover by calling the found function.
11460 return ExprError();
11461
John Wiegley01296292011-04-08 18:41:53 +000011462 // No viable function; fall through to handling this as a
11463 // built-in operator, which will produce an error message for us.
11464 break;
11465
11466 case OR_Ambiguous:
11467 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11468 << UnaryOperator::getOpcodeStr(Opc)
11469 << Input->getType()
11470 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011471 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011472 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11473 return ExprError();
11474
11475 case OR_Deleted:
11476 Diag(OpLoc, diag::err_ovl_deleted_oper)
11477 << Best->Function->isDeleted()
11478 << UnaryOperator::getOpcodeStr(Opc)
11479 << getDeletedOrUnavailableSuffix(Best->Function)
11480 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011481 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011482 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011483 return ExprError();
11484 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011485
11486 // Either we found no viable overloaded operator or we matched a
11487 // built-in operator. In either case, fall through to trying to
11488 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011489 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011490}
11491
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011492/// \brief Create a binary operation that may resolve to an overloaded
11493/// operator.
11494///
11495/// \param OpLoc The location of the operator itself (e.g., '+').
11496///
Craig Toppera92ffb02015-12-10 08:51:49 +000011497/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011498///
James Dennett18348b62012-06-22 08:52:37 +000011499/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011500/// considered by overload resolution. The caller needs to build this
11501/// set based on the context using, e.g.,
11502/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11503/// set should not contain any member functions; those will be added
11504/// by CreateOverloadedBinOp().
11505///
11506/// \param LHS Left-hand argument.
11507/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011508ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011509Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011510 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011511 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011512 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011513 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011514 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011515
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011516 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11517 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11518
11519 // If either side is type-dependent, create an appropriate dependent
11520 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011521 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011522 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011523 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011524 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011525 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011526 return new (Context) BinaryOperator(
11527 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11528 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011529
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011530 return new (Context) CompoundAssignOperator(
11531 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11532 Context.DependentTy, Context.DependentTy, OpLoc,
11533 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011534 }
John McCall4c4c1df2010-01-26 03:27:55 +000011535
11536 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011537 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011538 // TODO: provide better source location info in DNLoc component.
11539 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011540 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011541 = UnresolvedLookupExpr::Create(Context, NamingClass,
11542 NestedNameSpecifierLoc(), OpNameInfo,
11543 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011544 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011545 return new (Context)
11546 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11547 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011548 }
11549
John McCall4124c492011-10-17 18:40:02 +000011550 // Always do placeholder-like conversions on the RHS.
11551 if (checkPlaceholderForOverload(*this, Args[1]))
11552 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011553
John McCall526ab472011-10-25 17:37:35 +000011554 // Do placeholder-like conversion on the LHS; note that we should
11555 // not get here with a PseudoObject LHS.
11556 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011557 if (checkPlaceholderForOverload(*this, Args[0]))
11558 return ExprError();
11559
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011560 // If this is the assignment operator, we only perform overload resolution
11561 // if the left-hand side is a class or enumeration type. This is actually
11562 // a hack. The standard requires that we do overload resolution between the
11563 // various built-in candidates, but as DR507 points out, this can lead to
11564 // problems. So we do it this way, which pretty much follows what GCC does.
11565 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011566 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011567 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011568
John McCalle26a8722010-12-04 08:14:53 +000011569 // If this is the .* operator, which is not overloadable, just
11570 // create a built-in binary operator.
11571 if (Opc == BO_PtrMemD)
11572 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11573
Douglas Gregor084d8552009-03-13 23:49:33 +000011574 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011575 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011576
11577 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011578 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011579
11580 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011581 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011582
Richard Smith0daabd72014-09-23 20:31:39 +000011583 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11584 // performed for an assignment operator (nor for operator[] nor operator->,
11585 // which don't get here).
11586 if (Opc != BO_Assign)
11587 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11588 /*ExplicitTemplateArgs*/ nullptr,
11589 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011590
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011591 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011592 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011593
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011594 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11595
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011596 // Perform overload resolution.
11597 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011598 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011599 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011600 // We found a built-in operator or an overloaded operator.
11601 FunctionDecl *FnDecl = Best->Function;
11602
11603 if (FnDecl) {
11604 // We matched an overloaded operator. Build a call to that
11605 // operator.
11606
11607 // Convert the arguments.
11608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011609 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011610 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011611
Chandler Carruth8e543b32010-12-12 08:17:55 +000011612 ExprResult Arg1 =
11613 PerformCopyInitialization(
11614 InitializedEntity::InitializeParameter(Context,
11615 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011616 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011617 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011618 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011619
John Wiegley01296292011-04-08 18:41:53 +000011620 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011621 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011622 Best->FoundDecl, Method);
11623 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011624 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011625 Args[0] = Arg0.getAs<Expr>();
11626 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011627 } else {
11628 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011629 ExprResult Arg0 = PerformCopyInitialization(
11630 InitializedEntity::InitializeParameter(Context,
11631 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011632 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011633 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011634 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011635
Chandler Carruth8e543b32010-12-12 08:17:55 +000011636 ExprResult Arg1 =
11637 PerformCopyInitialization(
11638 InitializedEntity::InitializeParameter(Context,
11639 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011640 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011641 if (Arg1.isInvalid())
11642 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011643 Args[0] = LHS = Arg0.getAs<Expr>();
11644 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011645 }
11646
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011647 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011648 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011649 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011650 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011651 if (FnExpr.isInvalid())
11652 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011653
Richard Smithc1564702013-11-15 02:58:23 +000011654 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011655 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011656 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11657 ResultTy = ResultTy.getNonLValueExprType(Context);
11658
John McCallb268a282010-08-23 23:25:46 +000011659 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011660 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011661 Args, ResultTy, VK, OpLoc,
11662 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011663
Alp Toker314cc812014-01-25 16:55:45 +000011664 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011665 FnDecl))
11666 return ExprError();
11667
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011668 ArrayRef<const Expr *> ArgsArray(Args, 2);
11669 // Cut off the implicit 'this'.
11670 if (isa<CXXMethodDecl>(FnDecl))
11671 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011672
11673 // Check for a self move.
11674 if (Op == OO_Equal)
11675 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11676
Douglas Gregorb4866e82015-06-19 18:13:19 +000011677 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011678 TheCall->getSourceRange(), VariadicDoesNotApply);
11679
John McCallb268a282010-08-23 23:25:46 +000011680 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011681 } else {
11682 // We matched a built-in operator. Convert the arguments, then
11683 // break out so that we will build the appropriate built-in
11684 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011685 ExprResult ArgsRes0 =
11686 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11687 Best->Conversions[0], AA_Passing);
11688 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011689 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011690 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011691
John Wiegley01296292011-04-08 18:41:53 +000011692 ExprResult ArgsRes1 =
11693 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11694 Best->Conversions[1], AA_Passing);
11695 if (ArgsRes1.isInvalid())
11696 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011697 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011698 break;
11699 }
11700 }
11701
Douglas Gregor66950a32009-09-30 21:46:01 +000011702 case OR_No_Viable_Function: {
11703 // C++ [over.match.oper]p9:
11704 // If the operator is the operator , [...] and there are no
11705 // viable functions, then the operator is assumed to be the
11706 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011707 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011708 break;
11709
Chandler Carruth8e543b32010-12-12 08:17:55 +000011710 // For class as left operand for assignment or compound assigment
11711 // operator do not fall through to handling in built-in, but report that
11712 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011713 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011714 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011715 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011716 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11717 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011718 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011719 if (Args[0]->getType()->isIncompleteType()) {
11720 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11721 << Args[0]->getType()
11722 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11723 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011724 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011725 // This is an erroneous use of an operator which can be overloaded by
11726 // a non-member function. Check for non-member operators which were
11727 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011728 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011729 // FIXME: Recover by calling the found function.
11730 return ExprError();
11731
Douglas Gregor66950a32009-09-30 21:46:01 +000011732 // No viable function; try to create a built-in operation, which will
11733 // produce an error. Then, show the non-viable candidates.
11734 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011736 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011737 "C++ binary operator overloading is missing candidates!");
11738 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011739 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011740 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011741 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011742 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011743
11744 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011745 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011746 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011747 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011748 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011749 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011750 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011751 return ExprError();
11752
11753 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011754 if (isImplicitlyDeleted(Best->Function)) {
11755 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11756 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011757 << Context.getRecordType(Method->getParent())
11758 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011759
Richard Smithde1a4872012-12-28 12:23:24 +000011760 // The user probably meant to call this special member. Just
11761 // explain why it's deleted.
11762 NoteDeletedFunction(Method);
11763 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011764 } else {
11765 Diag(OpLoc, diag::err_ovl_deleted_oper)
11766 << Best->Function->isDeleted()
11767 << BinaryOperator::getOpcodeStr(Opc)
11768 << getDeletedOrUnavailableSuffix(Best->Function)
11769 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11770 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011771 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011772 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011773 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011774 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011775
Douglas Gregor66950a32009-09-30 21:46:01 +000011776 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011777 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011778}
11779
John McCalldadc5752010-08-24 06:29:42 +000011780ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011781Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11782 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011783 Expr *Base, Expr *Idx) {
11784 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011785 DeclarationName OpName =
11786 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11787
11788 // If either side is type-dependent, create an appropriate dependent
11789 // expression.
11790 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11791
Craig Topperc3ec1492014-05-26 06:22:03 +000011792 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011793 // CHECKME: no 'operator' keyword?
11794 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11795 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011796 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011797 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011798 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011799 /*ADL*/ true, /*Overloaded*/ false,
11800 UnresolvedSetIterator(),
11801 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011802 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011803
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011804 return new (Context)
11805 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11806 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011807 }
11808
John McCall4124c492011-10-17 18:40:02 +000011809 // Handle placeholders on both operands.
11810 if (checkPlaceholderForOverload(*this, Args[0]))
11811 return ExprError();
11812 if (checkPlaceholderForOverload(*this, Args[1]))
11813 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011814
Sebastian Redladba46e2009-10-29 20:17:01 +000011815 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011816 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011817
11818 // Subscript can only be overloaded as a member function.
11819
11820 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011821 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011822
11823 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011824 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011825
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011826 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11827
Sebastian Redladba46e2009-10-29 20:17:01 +000011828 // Perform overload resolution.
11829 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011830 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011831 case OR_Success: {
11832 // We found a built-in operator or an overloaded operator.
11833 FunctionDecl *FnDecl = Best->Function;
11834
11835 if (FnDecl) {
11836 // We matched an overloaded operator. Build a call to that
11837 // operator.
11838
John McCalla0296f72010-03-19 07:35:19 +000011839 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011840
Sebastian Redladba46e2009-10-29 20:17:01 +000011841 // Convert the arguments.
11842 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011843 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011844 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011845 Best->FoundDecl, Method);
11846 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011847 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011848 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011849
Anders Carlssona68e51e2010-01-29 18:37:50 +000011850 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011851 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011852 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011853 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011854 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011855 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011856 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011857 if (InputInit.isInvalid())
11858 return ExprError();
11859
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011860 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011861
Sebastian Redladba46e2009-10-29 20:17:01 +000011862 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011863 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11864 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011865 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011866 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011867 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011868 OpLocInfo.getLoc(),
11869 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011870 if (FnExpr.isInvalid())
11871 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011872
Richard Smithc1564702013-11-15 02:58:23 +000011873 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011874 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011875 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11876 ResultTy = ResultTy.getNonLValueExprType(Context);
11877
John McCallb268a282010-08-23 23:25:46 +000011878 CXXOperatorCallExpr *TheCall =
11879 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011880 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011881 ResultTy, VK, RLoc,
11882 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011883
Alp Toker314cc812014-01-25 16:55:45 +000011884 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011885 return ExprError();
11886
John McCallb268a282010-08-23 23:25:46 +000011887 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011888 } else {
11889 // We matched a built-in operator. Convert the arguments, then
11890 // break out so that we will build the appropriate built-in
11891 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011892 ExprResult ArgsRes0 =
11893 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11894 Best->Conversions[0], AA_Passing);
11895 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011896 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011897 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011898
11899 ExprResult ArgsRes1 =
11900 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11901 Best->Conversions[1], AA_Passing);
11902 if (ArgsRes1.isInvalid())
11903 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011904 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011905
11906 break;
11907 }
11908 }
11909
11910 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011911 if (CandidateSet.empty())
11912 Diag(LLoc, diag::err_ovl_no_oper)
11913 << Args[0]->getType() << /*subscript*/ 0
11914 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11915 else
11916 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11917 << Args[0]->getType()
11918 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011919 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011920 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011921 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011922 }
11923
11924 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011925 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011926 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011927 << Args[0]->getType() << Args[1]->getType()
11928 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011929 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011930 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011931 return ExprError();
11932
11933 case OR_Deleted:
11934 Diag(LLoc, diag::err_ovl_deleted_oper)
11935 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011936 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011937 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011938 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011939 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011940 return ExprError();
11941 }
11942
11943 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011944 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011945}
11946
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011947/// BuildCallToMemberFunction - Build a call to a member
11948/// function. MemExpr is the expression that refers to the member
11949/// function (and includes the object parameter), Args/NumArgs are the
11950/// arguments to the function call (not including the object
11951/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011952/// expression refers to a non-static member function or an overloaded
11953/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011954ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011955Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011956 SourceLocation LParenLoc,
11957 MultiExprArg Args,
11958 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011959 assert(MemExprE->getType() == Context.BoundMemberTy ||
11960 MemExprE->getType() == Context.OverloadTy);
11961
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011962 // Dig out the member expression. This holds both the object
11963 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011964 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011965
John McCall0009fcc2011-04-26 20:42:42 +000011966 // Determine whether this is a call to a pointer-to-member function.
11967 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11968 assert(op->getType() == Context.BoundMemberTy);
11969 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11970
11971 QualType fnType =
11972 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11973
11974 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11975 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011976 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011977
11978 // Check that the object type isn't more qualified than the
11979 // member function we're calling.
11980 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11981
11982 QualType objectType = op->getLHS()->getType();
11983 if (op->getOpcode() == BO_PtrMemI)
11984 objectType = objectType->castAs<PointerType>()->getPointeeType();
11985 Qualifiers objectQuals = objectType.getQualifiers();
11986
11987 Qualifiers difference = objectQuals - funcQuals;
11988 difference.removeObjCGCAttr();
11989 difference.removeAddressSpace();
11990 if (difference) {
11991 std::string qualsString = difference.getAsString();
11992 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11993 << fnType.getUnqualifiedType()
11994 << qualsString
11995 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11996 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011997
John McCall0009fcc2011-04-26 20:42:42 +000011998 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011999 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012000 resultType, valueKind, RParenLoc);
12001
Alp Toker314cc812014-01-25 16:55:45 +000012002 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012003 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012004 return ExprError();
12005
Craig Topperc3ec1492014-05-26 06:22:03 +000012006 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012007 return ExprError();
12008
Richard Trieu9be9c682013-06-22 02:30:38 +000012009 if (CheckOtherCall(call, proto))
12010 return ExprError();
12011
John McCall0009fcc2011-04-26 20:42:42 +000012012 return MaybeBindToTemporary(call);
12013 }
12014
David Majnemerced8bdf2015-02-25 17:36:15 +000012015 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12016 return new (Context)
12017 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12018
John McCall4124c492011-10-17 18:40:02 +000012019 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012020 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012021 return ExprError();
12022
John McCall10eae182009-11-30 22:42:35 +000012023 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012024 CXXMethodDecl *Method = nullptr;
12025 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12026 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012027 if (isa<MemberExpr>(NakedMemExpr)) {
12028 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012029 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012030 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012031 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012032 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012033 } else {
12034 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012035 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012036
John McCall6e9f8f62009-12-03 04:06:58 +000012037 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012038 Expr::Classification ObjectClassification
12039 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12040 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012041
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012042 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012043 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12044 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012045
John McCall2d74de92009-12-01 22:10:20 +000012046 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012047 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012048 if (UnresExpr->hasExplicitTemplateArgs()) {
12049 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12050 TemplateArgs = &TemplateArgsBuffer;
12051 }
12052
John McCall10eae182009-11-30 22:42:35 +000012053 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12054 E = UnresExpr->decls_end(); I != E; ++I) {
12055
John McCall6e9f8f62009-12-03 04:06:58 +000012056 NamedDecl *Func = *I;
12057 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12058 if (isa<UsingShadowDecl>(Func))
12059 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12060
Douglas Gregor02824322011-01-26 19:30:28 +000012061
Francois Pichet64225792011-01-18 05:04:39 +000012062 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012063 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012064 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012065 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012066 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012067 // If explicit template arguments were provided, we can't call a
12068 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012069 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012070 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012071
John McCalla0296f72010-03-19 07:35:19 +000012072 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012073 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012074 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012075 } else {
John McCall10eae182009-11-30 22:42:35 +000012076 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012077 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012078 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012079 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012080 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012081 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012082 }
Mike Stump11289f42009-09-09 15:08:12 +000012083
John McCall10eae182009-11-30 22:42:35 +000012084 DeclarationName DeclName = UnresExpr->getMemberName();
12085
John McCall4124c492011-10-17 18:40:02 +000012086 UnbridgedCasts.restore();
12087
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012088 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012089 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012090 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012091 case OR_Success:
12092 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012093 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012094 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012095 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12096 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012097 // If FoundDecl is different from Method (such as if one is a template
12098 // and the other a specialization), make sure DiagnoseUseOfDecl is
12099 // called on both.
12100 // FIXME: This would be more comprehensively addressed by modifying
12101 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12102 // being used.
12103 if (Method != FoundDecl.getDecl() &&
12104 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12105 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012106 break;
12107
12108 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012109 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012110 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012111 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012112 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012113 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012114 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012115
12116 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012117 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012118 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012119 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012120 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012121 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012122
12123 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012124 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012125 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012126 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012127 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012128 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012129 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012130 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012131 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012132 }
12133
John McCall16df1e52010-03-30 21:47:33 +000012134 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012135
John McCall2d74de92009-12-01 22:10:20 +000012136 // If overload resolution picked a static member, build a
12137 // non-member call based on that function.
12138 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012139 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12140 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012141 }
12142
John McCall10eae182009-11-30 22:42:35 +000012143 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012144 }
12145
Alp Toker314cc812014-01-25 16:55:45 +000012146 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012147 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12148 ResultType = ResultType.getNonLValueExprType(Context);
12149
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012150 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012151 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012152 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012153 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012154
Eli Bendersky291a57e2014-09-25 23:59:08 +000012155 // (CUDA B.1): Check for invalid calls between targets.
12156 if (getLangOpts().CUDA) {
12157 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12158 if (CheckCUDATarget(Caller, Method)) {
12159 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12160 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12161 << IdentifyCUDATarget(Caller);
12162 return ExprError();
12163 }
12164 }
12165 }
12166
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012167 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012168 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012169 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012170 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012171
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012172 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012173 // We only need to do this if there was actually an overload; otherwise
12174 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012175 if (!Method->isStatic()) {
12176 ExprResult ObjectArg =
12177 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12178 FoundDecl, Method);
12179 if (ObjectArg.isInvalid())
12180 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012181 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012182 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012183
12184 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012185 const FunctionProtoType *Proto =
12186 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012187 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012188 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012189 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012190
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012191 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012192
Richard Smith55ce3522012-06-25 20:30:08 +000012193 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012194 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012195
George Burgess IVaea6ade2015-09-25 17:53:16 +000012196 // In the case the method to call was not selected by the overloading
12197 // resolution process, we still need to handle the enable_if attribute. Do
12198 // that here, so it will not hide previous -- and more relevant -- errors
12199 if (isa<MemberExpr>(NakedMemExpr)) {
12200 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12201 Diag(MemExprE->getLocStart(),
12202 diag::err_ovl_no_viable_member_function_in_call)
12203 << Method << Method->getSourceRange();
12204 Diag(Method->getLocation(),
12205 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12206 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12207 return ExprError();
12208 }
12209 }
12210
Anders Carlsson47061ee2011-05-06 14:25:31 +000012211 if ((isa<CXXConstructorDecl>(CurContext) ||
12212 isa<CXXDestructorDecl>(CurContext)) &&
12213 TheCall->getMethodDecl()->isPure()) {
12214 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12215
Davide Italianoccb37382015-07-14 23:36:10 +000012216 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12217 MemExpr->performsVirtualDispatch(getLangOpts())) {
12218 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012219 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12220 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12221 << MD->getParent()->getDeclName();
12222
12223 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012224 if (getLangOpts().AppleKext)
12225 Diag(MemExpr->getLocStart(),
12226 diag::note_pure_qualified_call_kext)
12227 << MD->getParent()->getDeclName()
12228 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012229 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012230 }
John McCallb268a282010-08-23 23:25:46 +000012231 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012232}
12233
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012234/// BuildCallToObjectOfClassType - Build a call to an object of class
12235/// type (C++ [over.call.object]), which can end up invoking an
12236/// overloaded function call operator (@c operator()) or performing a
12237/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012238ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012239Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012240 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012241 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012242 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012243 if (checkPlaceholderForOverload(*this, Obj))
12244 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012245 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012246
12247 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012248 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012249 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012250
Nico Weberb58e51c2014-11-19 05:21:39 +000012251 assert(Object.get()->getType()->isRecordType() &&
12252 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012253 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012254
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012255 // C++ [over.call.object]p1:
12256 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012257 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012258 // candidate functions includes at least the function call
12259 // operators of T. The function call operators of T are obtained by
12260 // ordinary lookup of the name operator() in the context of
12261 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012262 OverloadCandidateSet CandidateSet(LParenLoc,
12263 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012264 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012265
John Wiegley01296292011-04-08 18:41:53 +000012266 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012267 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012268 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012269
John McCall27b18f82009-11-17 02:14:36 +000012270 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12271 LookupQualifiedName(R, Record->getDecl());
12272 R.suppressDiagnostics();
12273
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012274 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012275 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012276 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012277 Object.get()->Classify(Context),
12278 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012279 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012281
Douglas Gregorab7897a2008-11-19 22:57:39 +000012282 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012283 // In addition, for each (non-explicit in C++0x) conversion function
12284 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012285 //
12286 // operator conversion-type-id () cv-qualifier;
12287 //
12288 // where cv-qualifier is the same cv-qualification as, or a
12289 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012290 // denotes the type "pointer to function of (P1,...,Pn) returning
12291 // R", or the type "reference to pointer to function of
12292 // (P1,...,Pn) returning R", or the type "reference to function
12293 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012294 // is also considered as a candidate function. Similarly,
12295 // surrogate call functions are added to the set of candidate
12296 // functions for each conversion function declared in an
12297 // accessible base class provided the function is not hidden
12298 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012299 const auto &Conversions =
12300 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12301 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012302 NamedDecl *D = *I;
12303 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12304 if (isa<UsingShadowDecl>(D))
12305 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012306
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012307 // Skip over templated conversion functions; they aren't
12308 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012309 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012310 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012311
John McCall6e9f8f62009-12-03 04:06:58 +000012312 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012313 if (!Conv->isExplicit()) {
12314 // Strip the reference type (if any) and then the pointer type (if
12315 // any) to get down to what might be a function type.
12316 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12317 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12318 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012319
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012320 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12321 {
12322 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012323 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012324 }
12325 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012326 }
Mike Stump11289f42009-09-09 15:08:12 +000012327
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012328 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12329
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012330 // Perform overload resolution.
12331 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012332 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012333 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012334 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012335 // Overload resolution succeeded; we'll build the appropriate call
12336 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012337 break;
12338
12339 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012340 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012341 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012342 << Object.get()->getType() << /*call*/ 1
12343 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012344 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012345 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012346 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012347 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012348 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012349 break;
12350
12351 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012352 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012353 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012354 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012355 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012356 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012357
12358 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012359 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012360 diag::err_ovl_deleted_object_call)
12361 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012362 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012363 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012364 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012365 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012366 break;
Mike Stump11289f42009-09-09 15:08:12 +000012367 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012368
Douglas Gregorb412e172010-07-25 18:17:45 +000012369 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012370 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012371
John McCall4124c492011-10-17 18:40:02 +000012372 UnbridgedCasts.restore();
12373
Craig Topperc3ec1492014-05-26 06:22:03 +000012374 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012375 // Since there is no function declaration, this is one of the
12376 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012377 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012378 = cast<CXXConversionDecl>(
12379 Best->Conversions[0].UserDefined.ConversionFunction);
12380
Craig Topperc3ec1492014-05-26 06:22:03 +000012381 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12382 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012383 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12384 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012385 assert(Conv == Best->FoundDecl.getDecl() &&
12386 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012387 // We selected one of the surrogate functions that converts the
12388 // object parameter to a function pointer. Perform the conversion
12389 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012390
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012391 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012392 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012393 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12394 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012395 if (Call.isInvalid())
12396 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012397 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012398 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12399 CK_UserDefinedConversion, Call.get(),
12400 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012401
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012402 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012403 }
12404
Craig Topperc3ec1492014-05-26 06:22:03 +000012405 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012406
Douglas Gregorab7897a2008-11-19 22:57:39 +000012407 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12408 // that calls this method, using Object for the implicit object
12409 // parameter and passing along the remaining arguments.
12410 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012411
12412 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012413 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012414 return ExprError();
12415
Chandler Carruth8e543b32010-12-12 08:17:55 +000012416 const FunctionProtoType *Proto =
12417 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012418
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012419 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012420
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012421 DeclarationNameInfo OpLocInfo(
12422 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12423 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012424 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012425 HadMultipleCandidates,
12426 OpLocInfo.getLoc(),
12427 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012428 if (NewFn.isInvalid())
12429 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012430
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012431 // Build the full argument list for the method call (the implicit object
12432 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012433 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012434 MethodArgs[0] = Object.get();
12435 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12436
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012437 // Once we've built TheCall, all of the expressions are properly
12438 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012439 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012440 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12441 ResultTy = ResultTy.getNonLValueExprType(Context);
12442
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012443 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012444 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012445 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12446 ResultTy, VK, RParenLoc, false);
12447 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012448
Alp Toker314cc812014-01-25 16:55:45 +000012449 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012450 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012451
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012452 // We may have default arguments. If so, we need to allocate more
12453 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012454 if (Args.size() < NumParams)
12455 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012456
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012457 bool IsError = false;
12458
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012459 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012460 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012461 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012462 Best->FoundDecl, Method);
12463 if (ObjRes.isInvalid())
12464 IsError = true;
12465 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012466 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012467 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012468
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012469 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012470 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012471 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012472 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012473 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012474
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012475 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012476
John McCalldadc5752010-08-24 06:29:42 +000012477 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012478 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012479 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012480 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012481 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012482
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012483 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012484 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012485 } else {
John McCalldadc5752010-08-24 06:29:42 +000012486 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012487 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12488 if (DefArg.isInvalid()) {
12489 IsError = true;
12490 break;
12491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012492
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012493 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012494 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012495
12496 TheCall->setArg(i + 1, Arg);
12497 }
12498
12499 // If this is a variadic call, handle args passed through "...".
12500 if (Proto->isVariadic()) {
12501 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012502 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012503 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12504 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012505 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012506 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012507 }
12508 }
12509
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012510 if (IsError) return true;
12511
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012512 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012513
Richard Smith55ce3522012-06-25 20:30:08 +000012514 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012515 return true;
12516
John McCalle172be52010-08-24 06:09:16 +000012517 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012518}
12519
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012520/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012521/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012522/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012523ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012524Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12525 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012526 assert(Base->getType()->isRecordType() &&
12527 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012528
John McCall4124c492011-10-17 18:40:02 +000012529 if (checkPlaceholderForOverload(*this, Base))
12530 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012531
John McCallbc077cf2010-02-08 23:07:23 +000012532 SourceLocation Loc = Base->getExprLoc();
12533
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012534 // C++ [over.ref]p1:
12535 //
12536 // [...] An expression x->m is interpreted as (x.operator->())->m
12537 // for a class object x of type T if T::operator->() exists and if
12538 // the operator is selected as the best match function by the
12539 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012540 DeclarationName OpName =
12541 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012542 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012543 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012544
John McCallbc077cf2010-02-08 23:07:23 +000012545 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012546 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012547 return ExprError();
12548
John McCall27b18f82009-11-17 02:14:36 +000012549 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12550 LookupQualifiedName(R, BaseRecord->getDecl());
12551 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012552
12553 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012554 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012555 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012556 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012557 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012558
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012559 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12560
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012561 // Perform overload resolution.
12562 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012563 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012564 case OR_Success:
12565 // Overload resolution succeeded; we'll build the call below.
12566 break;
12567
12568 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012569 if (CandidateSet.empty()) {
12570 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012571 if (NoArrowOperatorFound) {
12572 // Report this specific error to the caller instead of emitting a
12573 // diagnostic, as requested.
12574 *NoArrowOperatorFound = true;
12575 return ExprError();
12576 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012577 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12578 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012579 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012580 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012581 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012582 }
12583 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012584 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012585 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012586 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012587 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012588
12589 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012590 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12591 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012592 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012593 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012594
12595 case OR_Deleted:
12596 Diag(OpLoc, diag::err_ovl_deleted_oper)
12597 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012598 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012599 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012600 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012601 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012602 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012603 }
12604
Craig Topperc3ec1492014-05-26 06:22:03 +000012605 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012606
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012607 // Convert the object parameter.
12608 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012609 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012610 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012611 Best->FoundDecl, Method);
12612 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012613 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012614 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012615
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012616 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012617 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012618 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012619 if (FnExpr.isInvalid())
12620 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012621
Alp Toker314cc812014-01-25 16:55:45 +000012622 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012623 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12624 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012625 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012626 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012627 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012628
Alp Toker314cc812014-01-25 16:55:45 +000012629 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012630 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012631
12632 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012633}
12634
Richard Smithbcc22fc2012-03-09 08:00:36 +000012635/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12636/// a literal operator described by the provided lookup results.
12637ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12638 DeclarationNameInfo &SuffixInfo,
12639 ArrayRef<Expr*> Args,
12640 SourceLocation LitEndLoc,
12641 TemplateArgumentListInfo *TemplateArgs) {
12642 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012643
Richard Smith100b24a2014-04-17 01:52:14 +000012644 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12645 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012646 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12647 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012648
Richard Smithbcc22fc2012-03-09 08:00:36 +000012649 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12650
Richard Smithbcc22fc2012-03-09 08:00:36 +000012651 // Perform overload resolution. This will usually be trivial, but might need
12652 // to perform substitutions for a literal operator template.
12653 OverloadCandidateSet::iterator Best;
12654 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12655 case OR_Success:
12656 case OR_Deleted:
12657 break;
12658
12659 case OR_No_Viable_Function:
12660 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12661 << R.getLookupName();
12662 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12663 return ExprError();
12664
12665 case OR_Ambiguous:
12666 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12667 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12668 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012669 }
12670
Richard Smithbcc22fc2012-03-09 08:00:36 +000012671 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012672 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12673 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012674 SuffixInfo.getLoc(),
12675 SuffixInfo.getInfo());
12676 if (Fn.isInvalid())
12677 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012678
12679 // Check the argument types. This should almost always be a no-op, except
12680 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012681 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012682 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012683 ExprResult InputInit = PerformCopyInitialization(
12684 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12685 SourceLocation(), Args[ArgIdx]);
12686 if (InputInit.isInvalid())
12687 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012688 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012689 }
12690
Alp Toker314cc812014-01-25 16:55:45 +000012691 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012692 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12693 ResultTy = ResultTy.getNonLValueExprType(Context);
12694
Richard Smithc67fdd42012-03-07 08:35:16 +000012695 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012696 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012697 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012698 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12699
Alp Toker314cc812014-01-25 16:55:45 +000012700 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012701 return ExprError();
12702
Craig Topperc3ec1492014-05-26 06:22:03 +000012703 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012704 return ExprError();
12705
12706 return MaybeBindToTemporary(UDL);
12707}
12708
Sam Panzer0f384432012-08-21 00:52:01 +000012709/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12710/// given LookupResult is non-empty, it is assumed to describe a member which
12711/// will be invoked. Otherwise, the function will be found via argument
12712/// dependent lookup.
12713/// CallExpr is set to a valid expression and FRS_Success returned on success,
12714/// otherwise CallExpr is set to ExprError() and some non-success value
12715/// is returned.
12716Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012717Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12718 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012719 const DeclarationNameInfo &NameInfo,
12720 LookupResult &MemberLookup,
12721 OverloadCandidateSet *CandidateSet,
12722 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012723 Scope *S = nullptr;
12724
Sam Panzer0f384432012-08-21 00:52:01 +000012725 CandidateSet->clear();
12726 if (!MemberLookup.empty()) {
12727 ExprResult MemberRef =
12728 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12729 /*IsPtr=*/false, CXXScopeSpec(),
12730 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012731 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012732 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012733 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012734 if (MemberRef.isInvalid()) {
12735 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012736 return FRS_DiagnosticIssued;
12737 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012738 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012739 if (CallExpr->isInvalid()) {
12740 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012741 return FRS_DiagnosticIssued;
12742 }
12743 } else {
12744 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012745 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012746 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012747 NestedNameSpecifierLoc(), NameInfo,
12748 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012749 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012750
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012751 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012752 CandidateSet, CallExpr);
12753 if (CandidateSet->empty() || CandidateSetError) {
12754 *CallExpr = ExprError();
12755 return FRS_NoViableFunction;
12756 }
12757 OverloadCandidateSet::iterator Best;
12758 OverloadingResult OverloadResult =
12759 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12760
12761 if (OverloadResult == OR_No_Viable_Function) {
12762 *CallExpr = ExprError();
12763 return FRS_NoViableFunction;
12764 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012765 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012766 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012767 OverloadResult,
12768 /*AllowTypoCorrection=*/false);
12769 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12770 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012771 return FRS_DiagnosticIssued;
12772 }
12773 }
12774 return FRS_Success;
12775}
12776
12777
Douglas Gregorcd695e52008-11-10 20:40:00 +000012778/// FixOverloadedFunctionReference - E is an expression that refers to
12779/// a C++ overloaded function (possibly with some parentheses and
12780/// perhaps a '&' around it). We have resolved the overloaded function
12781/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012782/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012783Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012784 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012785 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012786 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12787 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012788 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012789 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012790
Douglas Gregor51c538b2009-11-20 19:42:02 +000012791 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012792 }
12793
Douglas Gregor51c538b2009-11-20 19:42:02 +000012794 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012795 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12796 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012797 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012798 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012799 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012800 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012801 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012802 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012803
12804 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012805 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012806 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012807 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012808 }
12809
Douglas Gregor51c538b2009-11-20 19:42:02 +000012810 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012811 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012812 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012813 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12814 if (Method->isStatic()) {
12815 // Do nothing: static member functions aren't any different
12816 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012817 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012818 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012819 // UnresolvedLookupExpr holding an overloaded member function
12820 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012821 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12822 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012823 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012824 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012825
John McCalld14a8642009-11-21 08:51:07 +000012826 assert(isa<DeclRefExpr>(SubExpr)
12827 && "fixed to something other than a decl ref");
12828 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12829 && "fixed to a member ref with no nested name qualifier");
12830
12831 // We have taken the address of a pointer to member
12832 // function. Perform the computation here so that we get the
12833 // appropriate pointer to member type.
12834 QualType ClassType
12835 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12836 QualType MemPtrType
12837 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12838
John McCall7decc9e2010-11-18 06:31:45 +000012839 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12840 VK_RValue, OK_Ordinary,
12841 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012842 }
12843 }
John McCall16df1e52010-03-30 21:47:33 +000012844 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12845 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012846 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012847 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012848
John McCalle3027922010-08-25 11:45:40 +000012849 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012850 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012851 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012852 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012853 }
John McCalld14a8642009-11-21 08:51:07 +000012854
12855 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012856 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012857 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012858 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012859 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12860 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012861 }
12862
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012863 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12864 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012865 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012866 Fn,
John McCall113bee02012-03-10 09:33:50 +000012867 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012868 ULE->getNameLoc(),
12869 Fn->getType(),
12870 VK_LValue,
12871 Found.getDecl(),
12872 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012873 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012874 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12875 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012876 }
12877
John McCall10eae182009-11-30 22:42:35 +000012878 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012879 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012880 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012881 if (MemExpr->hasExplicitTemplateArgs()) {
12882 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12883 TemplateArgs = &TemplateArgsBuffer;
12884 }
John McCall6b51f282009-11-23 01:53:49 +000012885
John McCall2d74de92009-12-01 22:10:20 +000012886 Expr *Base;
12887
John McCall7decc9e2010-11-18 06:31:45 +000012888 // If we're filling in a static method where we used to have an
12889 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012890 if (MemExpr->isImplicitAccess()) {
12891 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012892 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12893 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012894 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012895 Fn,
John McCall113bee02012-03-10 09:33:50 +000012896 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012897 MemExpr->getMemberLoc(),
12898 Fn->getType(),
12899 VK_LValue,
12900 Found.getDecl(),
12901 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012902 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012903 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12904 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012905 } else {
12906 SourceLocation Loc = MemExpr->getMemberLoc();
12907 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012908 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012909 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012910 Base = new (Context) CXXThisExpr(Loc,
12911 MemExpr->getBaseType(),
12912 /*isImplicit=*/true);
12913 }
John McCall2d74de92009-12-01 22:10:20 +000012914 } else
John McCallc3007a22010-10-26 07:05:15 +000012915 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012916
John McCall4adb38c2011-04-27 00:36:17 +000012917 ExprValueKind valueKind;
12918 QualType type;
12919 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12920 valueKind = VK_LValue;
12921 type = Fn->getType();
12922 } else {
12923 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012924 type = Context.BoundMemberTy;
12925 }
12926
12927 MemberExpr *ME = MemberExpr::Create(
12928 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12929 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12930 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12931 OK_Ordinary);
12932 ME->setHadMultipleCandidates(true);
12933 MarkMemberReferenced(ME);
12934 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012936
John McCallc3007a22010-10-26 07:05:15 +000012937 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012938}
12939
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012940ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012941 DeclAccessPair Found,
12942 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012943 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012944}