blob: 0790dd15e1349a9cf4ffe07464760d7beb2e6092 [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:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000261 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000262 case CK_FloatingToIntegral:
263 case CK_FloatingToBoolean:
264 case CK_FloatingCast:
265 Converted = ICE->getSubExpr();
266 continue;
267
268 default:
269 return Converted;
270 }
271 }
272
273 return Converted;
274}
275
276/// Check if this standard conversion sequence represents a narrowing
277/// conversion, according to C++11 [dcl.init.list]p7.
278///
279/// \param Ctx The AST context.
280/// \param Converted The result of applying this standard conversion sequence.
281/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
282/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000283/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
284/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000285NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000286StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
287 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000288 APValue &ConstantValue,
289 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000290 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000291
292 // C++11 [dcl.init.list]p7:
293 // A narrowing conversion is an implicit conversion ...
294 QualType FromType = getToType(0);
295 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000296
297 // A conversion to an enumeration type is narrowing if the conversion to
298 // the underlying type is narrowing. This only arises for expressions of
299 // the form 'Enum{init}'.
300 if (auto *ET = ToType->getAs<EnumType>())
301 ToType = ET->getDecl()->getIntegerType();
302
Richard Smith66e05fe2012-01-18 05:21:49 +0000303 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000304 // 'bool' is an integral type; dispatch to the right place to handle it.
305 case ICK_Boolean_Conversion:
306 if (FromType->isRealFloatingType())
307 goto FloatingIntegralConversion;
308 if (FromType->isIntegralOrUnscopedEnumerationType())
309 goto IntegralConversion;
310 // Boolean conversions can be from pointers and pointers to members
311 // [conv.bool], and those aren't considered narrowing conversions.
312 return NK_Not_Narrowing;
313
Richard Smith66e05fe2012-01-18 05:21:49 +0000314 // -- from a floating-point type to an integer type, or
315 //
316 // -- from an integer type or unscoped enumeration type to a floating-point
317 // type, except where the source is a constant expression and the actual
318 // value after conversion will fit into the target type and will produce
319 // the original value when converted back to the original type, or
320 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000321 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000322 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
323 return NK_Type_Narrowing;
324 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
325 llvm::APSInt IntConstantValue;
326 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
327 if (Initializer &&
328 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
329 // Convert the integer to the floating type.
330 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
331 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
332 llvm::APFloat::rmNearestTiesToEven);
333 // And back.
334 llvm::APSInt ConvertedValue = IntConstantValue;
335 bool ignored;
336 Result.convertToInteger(ConvertedValue,
337 llvm::APFloat::rmTowardZero, &ignored);
338 // If the resulting value is different, this was a narrowing conversion.
339 if (IntConstantValue != ConvertedValue) {
340 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000341 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000342 return NK_Constant_Narrowing;
343 }
344 } else {
345 // Variables are always narrowings.
346 return NK_Variable_Narrowing;
347 }
348 }
349 return NK_Not_Narrowing;
350
351 // -- from long double to double or float, or from double to float, except
352 // where the source is a constant expression and the actual value after
353 // conversion is within the range of values that can be represented (even
354 // if it cannot be represented exactly), or
355 case ICK_Floating_Conversion:
356 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
357 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
358 // FromType is larger than ToType.
359 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
360 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
361 // Constant!
362 assert(ConstantValue.isFloat());
363 llvm::APFloat FloatVal = ConstantValue.getFloat();
364 // Convert the source value into the target type.
365 bool ignored;
366 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
367 Ctx.getFloatTypeSemantics(ToType),
368 llvm::APFloat::rmNearestTiesToEven, &ignored);
369 // If there was no overflow, the source value is within the range of
370 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000371 if (ConvertStatus & llvm::APFloat::opOverflow) {
372 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000373 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000374 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000375 } else {
376 return NK_Variable_Narrowing;
377 }
378 }
379 return NK_Not_Narrowing;
380
381 // -- from an integer type or unscoped enumeration type to an integer type
382 // that cannot represent all the values of the original type, except where
383 // the source is a constant expression and the actual value after
384 // conversion will fit into the target type and will produce the original
385 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000386 case ICK_Integral_Conversion:
387 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000388 assert(FromType->isIntegralOrUnscopedEnumerationType());
389 assert(ToType->isIntegralOrUnscopedEnumerationType());
390 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
391 const unsigned FromWidth = Ctx.getIntWidth(FromType);
392 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
393 const unsigned ToWidth = Ctx.getIntWidth(ToType);
394
395 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000396 (FromWidth == ToWidth && FromSigned != ToSigned) ||
397 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000398 // Not all values of FromType can be represented in ToType.
399 llvm::APSInt InitializerValue;
400 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000401 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
402 // Such conversions on variables are always narrowing.
403 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000404 }
405 bool Narrowing = false;
406 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000407 // Negative -> unsigned is narrowing. Otherwise, more bits is never
408 // narrowing.
409 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000410 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000411 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000412 // Add a bit to the InitializerValue so we don't have to worry about
413 // signed vs. unsigned comparisons.
414 InitializerValue = InitializerValue.extend(
415 InitializerValue.getBitWidth() + 1);
416 // Convert the initializer to and from the target width and signed-ness.
417 llvm::APSInt ConvertedValue = InitializerValue;
418 ConvertedValue = ConvertedValue.trunc(ToWidth);
419 ConvertedValue.setIsSigned(ToSigned);
420 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
421 ConvertedValue.setIsSigned(InitializerValue.isSigned());
422 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000423 if (ConvertedValue != InitializerValue)
424 Narrowing = true;
425 }
426 if (Narrowing) {
427 ConstantType = Initializer->getType();
428 ConstantValue = APValue(InitializerValue);
429 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000430 }
431 }
432 return NK_Not_Narrowing;
433 }
434
435 default:
436 // Other kinds of conversions are not narrowings.
437 return NK_Not_Narrowing;
438 }
439}
440
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000441/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000442/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000443LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000444 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000445 bool PrintedSomething = false;
446 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000448 PrintedSomething = true;
449 }
450
451 if (Second != ICK_Identity) {
452 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000453 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000454 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000456
457 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000458 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000459 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000460 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000461 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000462 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000463 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000464 PrintedSomething = true;
465 }
466
467 if (Third != ICK_Identity) {
468 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000469 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472 PrintedSomething = true;
473 }
474
475 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000476 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 }
478}
479
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000480/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000481/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000482void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000483 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000486 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000488 if (ConversionFunction)
489 OS << '\'' << *ConversionFunction << '\'';
490 else
491 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000493 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000494 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 }
496}
497
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000498/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000500void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000501 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000502 if (isStdInitializerListElement())
503 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 switch (ConversionKind) {
505 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000507 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 break;
509 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000510 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000511 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 break;
513 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000514 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515 break;
John McCall0d1da222010-01-12 00:44:57 +0000516 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000517 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000518 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000519 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000520 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000521 break;
522 }
523
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000524 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525}
526
John McCall0d1da222010-01-12 00:44:57 +0000527void AmbiguousConversionSequence::construct() {
528 new (&conversions()) ConversionSet();
529}
530
531void AmbiguousConversionSequence::destruct() {
532 conversions().~ConversionSet();
533}
534
535void
536AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
537 FromTypePtr = O.FromTypePtr;
538 ToTypePtr = O.ToTypePtr;
539 new (&conversions()) ConversionSet(O.conversions());
540}
541
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000542namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000543 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000544 // template argument information.
545 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000546 TemplateArgument FirstArg;
547 TemplateArgument SecondArg;
548 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000549 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000550 // template parameter and template argument information.
551 struct DFIParamWithArguments : DFIArguments {
552 TemplateParameter Param;
553 };
Richard Smith9b534542015-12-31 02:02:54 +0000554 // Structure used by DeductionFailureInfo to store template argument
555 // information and the index of the problematic call argument.
556 struct DFIDeducedMismatchArgs : DFIArguments {
557 TemplateArgumentList *TemplateArgs;
558 unsigned CallArgIndex;
559 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000560}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000561
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562/// \brief Convert from Sema's representation of template deduction information
563/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000564DeductionFailureInfo
565clang::MakeDeductionFailureInfo(ASTContext &Context,
566 Sema::TemplateDeductionResult TDK,
567 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000568 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000569 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000570 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000571 switch (TDK) {
572 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000573 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000575 case Sema::TDK_TooManyArguments:
576 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000577 case Sema::TDK_MiscellaneousDeductionFailure:
578 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000579 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000581 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000582 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583 Result.Data = Info.Param.getOpaqueValue();
584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Richard Smith9b534542015-12-31 02:02:54 +0000586 case Sema::TDK_DeducedMismatch: {
587 // FIXME: Should allocate from normal heap so that we can free this later.
588 auto *Saved = new (Context) DFIDeducedMismatchArgs;
589 Saved->FirstArg = Info.FirstArg;
590 Saved->SecondArg = Info.SecondArg;
591 Saved->TemplateArgs = Info.take();
592 Saved->CallArgIndex = Info.CallArgIndex;
593 Result.Data = Saved;
594 break;
595 }
596
Richard Smith44ecdbd2013-01-31 05:19:49 +0000597 case Sema::TDK_NonDeducedMismatch: {
598 // FIXME: Should allocate from normal heap so that we can free this later.
599 DFIArguments *Saved = new (Context) DFIArguments;
600 Saved->FirstArg = Info.FirstArg;
601 Saved->SecondArg = Info.SecondArg;
602 Result.Data = Saved;
603 break;
604 }
605
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000606 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000607 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000608 // FIXME: Should allocate from normal heap so that we can free this later.
609 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 Saved->Param = Info.Param;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Result.Data = Saved;
614 break;
615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000617 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000619 if (Info.hasSFINAEDiagnostic()) {
620 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
621 SourceLocation(), PartialDiagnostic::NullDiagnostic());
622 Info.takeSFINAEDiagnostic(*Diag);
623 Result.HasDiagnostic = true;
624 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000628 Result.Data = Info.Expression;
629 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 return Result;
633}
John McCall0d1da222010-01-12 00:44:57 +0000634
Larisse Voufo98b20f12013-07-19 23:00:19 +0000635void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000636 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
637 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000638 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 case Sema::TDK_InstantiationDepth:
640 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000641 case Sema::TDK_TooManyArguments:
642 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000643 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000644 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000646
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000647 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000648 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000649 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000650 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000651 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000652 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000654
655 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000656 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000657 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000658 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
659 Diag->~PartialDiagnosticAt();
660 HasDiagnostic = false;
661 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor461761d2010-05-08 18:20:53 +0000664 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000665 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000666 break;
667 }
668}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Larisse Voufo98b20f12013-07-19 23:00:19 +0000670PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000671 if (HasDiagnostic)
672 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000673 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000674}
675
Larisse Voufo98b20f12013-07-19 23:00:19 +0000676TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
678 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000679 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000680 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000681 case Sema::TDK_TooManyArguments:
682 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000683 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000684 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000685 case Sema::TDK_NonDeducedMismatch:
686 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000687 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000689 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000690 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692
693 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000694 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000695 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000698 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000699 break;
700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 return TemplateParameter();
703}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
Larisse Voufo98b20f12013-07-19 23:00:19 +0000705TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000707 case Sema::TDK_Success:
708 case Sema::TDK_Invalid:
709 case Sema::TDK_InstantiationDepth:
710 case Sema::TDK_TooManyArguments:
711 case Sema::TDK_TooFewArguments:
712 case Sema::TDK_Incomplete:
713 case Sema::TDK_InvalidExplicitArguments:
714 case Sema::TDK_Inconsistent:
715 case Sema::TDK_Underqualified:
716 case Sema::TDK_NonDeducedMismatch:
717 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000718 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000719
Richard Smith9b534542015-12-31 02:02:54 +0000720 case Sema::TDK_DeducedMismatch:
721 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
722
Richard Smith44ecdbd2013-01-31 05:19:49 +0000723 case Sema::TDK_SubstitutionFailure:
724 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
Richard Smith44ecdbd2013-01-31 05:19:49 +0000726 // Unhandled
727 case Sema::TDK_MiscellaneousDeductionFailure:
728 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000729 }
730
Craig Topperc3ec1492014-05-26 06:22:03 +0000731 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000732}
733
Larisse Voufo98b20f12013-07-19 23:00:19 +0000734const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000735 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
736 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000737 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_InstantiationDepth:
739 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000740 case Sema::TDK_TooManyArguments:
741 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000742 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000743 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000745 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000746
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000747 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000748 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000749 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000750 case Sema::TDK_NonDeducedMismatch:
751 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752
Douglas Gregor461761d2010-05-08 18:20:53 +0000753 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000754 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755 break;
756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757
Craig Topperc3ec1492014-05-26 06:22:03 +0000758 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000760
Larisse Voufo98b20f12013-07-19 23:00:19 +0000761const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000762 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
763 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000764 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000765 case Sema::TDK_InstantiationDepth:
766 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000767 case Sema::TDK_TooManyArguments:
768 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000769 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000770 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000771 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000772 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000773
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000774 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000775 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000776 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000777 case Sema::TDK_NonDeducedMismatch:
778 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000779
Douglas Gregor461761d2010-05-08 18:20:53 +0000780 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000781 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000782 break;
783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000784
Craig Topperc3ec1492014-05-26 06:22:03 +0000785 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000786}
787
Larisse Voufo98b20f12013-07-19 23:00:19 +0000788Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000789 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
790 Sema::TDK_FailedOverloadResolution)
791 return static_cast<Expr*>(Data);
792
Craig Topperc3ec1492014-05-26 06:22:03 +0000793 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000794}
795
Richard Smith9b534542015-12-31 02:02:54 +0000796llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
797 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
798 Sema::TDK_DeducedMismatch)
799 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
800
801 return llvm::None;
802}
803
Benjamin Kramer97e59492012-10-09 15:52:25 +0000804void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000805 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000806 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
807 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000808 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
809 i->DeductionFailure.Destroy();
810 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000811}
812
813void OverloadCandidateSet::clear() {
814 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000815 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000816 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000817 Functions.clear();
818}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819
John McCall4124c492011-10-17 18:40:02 +0000820namespace {
821 class UnbridgedCastsSet {
822 struct Entry {
823 Expr **Addr;
824 Expr *Saved;
825 };
826 SmallVector<Entry, 2> Entries;
827
828 public:
829 void save(Sema &S, Expr *&E) {
830 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
831 Entry entry = { &E, E };
832 Entries.push_back(entry);
833 E = S.stripARCUnbridgedCast(E);
834 }
835
836 void restore() {
837 for (SmallVectorImpl<Entry>::iterator
838 i = Entries.begin(), e = Entries.end(); i != e; ++i)
839 *i->Addr = i->Saved;
840 }
841 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000842}
John McCall4124c492011-10-17 18:40:02 +0000843
844/// checkPlaceholderForOverload - Do any interesting placeholder-like
845/// preprocessing on the given expression.
846///
847/// \param unbridgedCasts a collection to which to add unbridged casts;
848/// without this, they will be immediately diagnosed as errors
849///
850/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000851static bool
852checkPlaceholderForOverload(Sema &S, Expr *&E,
853 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000854 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
855 // We can't handle overloaded expressions here because overload
856 // resolution might reasonably tweak them.
857 if (placeholder->getKind() == BuiltinType::Overload) return false;
858
859 // If the context potentially accepts unbridged ARC casts, strip
860 // the unbridged cast and add it to the collection for later restoration.
861 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
862 unbridgedCasts) {
863 unbridgedCasts->save(S, E);
864 return false;
865 }
866
867 // Go ahead and check everything else.
868 ExprResult result = S.CheckPlaceholderExpr(E);
869 if (result.isInvalid())
870 return true;
871
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000872 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000873 return false;
874 }
875
876 // Nothing to do.
877 return false;
878}
879
880/// checkArgPlaceholdersForOverload - Check a set of call operands for
881/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000882static bool checkArgPlaceholdersForOverload(Sema &S,
883 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000884 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000885 for (unsigned i = 0, e = Args.size(); i != e; ++i)
886 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000887 return true;
888
889 return false;
890}
891
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000892// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000893// overload of the declarations in Old. This routine returns false if
894// New and Old cannot be overloaded, e.g., if New has the same
895// signature as some function in Old (C++ 1.3.10) or if the Old
896// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000897// it does return false, MatchedDecl will point to the decl that New
898// cannot be overloaded with. This decl may be a UsingShadowDecl on
899// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000900//
901// Example: Given the following input:
902//
903// void f(int, float); // #1
904// void f(int, int); // #2
905// int f(int, int); // #3
906//
907// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000908// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000909//
John McCall3d988d92009-12-02 08:47:38 +0000910// When we process #2, Old contains only the FunctionDecl for #1. By
911// comparing the parameter types, we see that #1 and #2 are overloaded
912// (since they have different signatures), so this routine returns
913// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000914//
John McCall3d988d92009-12-02 08:47:38 +0000915// When we process #3, Old is an overload set containing #1 and #2. We
916// compare the signatures of #3 to #1 (they're overloaded, so we do
917// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
918// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000919// signature), IsOverload returns false and MatchedDecl will be set to
920// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000921//
922// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
923// into a class by a using declaration. The rules for whether to hide
924// shadow declarations ignore some properties which otherwise figure
925// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000926Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000927Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
928 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000929 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000930 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000931 NamedDecl *OldD = *I;
932
933 bool OldIsUsingDecl = false;
934 if (isa<UsingShadowDecl>(OldD)) {
935 OldIsUsingDecl = true;
936
937 // We can always introduce two using declarations into the same
938 // context, even if they have identical signatures.
939 if (NewIsUsingDecl) continue;
940
941 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
942 }
943
Richard Smithf091e122015-09-15 01:28:55 +0000944 // A using-declaration does not conflict with another declaration
945 // if one of them is hidden.
946 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
947 continue;
948
John McCalle9cccd82010-06-16 08:42:20 +0000949 // If either declaration was introduced by a using declaration,
950 // we'll need to use slightly different rules for matching.
951 // Essentially, these rules are the normal rules, except that
952 // function templates hide function templates with different
953 // return types or template parameter lists.
954 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000955 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
956 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000957
Alp Tokera2794f92014-01-22 07:29:52 +0000958 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000959 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
960 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
961 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
962 continue;
963 }
964
Alp Tokera2794f92014-01-22 07:29:52 +0000965 if (!isa<FunctionTemplateDecl>(OldD) &&
966 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000967 continue;
968
John McCalldaa3d6b2009-12-09 03:35:25 +0000969 Match = *I;
970 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000971 }
John McCalla8987a2942010-11-10 03:01:53 +0000972 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000973 // We can overload with these, which can show up when doing
974 // redeclaration checks for UsingDecls.
975 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000976 } else if (isa<TagDecl>(OldD)) {
977 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000978 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
979 // Optimistically assume that an unresolved using decl will
980 // overload; if it doesn't, we'll have to diagnose during
981 // template instantiation.
982 } else {
John McCall1f82f242009-11-18 22:49:29 +0000983 // (C++ 13p1):
984 // Only function declarations can be overloaded; object and type
985 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000986 Match = *I;
987 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000988 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000989 }
John McCall1f82f242009-11-18 22:49:29 +0000990
John McCalldaa3d6b2009-12-09 03:35:25 +0000991 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000992}
993
Richard Smithac974a32013-06-30 09:48:50 +0000994bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +0000995 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +0000996 // C++ [basic.start.main]p2: This function shall not be overloaded.
997 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000998 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000999
David Majnemerc729b0b2013-09-16 22:44:20 +00001000 // MSVCRT user defined entry points cannot be overloaded.
1001 if (New->isMSVCRTEntryPoint())
1002 return false;
1003
John McCall1f82f242009-11-18 22:49:29 +00001004 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1005 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1006
1007 // C++ [temp.fct]p2:
1008 // A function template can be overloaded with other function templates
1009 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001010 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001011 return true;
1012
1013 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001014 QualType OldQType = Context.getCanonicalType(Old->getType());
1015 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001016
1017 // Compare the signatures (C++ 1.3.10) of the two functions to
1018 // determine whether they are overloads. If we find any mismatch
1019 // in the signature, they are overloads.
1020
1021 // If either of these functions is a K&R-style function (no
1022 // prototype), then we consider them to have matching signatures.
1023 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1024 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1025 return false;
1026
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001027 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1028 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001029
1030 // The signature of a function includes the types of its
1031 // parameters (C++ 1.3.10), which includes the presence or absence
1032 // of the ellipsis; see C++ DR 357).
1033 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001034 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001035 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001036 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001037 return true;
1038
1039 // C++ [temp.over.link]p4:
1040 // The signature of a function template consists of its function
1041 // signature, its return type and its template parameter list. The names
1042 // of the template parameters are significant only for establishing the
1043 // relationship between the template parameters and the rest of the
1044 // signature.
1045 //
1046 // We check the return type and template parameter lists for function
1047 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001048 //
1049 // However, we don't consider either of these when deciding whether
1050 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001051 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001052 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1053 OldTemplate->getTemplateParameters(),
1054 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001055 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001056 return true;
1057
1058 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001059 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001060 //
1061 // As part of this, also check whether one of the member functions
1062 // is static, in which case they are not overloads (C++
1063 // 13.1p2). While not part of the definition of the signature,
1064 // this check is important to determine whether these functions
1065 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001066 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1067 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001068 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001069 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1070 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001071 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001072 (OldMethod->getRefQualifier() == RQ_None ||
1073 NewMethod->getRefQualifier() == RQ_None)) {
1074 // C++0x [over.load]p2:
1075 // - Member function declarations with the same name and the same
1076 // parameter-type-list as well as member function template
1077 // declarations with the same name, the same parameter-type-list, and
1078 // the same template parameter lists cannot be overloaded if any of
1079 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001080 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001081 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001082 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001083 }
1084 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
Richard Smith574f4f62013-01-14 05:37:29 +00001087 // We may not have applied the implicit const for a constexpr member
1088 // function yet (because we haven't yet resolved whether this is a static
1089 // or non-static member function). Add it now, on the assumption that this
1090 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001091 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001092 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001093 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001094 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001095 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001096
1097 // We do not allow overloading based off of '__restrict'.
1098 OldQuals &= ~Qualifiers::Restrict;
1099 NewQuals &= ~Qualifiers::Restrict;
1100 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001101 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001103
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001104 // Though pass_object_size is placed on parameters and takes an argument, we
1105 // consider it to be a function-level modifier for the sake of function
1106 // identity. Either the function has one or more parameters with
1107 // pass_object_size or it doesn't.
1108 if (functionHasPassObjectSizeParams(New) !=
1109 functionHasPassObjectSizeParams(Old))
1110 return true;
1111
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001112 // enable_if attributes are an order-sensitive part of the signature.
1113 for (specific_attr_iterator<EnableIfAttr>
1114 NewI = New->specific_attr_begin<EnableIfAttr>(),
1115 NewE = New->specific_attr_end<EnableIfAttr>(),
1116 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1117 OldE = Old->specific_attr_end<EnableIfAttr>();
1118 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1119 if (NewI == NewE || OldI == OldE)
1120 return true;
1121 llvm::FoldingSetNodeID NewID, OldID;
1122 NewI->getCond()->Profile(NewID, Context, true);
1123 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001124 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001125 return true;
1126 }
1127
Justin Lebarba122ab2016-03-30 23:30:21 +00001128 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Artem Belevich94a55e82015-09-22 17:22:59 +00001129 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1130 OldTarget = IdentifyCUDATarget(Old);
1131 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1132 return false;
1133
1134 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1135
1136 // Don't allow mixing of HD with other kinds. This guarantees that
1137 // we have only one viable function with this signature on any
1138 // side of CUDA compilation .
Artem Belevich1ef9b592016-02-24 21:54:45 +00001139 // __global__ functions can't be overloaded based on attribute
1140 // difference because, like HD, they also exist on both sides.
1141 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1142 (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
Artem Belevich94a55e82015-09-22 17:22:59 +00001143 return false;
1144
1145 // Allow overloading of functions with same signature, but
1146 // different CUDA target attributes.
1147 return NewTarget != OldTarget;
1148 }
1149
John McCall1f82f242009-11-18 22:49:29 +00001150 // The signatures match; this is not an overload.
1151 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152}
1153
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001154/// \brief Checks availability of the function depending on the current
1155/// function context. Inside an unavailable function, unavailability is ignored.
1156///
1157/// \returns true if \arg FD is unavailable and current context is inside
1158/// an available function, false otherwise.
1159bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001160 if (!FD->isUnavailable())
1161 return false;
1162
1163 // Walk up the context of the caller.
1164 Decl *C = cast<Decl>(CurContext);
1165 do {
1166 if (C->isUnavailable())
1167 return false;
1168 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1169 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001170}
1171
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001172/// \brief Tries a user-defined conversion from From to ToType.
1173///
1174/// Produces an implicit conversion sequence for when a standard conversion
1175/// is not an option. See TryImplicitConversion for more information.
1176static ImplicitConversionSequence
1177TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1178 bool SuppressUserConversions,
1179 bool AllowExplicit,
1180 bool InOverloadResolution,
1181 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001182 bool AllowObjCWritebackConversion,
1183 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001184 ImplicitConversionSequence ICS;
1185
1186 if (SuppressUserConversions) {
1187 // We're not in the case above, so there is no conversion that
1188 // we can perform.
1189 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1190 return ICS;
1191 }
1192
1193 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001194 OverloadCandidateSet Conversions(From->getExprLoc(),
1195 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001196 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1197 Conversions, AllowExplicit,
1198 AllowObjCConversionOnExplicit)) {
1199 case OR_Success:
1200 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001201 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001202 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001203 // C++ [over.ics.user]p4:
1204 // A conversion of an expression of class type to the same class
1205 // type is given Exact Match rank, and a conversion of an
1206 // expression of class type to a base class of that type is
1207 // given Conversion rank, in spite of the fact that a copy
1208 // constructor (i.e., a user-defined conversion function) is
1209 // called for those cases.
1210 if (CXXConstructorDecl *Constructor
1211 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1212 QualType FromCanon
1213 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1214 QualType ToCanon
1215 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1216 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001217 (FromCanon == ToCanon ||
1218 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001219 // Turn this into a "standard" conversion sequence, so that it
1220 // gets ranked with standard conversion sequences.
1221 ICS.setStandard();
1222 ICS.Standard.setAsIdentityConversion();
1223 ICS.Standard.setFromType(From->getType());
1224 ICS.Standard.setAllToTypes(ToType);
1225 ICS.Standard.CopyConstructor = Constructor;
1226 if (ToCanon != FromCanon)
1227 ICS.Standard.Second = ICK_Derived_To_Base;
1228 }
1229 }
Richard Smith48372b62015-01-27 03:30:40 +00001230 break;
1231
1232 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001233 ICS.setAmbiguous();
1234 ICS.Ambiguous.setFromType(From->getType());
1235 ICS.Ambiguous.setToType(ToType);
1236 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1237 Cand != Conversions.end(); ++Cand)
1238 if (Cand->Viable)
1239 ICS.Ambiguous.addConversion(Cand->Function);
1240 break;
Richard Smith48372b62015-01-27 03:30:40 +00001241
1242 // Fall through.
1243 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001244 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001245 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001246 }
1247
1248 return ICS;
1249}
1250
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001251/// TryImplicitConversion - Attempt to perform an implicit conversion
1252/// from the given expression (Expr) to the given type (ToType). This
1253/// function returns an implicit conversion sequence that can be used
1254/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001255///
1256/// void f(float f);
1257/// void g(int i) { f(i); }
1258///
1259/// this routine would produce an implicit conversion sequence to
1260/// describe the initialization of f from i, which will be a standard
1261/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1262/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1263//
1264/// Note that this routine only determines how the conversion can be
1265/// performed; it does not actually perform the conversion. As such,
1266/// it will not produce any diagnostics if no conversion is available,
1267/// but will instead return an implicit conversion sequence of kind
1268/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001269///
1270/// If @p SuppressUserConversions, then user-defined conversions are
1271/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001272/// If @p AllowExplicit, then explicit user-defined conversions are
1273/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001274///
1275/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1276/// writeback conversion, which allows __autoreleasing id* parameters to
1277/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001278static ImplicitConversionSequence
1279TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1280 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001282 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001283 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001284 bool AllowObjCWritebackConversion,
1285 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001286 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001287 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001288 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001289 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001290 return ICS;
1291 }
1292
David Blaikiebbafb8a2012-03-11 07:00:24 +00001293 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001294 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001295 return ICS;
1296 }
1297
Douglas Gregor836a7e82010-08-11 02:15:33 +00001298 // C++ [over.ics.user]p4:
1299 // A conversion of an expression of class type to the same class
1300 // type is given Exact Match rank, and a conversion of an
1301 // expression of class type to a base class of that type is
1302 // given Conversion rank, in spite of the fact that a copy/move
1303 // constructor (i.e., a user-defined conversion function) is
1304 // called for those cases.
1305 QualType FromType = From->getType();
1306 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001307 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001308 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001309 ICS.setStandard();
1310 ICS.Standard.setAsIdentityConversion();
1311 ICS.Standard.setFromType(FromType);
1312 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313
Douglas Gregor5ab11652010-04-17 22:01:05 +00001314 // We don't actually check at this point whether there is a valid
1315 // copy/move constructor, since overloading just assumes that it
1316 // exists. When we actually perform initialization, we'll find the
1317 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001318 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319
Douglas Gregor5ab11652010-04-17 22:01:05 +00001320 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001321 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001322 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001323
Douglas Gregor836a7e82010-08-11 02:15:33 +00001324 return ICS;
1325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001326
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001327 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1328 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001329 AllowObjCWritebackConversion,
1330 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001331}
1332
John McCall31168b02011-06-15 23:02:42 +00001333ImplicitConversionSequence
1334Sema::TryImplicitConversion(Expr *From, QualType ToType,
1335 bool SuppressUserConversions,
1336 bool AllowExplicit,
1337 bool InOverloadResolution,
1338 bool CStyle,
1339 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001340 return ::TryImplicitConversion(*this, From, ToType,
1341 SuppressUserConversions, AllowExplicit,
1342 InOverloadResolution, CStyle,
1343 AllowObjCWritebackConversion,
1344 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001345}
1346
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001347/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001348/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001349/// converted expression. Flavor is the kind of conversion we're
1350/// performing, used in the error message. If @p AllowExplicit,
1351/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001352ExprResult
1353Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001354 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001355 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001356 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001357}
1358
John Wiegley01296292011-04-08 18:41:53 +00001359ExprResult
1360Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001361 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001362 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001363 if (checkPlaceholderForOverload(*this, From))
1364 return ExprError();
1365
John McCall31168b02011-06-15 23:02:42 +00001366 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1367 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001368 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001369 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001370 if (getLangOpts().ObjC1)
1371 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1372 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001373 ICS = ::TryImplicitConversion(*this, From, ToType,
1374 /*SuppressUserConversions=*/false,
1375 AllowExplicit,
1376 /*InOverloadResolution=*/false,
1377 /*CStyle=*/false,
1378 AllowObjCWritebackConversion,
1379 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001380 return PerformImplicitConversion(From, ToType, ICS, Action);
1381}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382
1383/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001384/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001385bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1386 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001387 if (Context.hasSameUnqualifiedType(FromType, ToType))
1388 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389
John McCall991eb4b2010-12-21 00:44:39 +00001390 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1391 // where F adds one of the following at most once:
1392 // - a pointer
1393 // - a member pointer
1394 // - a block pointer
1395 CanQualType CanTo = Context.getCanonicalType(ToType);
1396 CanQualType CanFrom = Context.getCanonicalType(FromType);
1397 Type::TypeClass TyClass = CanTo->getTypeClass();
1398 if (TyClass != CanFrom->getTypeClass()) return false;
1399 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1400 if (TyClass == Type::Pointer) {
1401 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1402 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1403 } else if (TyClass == Type::BlockPointer) {
1404 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1405 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1406 } else if (TyClass == Type::MemberPointer) {
1407 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1408 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1409 } else {
1410 return false;
1411 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001412
John McCall991eb4b2010-12-21 00:44:39 +00001413 TyClass = CanTo->getTypeClass();
1414 if (TyClass != CanFrom->getTypeClass()) return false;
1415 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1416 return false;
1417 }
1418
1419 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1420 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1421 if (!EInfo.getNoReturn()) return false;
1422
1423 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1424 assert(QualType(FromFn, 0).isCanonical());
1425 if (QualType(FromFn, 0) != CanTo) return false;
1426
1427 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001428 return true;
1429}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430
Douglas Gregor46188682010-05-18 22:42:18 +00001431/// \brief Determine whether the conversion from FromType to ToType is a valid
1432/// vector conversion.
1433///
1434/// \param ICK Will be set to the vector conversion kind, if this is a vector
1435/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001436static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001437 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001438 // We need at least one of these types to be a vector type to have a vector
1439 // conversion.
1440 if (!ToType->isVectorType() && !FromType->isVectorType())
1441 return false;
1442
1443 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001444 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001445 return false;
1446
1447 // There are no conversions between extended vector types, only identity.
1448 if (ToType->isExtVectorType()) {
1449 // There are no conversions between extended vector types other than the
1450 // identity conversion.
1451 if (FromType->isExtVectorType())
1452 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001453
Douglas Gregor46188682010-05-18 22:42:18 +00001454 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001455 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001456 ICK = ICK_Vector_Splat;
1457 return true;
1458 }
1459 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001460
1461 // We can perform the conversion between vector types in the following cases:
1462 // 1)vector types are equivalent AltiVec and GCC vector types
1463 // 2)lax vector conversions are permitted and the vector types are of the
1464 // same size
1465 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001466 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1467 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001468 ICK = ICK_Vector_Conversion;
1469 return true;
1470 }
Douglas Gregor46188682010-05-18 22:42:18 +00001471 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001472
Douglas Gregor46188682010-05-18 22:42:18 +00001473 return false;
1474}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001476static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1477 bool InOverloadResolution,
1478 StandardConversionSequence &SCS,
1479 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001480
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001481/// IsStandardConversion - Determines whether there is a standard
1482/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1483/// expression From to the type ToType. Standard conversion sequences
1484/// only consider non-class types; for conversions that involve class
1485/// types, use TryImplicitConversion. If a conversion exists, SCS will
1486/// contain the standard conversion sequence required to perform this
1487/// conversion and this routine will return true. Otherwise, this
1488/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001489static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1490 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001491 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001492 bool CStyle,
1493 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001494 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001497 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001498 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001499 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001500 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001502 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001503 // abort early. When overloading in C, however, we do permit them.
1504 if (S.getLangOpts().CPlusPlus &&
1505 (FromType->isRecordType() || ToType->isRecordType()))
1506 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001507
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001508 // The first conversion can be an lvalue-to-rvalue conversion,
1509 // array-to-pointer conversion, or function-to-pointer conversion
1510 // (C++ 4p1).
1511
John McCall5c32be02010-08-24 20:38:10 +00001512 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001513 DeclAccessPair AccessPair;
1514 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001515 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001516 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001517 // We were able to resolve the address of the overloaded function,
1518 // so we can convert to the type of that function.
1519 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001520 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001521
1522 // we can sometimes resolve &foo<int> regardless of ToType, so check
1523 // if the type matches (identity) or we are converting to bool
1524 if (!S.Context.hasSameUnqualifiedType(
1525 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1526 QualType resultTy;
1527 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001528 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001529 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1530 // otherwise, only a boolean conversion is standard
1531 if (!ToType->isBooleanType())
1532 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534
Chandler Carruthffce2452011-03-29 08:08:18 +00001535 // Check if the "from" expression is taking the address of an overloaded
1536 // function and recompute the FromType accordingly. Take advantage of the
1537 // fact that non-static member functions *must* have such an address-of
1538 // expression.
1539 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1540 if (Method && !Method->isStatic()) {
1541 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1542 "Non-unary operator on non-static member address");
1543 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1544 == UO_AddrOf &&
1545 "Non-address-of operator on non-static member address");
1546 const Type *ClassType
1547 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1548 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001549 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1550 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1551 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001552 "Non-address-of operator for overloaded function expression");
1553 FromType = S.Context.getPointerType(FromType);
1554 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555
Douglas Gregor980fb162010-04-29 18:24:40 +00001556 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001557 assert(S.Context.hasSameType(
1558 FromType,
1559 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001560 } else {
1561 return false;
1562 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001563 }
John McCall154a2fd2011-08-30 00:57:29 +00001564 // Lvalue-to-rvalue conversion (C++11 4.1):
1565 // A glvalue (3.10) of a non-function, non-array type T can
1566 // be converted to a prvalue.
1567 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001568 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001569 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001570 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001571 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572
Douglas Gregorc79862f2012-04-12 17:51:55 +00001573 // C11 6.3.2.1p2:
1574 // ... if the lvalue has atomic type, the value has the non-atomic version
1575 // of the type of the lvalue ...
1576 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1577 FromType = Atomic->getValueType();
1578
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001579 // If T is a non-class type, the type of the rvalue is the
1580 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001581 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1582 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001584 } else if (FromType->isArrayType()) {
1585 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587
1588 // An lvalue or rvalue of type "array of N T" or "array of unknown
1589 // bound of T" can be converted to an rvalue of type "pointer to
1590 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001591 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001592
John McCall5c32be02010-08-24 20:38:10 +00001593 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001594 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001595 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001596
1597 // For the purpose of ranking in overload resolution
1598 // (13.3.3.1.1), this conversion is considered an
1599 // array-to-pointer conversion followed by a qualification
1600 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001601 SCS.Second = ICK_Identity;
1602 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001603 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001604 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001605 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001606 }
John McCall086a4642010-11-24 05:12:34 +00001607 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001608 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001609 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001610
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001611 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1612 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1613 if (!S.checkAddressOfFunctionIsAvailable(FD))
1614 return false;
1615
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001616 // An lvalue of function type T can be converted to an rvalue of
1617 // type "pointer to T." The result is a pointer to the
1618 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001619 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001620 } else {
1621 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001622 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001623 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001624 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001625
1626 // The second conversion can be an integral promotion, floating
1627 // point promotion, integral conversion, floating point conversion,
1628 // floating-integral conversion, pointer conversion,
1629 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001630 // For overloading in C, this can also be a "compatible-type"
1631 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001632 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001633 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001634 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001635 // The unqualified versions of the types are the same: there's no
1636 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001637 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001638 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001639 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001640 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001641 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001642 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001643 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001644 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001645 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001646 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001647 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001648 SCS.Second = ICK_Complex_Promotion;
1649 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001650 } else if (ToType->isBooleanType() &&
1651 (FromType->isArithmeticType() ||
1652 FromType->isAnyPointerType() ||
1653 FromType->isBlockPointerType() ||
1654 FromType->isMemberPointerType() ||
1655 FromType->isNullPtrType())) {
1656 // Boolean conversions (C++ 4.12).
1657 SCS.Second = ICK_Boolean_Conversion;
1658 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001659 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001660 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001661 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001662 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001664 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001665 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001666 SCS.Second = ICK_Complex_Conversion;
1667 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001668 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1669 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001670 // Complex-real conversions (C99 6.3.1.7)
1671 SCS.Second = ICK_Complex_Real;
1672 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001673 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001674 // Floating point conversions (C++ 4.8).
1675 SCS.Second = ICK_Floating_Conversion;
1676 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001677 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001678 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001679 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001680 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001681 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001682 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001684 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001685 SCS.Second = ICK_Block_Pointer_Conversion;
1686 } else if (AllowObjCWritebackConversion &&
1687 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1688 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001689 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1690 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001691 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001692 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001693 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001694 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001695 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001696 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001697 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001698 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001699 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001700 SCS.Second = SecondICK;
1701 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001702 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001703 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001704 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001705 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001706 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001707 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001708 // Treat a conversion that strips "noreturn" as an identity conversion.
1709 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001710 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1711 InOverloadResolution,
1712 SCS, CStyle)) {
1713 SCS.Second = ICK_TransparentUnionConversion;
1714 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001715 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1716 CStyle)) {
1717 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001718 // appropriately.
1719 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001720 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001721 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001722 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001723 SCS.Second = ICK_Zero_Event_Conversion;
1724 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001725 } else {
1726 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001727 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001728 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001729 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001731 QualType CanonFrom;
1732 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001733 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001734 bool ObjCLifetimeConversion;
1735 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1736 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001737 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001738 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001740 CanonFrom = S.Context.getCanonicalType(FromType);
1741 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001742 } else {
1743 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001744 SCS.Third = ICK_Identity;
1745
Mike Stump11289f42009-09-09 15:08:12 +00001746 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001747 // [...] Any difference in top-level cv-qualification is
1748 // subsumed by the initialization itself and does not constitute
1749 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001750 CanonFrom = S.Context.getCanonicalType(FromType);
1751 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001752 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001753 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001754 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001755 FromType = ToType;
1756 CanonFrom = CanonTo;
1757 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001759 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001760
George Burgess IV45461812015-10-11 20:13:20 +00001761 if (CanonFrom == CanonTo)
1762 return true;
1763
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001764 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001765 // this is a bad conversion sequence, unless we're resolving an overload in C.
1766 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001767 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001768
George Burgess IV45461812015-10-11 20:13:20 +00001769 ExprResult ER = ExprResult{From};
1770 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1771 /*Diagnose=*/false,
1772 /*DiagnoseCFAudited=*/false,
1773 /*ConvertRHS=*/false);
1774 if (Conv != Sema::Compatible)
1775 return false;
1776
1777 SCS.setAllToTypes(ToType);
1778 // We need to set all three because we want this conversion to rank terribly,
1779 // and we don't know what conversions it may overlap with.
1780 SCS.First = ICK_C_Only_Conversion;
1781 SCS.Second = ICK_C_Only_Conversion;
1782 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001783 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001784}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001785
1786static bool
1787IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1788 QualType &ToType,
1789 bool InOverloadResolution,
1790 StandardConversionSequence &SCS,
1791 bool CStyle) {
1792
1793 const RecordType *UT = ToType->getAsUnionType();
1794 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1795 return false;
1796 // The field to initialize within the transparent union.
1797 RecordDecl *UD = UT->getDecl();
1798 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001799 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001800 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1801 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001802 ToType = it->getType();
1803 return true;
1804 }
1805 }
1806 return false;
1807}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808
1809/// IsIntegralPromotion - Determines whether the conversion from the
1810/// expression From (whose potentially-adjusted type is FromType) to
1811/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1812/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001813bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001814 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001815 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001816 if (!To) {
1817 return false;
1818 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001819
1820 // An rvalue of type char, signed char, unsigned char, short int, or
1821 // unsigned short int can be converted to an rvalue of type int if
1822 // int can represent all the values of the source type; otherwise,
1823 // the source rvalue can be converted to an rvalue of type unsigned
1824 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001825 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1826 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001827 if (// We can promote any signed, promotable integer type to an int
1828 (FromType->isSignedIntegerType() ||
1829 // We can promote any unsigned integer type whose size is
1830 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001831 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001832 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001834 }
1835
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001836 return To->getKind() == BuiltinType::UInt;
1837 }
1838
Richard Smithb9c5a602012-09-13 21:18:54 +00001839 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840 // A prvalue of an unscoped enumeration type whose underlying type is not
1841 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1842 // following types that can represent all the values of the enumeration
1843 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1844 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001845 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001847 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001848 // with lowest integer conversion rank (4.13) greater than the rank of long
1849 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001850 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001851 // C++11 [conv.prom]p4:
1852 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1853 // can be converted to a prvalue of its underlying type. Moreover, if
1854 // integral promotion can be applied to its underlying type, a prvalue of an
1855 // unscoped enumeration type whose underlying type is fixed can also be
1856 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001857 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1858 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1859 // provided for a scoped enumeration.
1860 if (FromEnumType->getDecl()->isScoped())
1861 return false;
1862
Richard Smithb9c5a602012-09-13 21:18:54 +00001863 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001864 // even if that's not the promoted type. Note that the check for promoting
1865 // the underlying type is based on the type alone, and does not consider
1866 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001867 if (FromEnumType->getDecl()->isFixed()) {
1868 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1869 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001870 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001871 }
1872
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001873 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001875 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001876 return Context.hasSameUnqualifiedType(
1877 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001878 }
John McCall56774992009-12-09 09:09:27 +00001879
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001880 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1882 // to an rvalue a prvalue of the first of the following types that can
1883 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001884 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001886 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001888 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001889 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001890 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001891 // Determine whether the type we're converting from is signed or
1892 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001893 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001894 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001896 // The types we'll try to promote to, in the appropriate
1897 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001898 QualType PromoteTypes[6] = {
1899 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001900 Context.LongTy, Context.UnsignedLongTy ,
1901 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001902 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001903 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001904 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1905 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001906 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001907 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1908 // We found the type that we can promote to. If this is the
1909 // type we wanted, we have a promotion. Otherwise, no
1910 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001911 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001912 }
1913 }
1914 }
1915
1916 // An rvalue for an integral bit-field (9.6) can be converted to an
1917 // rvalue of type int if int can represent all the values of the
1918 // bit-field; otherwise, it can be converted to unsigned int if
1919 // unsigned int can represent all the values of the bit-field. If
1920 // the bit-field is larger yet, no integral promotion applies to
1921 // it. If the bit-field has an enumerated type, it is treated as any
1922 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001923 // FIXME: We should delay checking of bit-fields until we actually perform the
1924 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001925 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001926 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001927 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001928 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001929 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001930 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001931 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001932
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001933 // Are we promoting to an int from a bitfield that fits in an int?
1934 if (BitWidth < ToSize ||
1935 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1936 return To->getKind() == BuiltinType::Int;
1937 }
Mike Stump11289f42009-09-09 15:08:12 +00001938
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001939 // Are we promoting to an unsigned int from an unsigned bitfield
1940 // that fits into an unsigned int?
1941 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1942 return To->getKind() == BuiltinType::UInt;
1943 }
Mike Stump11289f42009-09-09 15:08:12 +00001944
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001945 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001946 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001947 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001948 }
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950 // An rvalue of type bool can be converted to an rvalue of type int,
1951 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001952 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001953 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001954 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001955
1956 return false;
1957}
1958
1959/// IsFloatingPointPromotion - Determines whether the conversion from
1960/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1961/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001962bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001963 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1964 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001965 /// An rvalue of type float can be converted to an rvalue of type
1966 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001967 if (FromBuiltin->getKind() == BuiltinType::Float &&
1968 ToBuiltin->getKind() == BuiltinType::Double)
1969 return true;
1970
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001971 // C99 6.3.1.5p1:
1972 // When a float is promoted to double or long double, or a
1973 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001974 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001975 (FromBuiltin->getKind() == BuiltinType::Float ||
1976 FromBuiltin->getKind() == BuiltinType::Double) &&
1977 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1978 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001979
1980 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001981 if (!getLangOpts().NativeHalfType &&
1982 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001983 ToBuiltin->getKind() == BuiltinType::Float)
1984 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001985 }
1986
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001987 return false;
1988}
1989
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001990/// \brief Determine if a conversion is a complex promotion.
1991///
1992/// A complex promotion is defined as a complex -> complex conversion
1993/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001994/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001995bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001996 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001997 if (!FromComplex)
1998 return false;
1999
John McCall9dd450b2009-09-21 23:43:11 +00002000 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002001 if (!ToComplex)
2002 return false;
2003
2004 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002005 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002006 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002007 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002008}
2009
Douglas Gregor237f96c2008-11-26 23:31:11 +00002010/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2011/// the pointer type FromPtr to a pointer to type ToPointee, with the
2012/// same type qualifiers as FromPtr has on its pointee type. ToType,
2013/// if non-empty, will be a pointer to ToType that may or may not have
2014/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002015///
Mike Stump11289f42009-09-09 15:08:12 +00002016static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002017BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002018 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002019 ASTContext &Context,
2020 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002021 assert((FromPtr->getTypeClass() == Type::Pointer ||
2022 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2023 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024
John McCall31168b02011-06-15 23:02:42 +00002025 /// Conversions to 'id' subsume cv-qualifier conversions.
2026 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002027 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028
2029 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002030 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002031 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002032 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002033
John McCall31168b02011-06-15 23:02:42 +00002034 if (StripObjCLifetime)
2035 Quals.removeObjCLifetime();
2036
Mike Stump11289f42009-09-09 15:08:12 +00002037 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002038 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002039 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002040 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002041 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002042
2043 // Build a pointer to ToPointee. It has the right qualifiers
2044 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002045 if (isa<ObjCObjectPointerType>(ToType))
2046 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002047 return Context.getPointerType(ToPointee);
2048 }
2049
2050 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002051 QualType QualifiedCanonToPointee
2052 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002053
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002054 if (isa<ObjCObjectPointerType>(ToType))
2055 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2056 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002057}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002058
Mike Stump11289f42009-09-09 15:08:12 +00002059static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002060 bool InOverloadResolution,
2061 ASTContext &Context) {
2062 // Handle value-dependent integral null pointer constants correctly.
2063 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2064 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002065 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002066 return !InOverloadResolution;
2067
Douglas Gregor56751b52009-09-25 04:25:58 +00002068 return Expr->isNullPointerConstant(Context,
2069 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2070 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002071}
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002073/// IsPointerConversion - Determines whether the conversion of the
2074/// expression From, which has the (possibly adjusted) type FromType,
2075/// can be converted to the type ToType via a pointer conversion (C++
2076/// 4.10). If so, returns true and places the converted type (that
2077/// might differ from ToType in its cv-qualifiers at some level) into
2078/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002079///
Douglas Gregora29dc052008-11-27 01:19:21 +00002080/// This routine also supports conversions to and from block pointers
2081/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2082/// pointers to interfaces. FIXME: Once we've determined the
2083/// appropriate overloading rules for Objective-C, we may want to
2084/// split the Objective-C checks into a different routine; however,
2085/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002086/// conversions, so for now they live here. IncompatibleObjC will be
2087/// set if the conversion is an allowed Objective-C conversion that
2088/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002089bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002090 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002091 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002092 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002093 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002094 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2095 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002096 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002097
Mike Stump11289f42009-09-09 15:08:12 +00002098 // Conversion from a null pointer constant to any Objective-C pointer type.
2099 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002100 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002101 ConvertedType = ToType;
2102 return true;
2103 }
2104
Douglas Gregor231d1c62008-11-27 00:15:41 +00002105 // Blocks: Block pointers can be converted to void*.
2106 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002107 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002108 ConvertedType = ToType;
2109 return true;
2110 }
2111 // Blocks: A null pointer constant can be converted to a block
2112 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002113 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002114 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002115 ConvertedType = ToType;
2116 return true;
2117 }
2118
Sebastian Redl576fd422009-05-10 18:38:11 +00002119 // If the left-hand-side is nullptr_t, the right side can be a null
2120 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002121 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002122 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002123 ConvertedType = ToType;
2124 return true;
2125 }
2126
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002127 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002128 if (!ToTypePtr)
2129 return false;
2130
2131 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002132 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002133 ConvertedType = ToType;
2134 return true;
2135 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002136
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002138 // , including objective-c pointers.
2139 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002140 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002141 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002142 ConvertedType = BuildSimilarlyQualifiedPointerType(
2143 FromType->getAs<ObjCObjectPointerType>(),
2144 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002145 ToType, Context);
2146 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002147 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002148 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002149 if (!FromTypePtr)
2150 return false;
2151
2152 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002153
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002155 // pointer conversion, so don't do all of the work below.
2156 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2157 return false;
2158
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002159 // An rvalue of type "pointer to cv T," where T is an object type,
2160 // can be converted to an rvalue of type "pointer to cv void" (C++
2161 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002162 if (FromPointeeType->isIncompleteOrObjectType() &&
2163 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002164 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002165 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002166 ToType, Context,
2167 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002168 return true;
2169 }
2170
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002171 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002172 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002173 ToPointeeType->isVoidType()) {
2174 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2175 ToPointeeType,
2176 ToType, Context);
2177 return true;
2178 }
2179
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002180 // When we're overloading in C, we allow a special kind of pointer
2181 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002182 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002183 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002184 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002185 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002186 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002187 return true;
2188 }
2189
Douglas Gregor5c407d92008-10-23 00:40:37 +00002190 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002191 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002192 // An rvalue of type "pointer to cv D," where D is a class type,
2193 // can be converted to an rvalue of type "pointer to cv B," where
2194 // B is a base class (clause 10) of D. If B is an inaccessible
2195 // (clause 11) or ambiguous (10.2) base class of D, a program that
2196 // necessitates this conversion is ill-formed. The result of the
2197 // conversion is a pointer to the base class sub-object of the
2198 // derived class object. The null pointer value is converted to
2199 // the null pointer value of the destination type.
2200 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002201 // Note that we do not check for ambiguity or inaccessibility
2202 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002203 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002204 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002205 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002206 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002208 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002209 ToType, Context);
2210 return true;
2211 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002212
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002213 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2214 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2215 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2216 ToPointeeType,
2217 ToType, Context);
2218 return true;
2219 }
2220
Douglas Gregora119f102008-12-19 19:13:09 +00002221 return false;
2222}
Douglas Gregoraec25842011-04-26 23:16:46 +00002223
2224/// \brief Adopt the given qualifiers for the given type.
2225static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2226 Qualifiers TQs = T.getQualifiers();
2227
2228 // Check whether qualifiers already match.
2229 if (TQs == Qs)
2230 return T;
2231
2232 if (Qs.compatiblyIncludes(TQs))
2233 return Context.getQualifiedType(T, Qs);
2234
2235 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2236}
Douglas Gregora119f102008-12-19 19:13:09 +00002237
2238/// isObjCPointerConversion - Determines whether this is an
2239/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2240/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002241bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002242 QualType& ConvertedType,
2243 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002244 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002245 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002246
Douglas Gregoraec25842011-04-26 23:16:46 +00002247 // The set of qualifiers on the type we're converting from.
2248 Qualifiers FromQualifiers = FromType.getQualifiers();
2249
Steve Naroff7cae42b2009-07-10 23:34:53 +00002250 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002251 const ObjCObjectPointerType* ToObjCPtr =
2252 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002253 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002254 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002255
Steve Naroff7cae42b2009-07-10 23:34:53 +00002256 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002257 // If the pointee types are the same (ignoring qualifications),
2258 // then this is not a pointer conversion.
2259 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2260 FromObjCPtr->getPointeeType()))
2261 return false;
2262
Douglas Gregorab209d82015-07-07 03:58:42 +00002263 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002264 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002265 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2266 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002267 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002268 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2269 FromObjCPtr->getPointeeType()))
2270 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002271 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002272 ToObjCPtr->getPointeeType(),
2273 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002274 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002275 return true;
2276 }
2277
2278 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2279 // Okay: this is some kind of implicit downcast of Objective-C
2280 // interfaces, which is permitted. However, we're going to
2281 // complain about it.
2282 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002283 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002284 ToObjCPtr->getPointeeType(),
2285 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002286 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002287 return true;
2288 }
Mike Stump11289f42009-09-09 15:08:12 +00002289 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002290 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002291 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002292 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002293 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002294 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002295 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002296 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002297 // to a block pointer type.
2298 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002299 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002300 return true;
2301 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002302 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002305 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002306 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002307 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002308 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002309 return true;
2310 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002311 else
Douglas Gregora119f102008-12-19 19:13:09 +00002312 return false;
2313
Douglas Gregor033f56d2008-12-23 00:53:59 +00002314 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002315 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002316 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002317 else if (const BlockPointerType *FromBlockPtr =
2318 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002319 FromPointeeType = FromBlockPtr->getPointeeType();
2320 else
Douglas Gregora119f102008-12-19 19:13:09 +00002321 return false;
2322
Douglas Gregora119f102008-12-19 19:13:09 +00002323 // If we have pointers to pointers, recursively check whether this
2324 // is an Objective-C conversion.
2325 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2326 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2327 IncompatibleObjC)) {
2328 // We always complain about this conversion.
2329 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002330 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002331 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002332 return true;
2333 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002334 // Allow conversion of pointee being objective-c pointer to another one;
2335 // as in I* to id.
2336 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2337 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2338 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2339 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002340
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002341 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002342 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002343 return true;
2344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002345
Douglas Gregor033f56d2008-12-23 00:53:59 +00002346 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002347 // differences in the argument and result types are in Objective-C
2348 // pointer conversions. If so, we permit the conversion (but
2349 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002350 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002351 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002352 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002353 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002354 if (FromFunctionType && ToFunctionType) {
2355 // If the function types are exactly the same, this isn't an
2356 // Objective-C pointer conversion.
2357 if (Context.getCanonicalType(FromPointeeType)
2358 == Context.getCanonicalType(ToPointeeType))
2359 return false;
2360
2361 // Perform the quick checks that will tell us whether these
2362 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002363 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002364 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2365 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2366 return false;
2367
2368 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002369 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2370 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002371 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002372 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2373 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002374 ConvertedType, IncompatibleObjC)) {
2375 // Okay, we have an Objective-C pointer conversion.
2376 HasObjCConversion = true;
2377 } else {
2378 // Function types are too different. Abort.
2379 return false;
2380 }
Mike Stump11289f42009-09-09 15:08:12 +00002381
Douglas Gregora119f102008-12-19 19:13:09 +00002382 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002383 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002384 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002385 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2386 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002387 if (Context.getCanonicalType(FromArgType)
2388 == Context.getCanonicalType(ToArgType)) {
2389 // Okay, the types match exactly. Nothing to do.
2390 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2391 ConvertedType, IncompatibleObjC)) {
2392 // Okay, we have an Objective-C pointer conversion.
2393 HasObjCConversion = true;
2394 } else {
2395 // Argument types are too different. Abort.
2396 return false;
2397 }
2398 }
2399
2400 if (HasObjCConversion) {
2401 // We had an Objective-C conversion. Allow this pointer
2402 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002403 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002404 IncompatibleObjC = true;
2405 return true;
2406 }
2407 }
2408
Sebastian Redl72b597d2009-01-25 19:43:20 +00002409 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002410}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002411
John McCall31168b02011-06-15 23:02:42 +00002412/// \brief Determine whether this is an Objective-C writeback conversion,
2413/// used for parameter passing when performing automatic reference counting.
2414///
2415/// \param FromType The type we're converting form.
2416///
2417/// \param ToType The type we're converting to.
2418///
2419/// \param ConvertedType The type that will be produced after applying
2420/// this conversion.
2421bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2422 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002423 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002424 Context.hasSameUnqualifiedType(FromType, ToType))
2425 return false;
2426
2427 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2428 QualType ToPointee;
2429 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2430 ToPointee = ToPointer->getPointeeType();
2431 else
2432 return false;
2433
2434 Qualifiers ToQuals = ToPointee.getQualifiers();
2435 if (!ToPointee->isObjCLifetimeType() ||
2436 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002437 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002438 return false;
2439
2440 // Argument must be a pointer to __strong to __weak.
2441 QualType FromPointee;
2442 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2443 FromPointee = FromPointer->getPointeeType();
2444 else
2445 return false;
2446
2447 Qualifiers FromQuals = FromPointee.getQualifiers();
2448 if (!FromPointee->isObjCLifetimeType() ||
2449 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2450 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2451 return false;
2452
2453 // Make sure that we have compatible qualifiers.
2454 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2455 if (!ToQuals.compatiblyIncludes(FromQuals))
2456 return false;
2457
2458 // Remove qualifiers from the pointee type we're converting from; they
2459 // aren't used in the compatibility check belong, and we'll be adding back
2460 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2461 FromPointee = FromPointee.getUnqualifiedType();
2462
2463 // The unqualified form of the pointee types must be compatible.
2464 ToPointee = ToPointee.getUnqualifiedType();
2465 bool IncompatibleObjC;
2466 if (Context.typesAreCompatible(FromPointee, ToPointee))
2467 FromPointee = ToPointee;
2468 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2469 IncompatibleObjC))
2470 return false;
2471
2472 /// \brief Construct the type we're converting to, which is a pointer to
2473 /// __autoreleasing pointee.
2474 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2475 ConvertedType = Context.getPointerType(FromPointee);
2476 return true;
2477}
2478
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002479bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2480 QualType& ConvertedType) {
2481 QualType ToPointeeType;
2482 if (const BlockPointerType *ToBlockPtr =
2483 ToType->getAs<BlockPointerType>())
2484 ToPointeeType = ToBlockPtr->getPointeeType();
2485 else
2486 return false;
2487
2488 QualType FromPointeeType;
2489 if (const BlockPointerType *FromBlockPtr =
2490 FromType->getAs<BlockPointerType>())
2491 FromPointeeType = FromBlockPtr->getPointeeType();
2492 else
2493 return false;
2494 // We have pointer to blocks, check whether the only
2495 // differences in the argument and result types are in Objective-C
2496 // pointer conversions. If so, we permit the conversion.
2497
2498 const FunctionProtoType *FromFunctionType
2499 = FromPointeeType->getAs<FunctionProtoType>();
2500 const FunctionProtoType *ToFunctionType
2501 = ToPointeeType->getAs<FunctionProtoType>();
2502
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002503 if (!FromFunctionType || !ToFunctionType)
2504 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002505
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002506 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002507 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002508
2509 // Perform the quick checks that will tell us whether these
2510 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002511 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002512 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2513 return false;
2514
2515 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2516 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2517 if (FromEInfo != ToEInfo)
2518 return false;
2519
2520 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002521 if (Context.hasSameType(FromFunctionType->getReturnType(),
2522 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002523 // Okay, the types match exactly. Nothing to do.
2524 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002525 QualType RHS = FromFunctionType->getReturnType();
2526 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002527 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002528 !RHS.hasQualifiers() && LHS.hasQualifiers())
2529 LHS = LHS.getUnqualifiedType();
2530
2531 if (Context.hasSameType(RHS,LHS)) {
2532 // OK exact match.
2533 } else if (isObjCPointerConversion(RHS, LHS,
2534 ConvertedType, IncompatibleObjC)) {
2535 if (IncompatibleObjC)
2536 return false;
2537 // Okay, we have an Objective-C pointer conversion.
2538 }
2539 else
2540 return false;
2541 }
2542
2543 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002544 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002545 ArgIdx != NumArgs; ++ArgIdx) {
2546 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002547 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2548 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002549 if (Context.hasSameType(FromArgType, ToArgType)) {
2550 // Okay, the types match exactly. Nothing to do.
2551 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2552 ConvertedType, IncompatibleObjC)) {
2553 if (IncompatibleObjC)
2554 return false;
2555 // Okay, we have an Objective-C pointer conversion.
2556 } else
2557 // Argument types are too different. Abort.
2558 return false;
2559 }
John McCall18afab72016-03-01 00:49:02 +00002560 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2561 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002562 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002563
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002564 ConvertedType = ToType;
2565 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002566}
2567
Richard Trieucaff2472011-11-23 22:32:32 +00002568enum {
2569 ft_default,
2570 ft_different_class,
2571 ft_parameter_arity,
2572 ft_parameter_mismatch,
2573 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002574 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002575};
2576
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002577/// Attempts to get the FunctionProtoType from a Type. Handles
2578/// MemberFunctionPointers properly.
2579static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2580 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2581 return FPT;
2582
2583 if (auto *MPT = FromType->getAs<MemberPointerType>())
2584 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2585
2586 return nullptr;
2587}
2588
Richard Trieucaff2472011-11-23 22:32:32 +00002589/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2590/// function types. Catches different number of parameter, mismatch in
2591/// parameter types, and different return types.
2592void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2593 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002594 // If either type is not valid, include no extra info.
2595 if (FromType.isNull() || ToType.isNull()) {
2596 PDiag << ft_default;
2597 return;
2598 }
2599
Richard Trieucaff2472011-11-23 22:32:32 +00002600 // Get the function type from the pointers.
2601 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2602 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2603 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002604 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002605 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2606 << QualType(FromMember->getClass(), 0);
2607 return;
2608 }
2609 FromType = FromMember->getPointeeType();
2610 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002611 }
2612
Richard Trieu96ed5b62011-12-13 23:19:45 +00002613 if (FromType->isPointerType())
2614 FromType = FromType->getPointeeType();
2615 if (ToType->isPointerType())
2616 ToType = ToType->getPointeeType();
2617
2618 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002619 FromType = FromType.getNonReferenceType();
2620 ToType = ToType.getNonReferenceType();
2621
Richard Trieucaff2472011-11-23 22:32:32 +00002622 // Don't print extra info for non-specialized template functions.
2623 if (FromType->isInstantiationDependentType() &&
2624 !FromType->getAs<TemplateSpecializationType>()) {
2625 PDiag << ft_default;
2626 return;
2627 }
2628
Richard Trieu96ed5b62011-12-13 23:19:45 +00002629 // No extra info for same types.
2630 if (Context.hasSameType(FromType, ToType)) {
2631 PDiag << ft_default;
2632 return;
2633 }
2634
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002635 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2636 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002637
2638 // Both types need to be function types.
2639 if (!FromFunction || !ToFunction) {
2640 PDiag << ft_default;
2641 return;
2642 }
2643
Alp Toker9cacbab2014-01-20 20:26:09 +00002644 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2645 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2646 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002647 return;
2648 }
2649
2650 // Handle different parameter types.
2651 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002652 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002653 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002654 << ToFunction->getParamType(ArgPos)
2655 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002656 return;
2657 }
2658
2659 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002660 if (!Context.hasSameType(FromFunction->getReturnType(),
2661 ToFunction->getReturnType())) {
2662 PDiag << ft_return_type << ToFunction->getReturnType()
2663 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002664 return;
2665 }
2666
2667 unsigned FromQuals = FromFunction->getTypeQuals(),
2668 ToQuals = ToFunction->getTypeQuals();
2669 if (FromQuals != ToQuals) {
2670 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2671 return;
2672 }
2673
2674 // Unable to find a difference, so add no extra info.
2675 PDiag << ft_default;
2676}
2677
Alp Toker9cacbab2014-01-20 20:26:09 +00002678/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002679/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002680/// they have same number of arguments. If the parameters are different,
2681/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002682bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2683 const FunctionProtoType *NewType,
2684 unsigned *ArgPos) {
2685 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2686 N = NewType->param_type_begin(),
2687 E = OldType->param_type_end();
2688 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002689 if (!Context.hasSameType(O->getUnqualifiedType(),
2690 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002691 if (ArgPos)
2692 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002693 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002694 }
2695 }
2696 return true;
2697}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002698
Douglas Gregor39c16d42008-10-24 04:54:22 +00002699/// CheckPointerConversion - Check the pointer conversion from the
2700/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002701/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002702/// conversions for which IsPointerConversion has already returned
2703/// true. It returns true and produces a diagnostic if there was an
2704/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002705bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002706 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002707 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002708 bool IgnoreBaseAccess,
2709 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002710 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002711 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002712
John McCall8cb679e2010-11-15 09:13:47 +00002713 Kind = CK_BitCast;
2714
George Burgess IV60bc9722016-01-13 23:36:34 +00002715 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002716 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002717 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002718 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2719 DiagRuntimeBehavior(From->getExprLoc(), From,
2720 PDiag(diag::warn_impcast_bool_to_null_pointer)
2721 << ToType << From->getSourceRange());
2722 else if (!isUnevaluatedContext())
2723 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2724 << ToType << From->getSourceRange();
2725 }
John McCall9320b872011-09-09 05:25:32 +00002726 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2727 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002728 QualType FromPointeeType = FromPtrType->getPointeeType(),
2729 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002730
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002731 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2732 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002733 // We must have a derived-to-base conversion. Check an
2734 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002735 unsigned InaccessibleID = 0;
2736 unsigned AmbigiousID = 0;
2737 if (Diagnose) {
2738 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2739 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2740 }
2741 if (CheckDerivedToBaseConversion(
2742 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2743 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2744 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002745 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002747 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002748 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002749 }
David Majnemer6bf02822015-10-31 08:42:14 +00002750
George Burgess IV60bc9722016-01-13 23:36:34 +00002751 if (Diagnose && !IsCStyleOrFunctionalCast &&
2752 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002753 assert(getLangOpts().MSVCCompat &&
2754 "this should only be possible with MSVCCompat!");
2755 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2756 << From->getSourceRange();
2757 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002758 }
John McCall9320b872011-09-09 05:25:32 +00002759 } else if (const ObjCObjectPointerType *ToPtrType =
2760 ToType->getAs<ObjCObjectPointerType>()) {
2761 if (const ObjCObjectPointerType *FromPtrType =
2762 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002763 // Objective-C++ conversions are always okay.
2764 // FIXME: We should have a different class of conversions for the
2765 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002766 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002767 return false;
John McCall9320b872011-09-09 05:25:32 +00002768 } else if (FromType->isBlockPointerType()) {
2769 Kind = CK_BlockPointerToObjCPointerCast;
2770 } else {
2771 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002772 }
John McCall9320b872011-09-09 05:25:32 +00002773 } else if (ToType->isBlockPointerType()) {
2774 if (!FromType->isBlockPointerType())
2775 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002776 }
John McCall8cb679e2010-11-15 09:13:47 +00002777
2778 // We shouldn't fall into this case unless it's valid for other
2779 // reasons.
2780 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2781 Kind = CK_NullToPointer;
2782
Douglas Gregor39c16d42008-10-24 04:54:22 +00002783 return false;
2784}
2785
Sebastian Redl72b597d2009-01-25 19:43:20 +00002786/// IsMemberPointerConversion - Determines whether the conversion of the
2787/// expression From, which has the (possibly adjusted) type FromType, can be
2788/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2789/// If so, returns true and places the converted type (that might differ from
2790/// ToType in its cv-qualifiers at some level) into ConvertedType.
2791bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002792 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002793 bool InOverloadResolution,
2794 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002795 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002796 if (!ToTypePtr)
2797 return false;
2798
2799 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002800 if (From->isNullPointerConstant(Context,
2801 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2802 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002803 ConvertedType = ToType;
2804 return true;
2805 }
2806
2807 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002808 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002809 if (!FromTypePtr)
2810 return false;
2811
2812 // A pointer to member of B can be converted to a pointer to member of D,
2813 // where D is derived from B (C++ 4.11p2).
2814 QualType FromClass(FromTypePtr->getClass(), 0);
2815 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002816
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002817 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002818 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002819 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2820 ToClass.getTypePtr());
2821 return true;
2822 }
2823
2824 return false;
2825}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826
Sebastian Redl72b597d2009-01-25 19:43:20 +00002827/// CheckMemberPointerConversion - Check the member pointer conversion from the
2828/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002829/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002830/// for which IsMemberPointerConversion has already returned true. It returns
2831/// true and produces a diagnostic if there was an error, or returns false
2832/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002833bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002834 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002835 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002836 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002837 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002838 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002839 if (!FromPtrType) {
2840 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002842 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002843 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002844 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002845 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002846 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002847
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002848 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002849 assert(ToPtrType && "No member pointer cast has a target type "
2850 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002851
Sebastian Redled8f2002009-01-28 18:33:18 +00002852 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2853 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002854
Sebastian Redled8f2002009-01-28 18:33:18 +00002855 // FIXME: What about dependent types?
2856 assert(FromClass->isRecordType() && "Pointer into non-class.");
2857 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002858
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002859 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002860 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002861 bool DerivationOkay =
2862 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002863 assert(DerivationOkay &&
2864 "Should not have been called if derivation isn't OK.");
2865 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002866
Sebastian Redled8f2002009-01-28 18:33:18 +00002867 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2868 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002869 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2870 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2871 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2872 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002873 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002874
Douglas Gregor89ee6822009-02-28 01:32:25 +00002875 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002876 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2877 << FromClass << ToClass << QualType(VBase, 0)
2878 << From->getSourceRange();
2879 return true;
2880 }
2881
John McCall5b0829a2010-02-10 09:31:12 +00002882 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002883 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2884 Paths.front(),
2885 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002886
Anders Carlssond7923c62009-08-22 23:33:40 +00002887 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002888 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002889 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002890 return false;
2891}
2892
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002893/// Determine whether the lifetime conversion between the two given
2894/// qualifiers sets is nontrivial.
2895static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2896 Qualifiers ToQuals) {
2897 // Converting anything to const __unsafe_unretained is trivial.
2898 if (ToQuals.hasConst() &&
2899 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2900 return false;
2901
2902 return true;
2903}
2904
Douglas Gregor9a657932008-10-21 23:43:52 +00002905/// IsQualificationConversion - Determines whether the conversion from
2906/// an rvalue of type FromType to ToType is a qualification conversion
2907/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002908///
2909/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2910/// when the qualification conversion involves a change in the Objective-C
2911/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002912bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002914 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002915 FromType = Context.getCanonicalType(FromType);
2916 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002917 ObjCLifetimeConversion = false;
2918
Douglas Gregor9a657932008-10-21 23:43:52 +00002919 // If FromType and ToType are the same type, this is not a
2920 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002921 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002922 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002923
Douglas Gregor9a657932008-10-21 23:43:52 +00002924 // (C++ 4.4p4):
2925 // A conversion can add cv-qualifiers at levels other than the first
2926 // in multi-level pointers, subject to the following rules: [...]
2927 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002928 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002929 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002930 // Within each iteration of the loop, we check the qualifiers to
2931 // determine if this still looks like a qualification
2932 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002933 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002934 // until there are no more pointers or pointers-to-members left to
2935 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002936 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002937
Douglas Gregor90609aa2011-04-25 18:40:17 +00002938 Qualifiers FromQuals = FromType.getQualifiers();
2939 Qualifiers ToQuals = ToType.getQualifiers();
2940
John McCall31168b02011-06-15 23:02:42 +00002941 // Objective-C ARC:
2942 // Check Objective-C lifetime conversions.
2943 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2944 UnwrappedAnyPointer) {
2945 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002946 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2947 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002948 FromQuals.removeObjCLifetime();
2949 ToQuals.removeObjCLifetime();
2950 } else {
2951 // Qualification conversions cannot cast between different
2952 // Objective-C lifetime qualifiers.
2953 return false;
2954 }
2955 }
2956
Douglas Gregorf30053d2011-05-08 06:09:53 +00002957 // Allow addition/removal of GC attributes but not changing GC attributes.
2958 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2959 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2960 FromQuals.removeObjCGCAttr();
2961 ToQuals.removeObjCGCAttr();
2962 }
2963
Douglas Gregor9a657932008-10-21 23:43:52 +00002964 // -- for every j > 0, if const is in cv 1,j then const is in cv
2965 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002966 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002967 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002968
Douglas Gregor9a657932008-10-21 23:43:52 +00002969 // -- if the cv 1,j and cv 2,j are different, then const is in
2970 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002971 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002972 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002973 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002974
Douglas Gregor9a657932008-10-21 23:43:52 +00002975 // Keep track of whether all prior cv-qualifiers in the "to" type
2976 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002977 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002978 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002979 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002980
2981 // We are left with FromType and ToType being the pointee types
2982 // after unwrapping the original FromType and ToType the same number
2983 // of types. If we unwrapped any pointers, and if FromType and
2984 // ToType have the same unqualified type (since we checked
2985 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002986 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002987}
2988
Douglas Gregorc79862f2012-04-12 17:51:55 +00002989/// \brief - Determine whether this is a conversion from a scalar type to an
2990/// atomic type.
2991///
2992/// If successful, updates \c SCS's second and third steps in the conversion
2993/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002994static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2995 bool InOverloadResolution,
2996 StandardConversionSequence &SCS,
2997 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002998 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2999 if (!ToAtomic)
3000 return false;
3001
3002 StandardConversionSequence InnerSCS;
3003 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3004 InOverloadResolution, InnerSCS,
3005 CStyle, /*AllowObjCWritebackConversion=*/false))
3006 return false;
3007
3008 SCS.Second = InnerSCS.Second;
3009 SCS.setToType(1, InnerSCS.getToType(1));
3010 SCS.Third = InnerSCS.Third;
3011 SCS.QualificationIncludesObjCLifetime
3012 = InnerSCS.QualificationIncludesObjCLifetime;
3013 SCS.setToType(2, InnerSCS.getToType(2));
3014 return true;
3015}
3016
Sebastian Redle5417162012-03-27 18:33:03 +00003017static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3018 CXXConstructorDecl *Constructor,
3019 QualType Type) {
3020 const FunctionProtoType *CtorType =
3021 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003022 if (CtorType->getNumParams() > 0) {
3023 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003024 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3025 return true;
3026 }
3027 return false;
3028}
3029
Sebastian Redl82ace982012-02-11 23:51:08 +00003030static OverloadingResult
3031IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3032 CXXRecordDecl *To,
3033 UserDefinedConversionSequence &User,
3034 OverloadCandidateSet &CandidateSet,
3035 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00003036 DeclContext::lookup_result R = S.LookupConstructors(To);
3037 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00003038 Con != ConEnd; ++Con) {
3039 NamedDecl *D = *Con;
3040 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3041
3042 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003043 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00003044 FunctionTemplateDecl *ConstructorTmpl
3045 = dyn_cast<FunctionTemplateDecl>(D);
3046 if (ConstructorTmpl)
3047 Constructor
3048 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3049 else
3050 Constructor = cast<CXXConstructorDecl>(D);
3051
3052 bool Usable = !Constructor->isInvalidDecl() &&
3053 S.isInitListConstructor(Constructor) &&
3054 (AllowExplicit || !Constructor->isExplicit());
3055 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003056 // If the first argument is (a reference to) the target type,
3057 // suppress conversions.
3058 bool SuppressUserConversions =
3059 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00003060 if (ConstructorTmpl)
3061 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003062 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003063 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003064 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003065 else
3066 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003067 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003068 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003069 }
3070 }
3071
3072 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3073
3074 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003075 switch (auto Result =
3076 CandidateSet.BestViableFunction(S, From->getLocStart(),
3077 Best, true)) {
3078 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003079 case OR_Success: {
3080 // Record the standard conversion we used and the conversion function.
3081 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003082 QualType ThisType = Constructor->getThisType(S.Context);
3083 // Initializer lists don't have conversions as such.
3084 User.Before.setAsIdentityConversion();
3085 User.HadMultipleCandidates = HadMultipleCandidates;
3086 User.ConversionFunction = Constructor;
3087 User.FoundConversionFunction = Best->FoundDecl;
3088 User.After.setAsIdentityConversion();
3089 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3090 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003091 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003092 }
3093
3094 case OR_No_Viable_Function:
3095 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003096 case OR_Ambiguous:
3097 return OR_Ambiguous;
3098 }
3099
3100 llvm_unreachable("Invalid OverloadResult!");
3101}
3102
Douglas Gregor576e98c2009-01-30 23:27:23 +00003103/// Determines whether there is a user-defined conversion sequence
3104/// (C++ [over.ics.user]) that converts expression From to the type
3105/// ToType. If such a conversion exists, User will contain the
3106/// user-defined conversion sequence that performs such a conversion
3107/// and this routine will return true. Otherwise, this routine returns
3108/// false and User is unspecified.
3109///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003110/// \param AllowExplicit true if the conversion should consider C++0x
3111/// "explicit" conversion functions as well as non-explicit conversion
3112/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003113///
3114/// \param AllowObjCConversionOnExplicit true if the conversion should
3115/// allow an extra Objective-C pointer conversion on uses of explicit
3116/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003117static OverloadingResult
3118IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003119 UserDefinedConversionSequence &User,
3120 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003121 bool AllowExplicit,
3122 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003123 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003124
Douglas Gregor5ab11652010-04-17 22:01:05 +00003125 // Whether we will only visit constructors.
3126 bool ConstructorsOnly = false;
3127
3128 // If the type we are conversion to is a class type, enumerate its
3129 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003130 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003131 // C++ [over.match.ctor]p1:
3132 // When objects of class type are direct-initialized (8.5), or
3133 // copy-initialized from an expression of the same or a
3134 // derived class type (8.5), overload resolution selects the
3135 // constructor. [...] For copy-initialization, the candidate
3136 // functions are all the converting constructors (12.3.1) of
3137 // that class. The argument list is the expression-list within
3138 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003139 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003140 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003141 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003142 ConstructorsOnly = true;
3143
Richard Smithdb0ac552015-12-18 22:40:25 +00003144 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003145 // We're not going to find any constructors.
3146 } else if (CXXRecordDecl *ToRecordDecl
3147 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003148
3149 Expr **Args = &From;
3150 unsigned NumArgs = 1;
3151 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003152 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003153 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003154 OverloadingResult Result = IsInitializerListConstructorConversion(
3155 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3156 if (Result != OR_No_Viable_Function)
3157 return Result;
3158 // Never mind.
3159 CandidateSet.clear();
3160
3161 // If we're list-initializing, we pass the individual elements as
3162 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003163 Args = InitList->getInits();
3164 NumArgs = InitList->getNumInits();
3165 ListInitializing = true;
3166 }
3167
David Blaikieff7d47a2012-12-19 00:45:41 +00003168 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3169 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003170 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003171 NamedDecl *D = *Con;
3172 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3173
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003174 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003175 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003176 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003177 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003178 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003179 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003180 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3181 else
John McCalla0296f72010-03-19 07:35:19 +00003182 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003184 bool Usable = !Constructor->isInvalidDecl();
3185 if (ListInitializing)
3186 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3187 else
3188 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3189 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003190 bool SuppressUserConversions = !ConstructorsOnly;
3191 if (SuppressUserConversions && ListInitializing) {
3192 SuppressUserConversions = false;
3193 if (NumArgs == 1) {
3194 // If the first argument is (a reference to) the target type,
3195 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003196 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3197 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003198 }
3199 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003200 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003201 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003202 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003203 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003204 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003205 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003206 // Allow one user-defined conversion when user specifies a
3207 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003208 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003209 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003210 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003211 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003212 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003213 }
3214 }
3215
Douglas Gregor5ab11652010-04-17 22:01:05 +00003216 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003217 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003218 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003219 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003220 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003221 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003222 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003223 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3224 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003225 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3226 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003227 DeclAccessPair FoundDecl = I.getPair();
3228 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003229 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3230 if (isa<UsingShadowDecl>(D))
3231 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3232
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003233 CXXConversionDecl *Conv;
3234 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003235 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3236 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003237 else
John McCallda4458e2010-03-31 01:36:47 +00003238 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003239
3240 if (AllowExplicit || !Conv->isExplicit()) {
3241 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003242 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3243 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003244 CandidateSet,
3245 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003246 else
John McCall5c32be02010-08-24 20:38:10 +00003247 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003248 From, ToType, CandidateSet,
3249 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003250 }
3251 }
3252 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003253 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003254
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003255 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3256
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003257 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003258 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3259 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003260 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003261 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003262 // Record the standard conversion we used and the conversion function.
3263 if (CXXConstructorDecl *Constructor
3264 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3265 // C++ [over.ics.user]p1:
3266 // If the user-defined conversion is specified by a
3267 // constructor (12.3.1), the initial standard conversion
3268 // sequence converts the source type to the type required by
3269 // the argument of the constructor.
3270 //
3271 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003272 if (isa<InitListExpr>(From)) {
3273 // Initializer lists don't have conversions as such.
3274 User.Before.setAsIdentityConversion();
3275 } else {
3276 if (Best->Conversions[0].isEllipsis())
3277 User.EllipsisConversion = true;
3278 else {
3279 User.Before = Best->Conversions[0].Standard;
3280 User.EllipsisConversion = false;
3281 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003282 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003283 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003284 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003285 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003286 User.After.setAsIdentityConversion();
3287 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3288 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003289 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003290 }
3291 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003292 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3293 // C++ [over.ics.user]p1:
3294 //
3295 // [...] If the user-defined conversion is specified by a
3296 // conversion function (12.3.2), the initial standard
3297 // conversion sequence converts the source type to the
3298 // implicit object parameter of the conversion function.
3299 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003300 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003301 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003302 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003303 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003304
John McCall5c32be02010-08-24 20:38:10 +00003305 // C++ [over.ics.user]p2:
3306 // The second standard conversion sequence converts the
3307 // result of the user-defined conversion to the target type
3308 // for the sequence. Since an implicit conversion sequence
3309 // is an initialization, the special rules for
3310 // initialization by user-defined conversion apply when
3311 // selecting the best user-defined conversion for a
3312 // user-defined conversion sequence (see 13.3.3 and
3313 // 13.3.3.1).
3314 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003315 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003316 }
David Blaikie8a40f702012-01-17 06:56:22 +00003317 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003318
John McCall5c32be02010-08-24 20:38:10 +00003319 case OR_No_Viable_Function:
3320 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321
John McCall5c32be02010-08-24 20:38:10 +00003322 case OR_Ambiguous:
3323 return OR_Ambiguous;
3324 }
3325
David Blaikie8a40f702012-01-17 06:56:22 +00003326 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003327}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003329bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003330Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003331 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003332 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3333 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003335 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003336 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003337 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003338 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3339 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003340 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003341 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003342 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003343 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003344 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003345 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003346 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003347 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003348 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003349 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003350}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003351
Douglas Gregor2837aa22012-02-22 17:32:19 +00003352/// \brief Compare the user-defined conversion functions or constructors
3353/// of two user-defined conversion sequences to determine whether any ordering
3354/// is possible.
3355static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003356compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003357 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003358 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003359 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003360
Douglas Gregor2837aa22012-02-22 17:32:19 +00003361 // Objective-C++:
3362 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003363 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003364 // respectively, always prefer the conversion to a function pointer,
3365 // because the function pointer is more lightweight and is more likely
3366 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003367 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003368 if (!Conv1)
3369 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003370
Douglas Gregor2837aa22012-02-22 17:32:19 +00003371 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3372 if (!Conv2)
3373 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003374
Douglas Gregor2837aa22012-02-22 17:32:19 +00003375 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3376 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3377 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3378 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003379 return Block1 ? ImplicitConversionSequence::Worse
3380 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003381 }
3382
3383 return ImplicitConversionSequence::Indistinguishable;
3384}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003385
3386static bool hasDeprecatedStringLiteralToCharPtrConversion(
3387 const ImplicitConversionSequence &ICS) {
3388 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3389 (ICS.isUserDefined() &&
3390 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3391}
3392
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003393/// CompareImplicitConversionSequences - Compare two implicit
3394/// conversion sequences to determine whether one is better than the
3395/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003396static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003397CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003398 const ImplicitConversionSequence& ICS1,
3399 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003400{
3401 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3402 // conversion sequences (as defined in 13.3.3.1)
3403 // -- a standard conversion sequence (13.3.3.1.1) is a better
3404 // conversion sequence than a user-defined conversion sequence or
3405 // an ellipsis conversion sequence, and
3406 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3407 // conversion sequence than an ellipsis conversion sequence
3408 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003409 //
John McCall0d1da222010-01-12 00:44:57 +00003410 // C++0x [over.best.ics]p10:
3411 // For the purpose of ranking implicit conversion sequences as
3412 // described in 13.3.3.2, the ambiguous conversion sequence is
3413 // treated as a user-defined sequence that is indistinguishable
3414 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003415
3416 // String literal to 'char *' conversion has been deprecated in C++03. It has
3417 // been removed from C++11. We still accept this conversion, if it happens at
3418 // the best viable function. Otherwise, this conversion is considered worse
3419 // than ellipsis conversion. Consider this as an extension; this is not in the
3420 // standard. For example:
3421 //
3422 // int &f(...); // #1
3423 // void f(char*); // #2
3424 // void g() { int &r = f("foo"); }
3425 //
3426 // In C++03, we pick #2 as the best viable function.
3427 // In C++11, we pick #1 as the best viable function, because ellipsis
3428 // conversion is better than string-literal to char* conversion (since there
3429 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3430 // convert arguments, #2 would be the best viable function in C++11.
3431 // If the best viable function has this conversion, a warning will be issued
3432 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3433
3434 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3435 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3436 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3437 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3438 ? ImplicitConversionSequence::Worse
3439 : ImplicitConversionSequence::Better;
3440
Douglas Gregor5ab11652010-04-17 22:01:05 +00003441 if (ICS1.getKindRank() < ICS2.getKindRank())
3442 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003443 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003444 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003445
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003446 // The following checks require both conversion sequences to be of
3447 // the same kind.
3448 if (ICS1.getKind() != ICS2.getKind())
3449 return ImplicitConversionSequence::Indistinguishable;
3450
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003451 ImplicitConversionSequence::CompareKind Result =
3452 ImplicitConversionSequence::Indistinguishable;
3453
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003454 // Two implicit conversion sequences of the same form are
3455 // indistinguishable conversion sequences unless one of the
3456 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003457
3458 // List-initialization sequence L1 is a better conversion sequence than
3459 // list-initialization sequence L2 if:
3460 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3461 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003462 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003463 // and N1 is smaller than N2.,
3464 // even if one of the other rules in this paragraph would otherwise apply.
3465 if (!ICS1.isBad()) {
3466 if (ICS1.isStdInitializerListElement() &&
3467 !ICS2.isStdInitializerListElement())
3468 return ImplicitConversionSequence::Better;
3469 if (!ICS1.isStdInitializerListElement() &&
3470 ICS2.isStdInitializerListElement())
3471 return ImplicitConversionSequence::Worse;
3472 }
3473
John McCall0d1da222010-01-12 00:44:57 +00003474 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003475 // Standard conversion sequence S1 is a better conversion sequence than
3476 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003477 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003478 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003479 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003480 // User-defined conversion sequence U1 is a better conversion
3481 // sequence than another user-defined conversion sequence U2 if
3482 // they contain the same user-defined conversion function or
3483 // constructor and if the second standard conversion sequence of
3484 // U1 is better than the second standard conversion sequence of
3485 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003486 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003487 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003488 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003489 ICS1.UserDefined.After,
3490 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003491 else
3492 Result = compareConversionFunctions(S,
3493 ICS1.UserDefined.ConversionFunction,
3494 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003495 }
3496
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003497 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003498}
3499
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003500static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3501 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3502 Qualifiers Quals;
3503 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003507 return Context.hasSameUnqualifiedType(T1, T2);
3508}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003510// Per 13.3.3.2p3, compare the given standard conversion sequences to
3511// determine if one is a proper subset of the other.
3512static ImplicitConversionSequence::CompareKind
3513compareStandardConversionSubsets(ASTContext &Context,
3514 const StandardConversionSequence& SCS1,
3515 const StandardConversionSequence& SCS2) {
3516 ImplicitConversionSequence::CompareKind Result
3517 = ImplicitConversionSequence::Indistinguishable;
3518
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003520 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003521 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3522 return ImplicitConversionSequence::Better;
3523 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3524 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003526 if (SCS1.Second != SCS2.Second) {
3527 if (SCS1.Second == ICK_Identity)
3528 Result = ImplicitConversionSequence::Better;
3529 else if (SCS2.Second == ICK_Identity)
3530 Result = ImplicitConversionSequence::Worse;
3531 else
3532 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003533 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003534 return ImplicitConversionSequence::Indistinguishable;
3535
3536 if (SCS1.Third == SCS2.Third) {
3537 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3538 : ImplicitConversionSequence::Indistinguishable;
3539 }
3540
3541 if (SCS1.Third == ICK_Identity)
3542 return Result == ImplicitConversionSequence::Worse
3543 ? ImplicitConversionSequence::Indistinguishable
3544 : ImplicitConversionSequence::Better;
3545
3546 if (SCS2.Third == ICK_Identity)
3547 return Result == ImplicitConversionSequence::Better
3548 ? ImplicitConversionSequence::Indistinguishable
3549 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003551 return ImplicitConversionSequence::Indistinguishable;
3552}
3553
Douglas Gregore696ebb2011-01-26 14:52:12 +00003554/// \brief Determine whether one of the given reference bindings is better
3555/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003556static bool
3557isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3558 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003559 // C++0x [over.ics.rank]p3b4:
3560 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3561 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003563 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003565 // reference*.
3566 //
3567 // FIXME: Rvalue references. We're going rogue with the above edits,
3568 // because the semantics in the current C++0x working paper (N3225 at the
3569 // time of this writing) break the standard definition of std::forward
3570 // and std::reference_wrapper when dealing with references to functions.
3571 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003572 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3573 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3574 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575
Douglas Gregore696ebb2011-01-26 14:52:12 +00003576 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3577 SCS2.IsLvalueReference) ||
3578 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003579 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003580}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003581
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003582/// CompareStandardConversionSequences - Compare two standard
3583/// conversion sequences to determine whether one is better than the
3584/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003585static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003586CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003587 const StandardConversionSequence& SCS1,
3588 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003589{
3590 // Standard conversion sequence S1 is a better conversion sequence
3591 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3592
3593 // -- S1 is a proper subsequence of S2 (comparing the conversion
3594 // sequences in the canonical form defined by 13.3.3.1.1,
3595 // excluding any Lvalue Transformation; the identity conversion
3596 // sequence is considered to be a subsequence of any
3597 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003598 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003599 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003600 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003601
3602 // -- the rank of S1 is better than the rank of S2 (by the rules
3603 // defined below), or, if not that,
3604 ImplicitConversionRank Rank1 = SCS1.getRank();
3605 ImplicitConversionRank Rank2 = SCS2.getRank();
3606 if (Rank1 < Rank2)
3607 return ImplicitConversionSequence::Better;
3608 else if (Rank2 < Rank1)
3609 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003610
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003611 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3612 // are indistinguishable unless one of the following rules
3613 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003614
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003615 // A conversion that is not a conversion of a pointer, or
3616 // pointer to member, to bool is better than another conversion
3617 // that is such a conversion.
3618 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3619 return SCS2.isPointerConversionToBool()
3620 ? ImplicitConversionSequence::Better
3621 : ImplicitConversionSequence::Worse;
3622
Douglas Gregor5c407d92008-10-23 00:40:37 +00003623 // C++ [over.ics.rank]p4b2:
3624 //
3625 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003626 // conversion of B* to A* is better than conversion of B* to
3627 // void*, and conversion of A* to void* is better than conversion
3628 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003629 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003630 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003631 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003632 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003633 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3634 // Exactly one of the conversion sequences is a conversion to
3635 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003636 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3637 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003638 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3639 // Neither conversion sequence converts to a void pointer; compare
3640 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003641 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003642 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003643 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003644 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3645 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003646 // Both conversion sequences are conversions to void
3647 // pointers. Compare the source types to determine if there's an
3648 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003649 QualType FromType1 = SCS1.getFromType();
3650 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003651
3652 // Adjust the types we're converting from via the array-to-pointer
3653 // conversion, if we need to.
3654 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003655 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003656 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003657 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003658
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003659 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3660 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003661
Richard Smith0f59cb32015-12-18 21:45:41 +00003662 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003663 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003664 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003665 return ImplicitConversionSequence::Worse;
3666
3667 // Objective-C++: If one interface is more specific than the
3668 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003669 const ObjCObjectPointerType* FromObjCPtr1
3670 = FromType1->getAs<ObjCObjectPointerType>();
3671 const ObjCObjectPointerType* FromObjCPtr2
3672 = FromType2->getAs<ObjCObjectPointerType>();
3673 if (FromObjCPtr1 && FromObjCPtr2) {
3674 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3675 FromObjCPtr2);
3676 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3677 FromObjCPtr1);
3678 if (AssignLeft != AssignRight) {
3679 return AssignLeft? ImplicitConversionSequence::Better
3680 : ImplicitConversionSequence::Worse;
3681 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003682 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003683 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003684
3685 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3686 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003687 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003688 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003689 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003690
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003691 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003692 // Check for a better reference binding based on the kind of bindings.
3693 if (isBetterReferenceBindingKind(SCS1, SCS2))
3694 return ImplicitConversionSequence::Better;
3695 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3696 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697
Sebastian Redlb28b4072009-03-22 23:49:27 +00003698 // C++ [over.ics.rank]p3b4:
3699 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3700 // which the references refer are the same type except for
3701 // top-level cv-qualifiers, and the type to which the reference
3702 // initialized by S2 refers is more cv-qualified than the type
3703 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003704 QualType T1 = SCS1.getToType(2);
3705 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003706 T1 = S.Context.getCanonicalType(T1);
3707 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003708 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003709 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3710 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003711 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003712 // Objective-C++ ARC: If the references refer to objects with different
3713 // lifetimes, prefer bindings that don't change lifetime.
3714 if (SCS1.ObjCLifetimeConversionBinding !=
3715 SCS2.ObjCLifetimeConversionBinding) {
3716 return SCS1.ObjCLifetimeConversionBinding
3717 ? ImplicitConversionSequence::Worse
3718 : ImplicitConversionSequence::Better;
3719 }
3720
Chandler Carruth8e543b32010-12-12 08:17:55 +00003721 // If the type is an array type, promote the element qualifiers to the
3722 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003723 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003724 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003725 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003726 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003727 if (T2.isMoreQualifiedThan(T1))
3728 return ImplicitConversionSequence::Better;
3729 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003730 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003731 }
3732 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003733
Francois Pichet08d2fa02011-09-18 21:37:37 +00003734 // In Microsoft mode, prefer an integral conversion to a
3735 // floating-to-integral conversion if the integral conversion
3736 // is between types of the same size.
3737 // For example:
3738 // void f(float);
3739 // void f(int);
3740 // int main {
3741 // long a;
3742 // f(a);
3743 // }
3744 // Here, MSVC will call f(int) instead of generating a compile error
3745 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003746 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3747 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003748 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003749 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003750 return ImplicitConversionSequence::Better;
3751
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003752 return ImplicitConversionSequence::Indistinguishable;
3753}
3754
3755/// CompareQualificationConversions - Compares two standard conversion
3756/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003757/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003758static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003759CompareQualificationConversions(Sema &S,
3760 const StandardConversionSequence& SCS1,
3761 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003762 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003763 // -- S1 and S2 differ only in their qualification conversion and
3764 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3765 // cv-qualification signature of type T1 is a proper subset of
3766 // the cv-qualification signature of type T2, and S1 is not the
3767 // deprecated string literal array-to-pointer conversion (4.2).
3768 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3769 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3770 return ImplicitConversionSequence::Indistinguishable;
3771
3772 // FIXME: the example in the standard doesn't use a qualification
3773 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003774 QualType T1 = SCS1.getToType(2);
3775 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003776 T1 = S.Context.getCanonicalType(T1);
3777 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003778 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003779 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3780 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003781
3782 // If the types are the same, we won't learn anything by unwrapped
3783 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003784 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003785 return ImplicitConversionSequence::Indistinguishable;
3786
Chandler Carruth607f38e2009-12-29 07:16:59 +00003787 // If the type is an array type, promote the element qualifiers to the type
3788 // for comparison.
3789 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003790 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003791 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003792 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003793
Mike Stump11289f42009-09-09 15:08:12 +00003794 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003795 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003796
3797 // Objective-C++ ARC:
3798 // Prefer qualification conversions not involving a change in lifetime
3799 // to qualification conversions that do not change lifetime.
3800 if (SCS1.QualificationIncludesObjCLifetime !=
3801 SCS2.QualificationIncludesObjCLifetime) {
3802 Result = SCS1.QualificationIncludesObjCLifetime
3803 ? ImplicitConversionSequence::Worse
3804 : ImplicitConversionSequence::Better;
3805 }
3806
John McCall5c32be02010-08-24 20:38:10 +00003807 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003808 // Within each iteration of the loop, we check the qualifiers to
3809 // determine if this still looks like a qualification
3810 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003811 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003812 // until there are no more pointers or pointers-to-members left
3813 // to unwrap. This essentially mimics what
3814 // IsQualificationConversion does, but here we're checking for a
3815 // strict subset of qualifiers.
3816 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3817 // The qualifiers are the same, so this doesn't tell us anything
3818 // about how the sequences rank.
3819 ;
3820 else if (T2.isMoreQualifiedThan(T1)) {
3821 // T1 has fewer qualifiers, so it could be the better sequence.
3822 if (Result == ImplicitConversionSequence::Worse)
3823 // Neither has qualifiers that are a subset of the other's
3824 // qualifiers.
3825 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003826
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003827 Result = ImplicitConversionSequence::Better;
3828 } else if (T1.isMoreQualifiedThan(T2)) {
3829 // T2 has fewer qualifiers, so it could be the better sequence.
3830 if (Result == ImplicitConversionSequence::Better)
3831 // Neither has qualifiers that are a subset of the other's
3832 // qualifiers.
3833 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003834
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003835 Result = ImplicitConversionSequence::Worse;
3836 } else {
3837 // Qualifiers are disjoint.
3838 return ImplicitConversionSequence::Indistinguishable;
3839 }
3840
3841 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003842 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003843 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003844 }
3845
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003846 // Check that the winning standard conversion sequence isn't using
3847 // the deprecated string literal array to pointer conversion.
3848 switch (Result) {
3849 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003850 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003851 Result = ImplicitConversionSequence::Indistinguishable;
3852 break;
3853
3854 case ImplicitConversionSequence::Indistinguishable:
3855 break;
3856
3857 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003858 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003859 Result = ImplicitConversionSequence::Indistinguishable;
3860 break;
3861 }
3862
3863 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003864}
3865
Douglas Gregor5c407d92008-10-23 00:40:37 +00003866/// CompareDerivedToBaseConversions - Compares two standard conversion
3867/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003868/// various kinds of derived-to-base conversions (C++
3869/// [over.ics.rank]p4b3). As part of these checks, we also look at
3870/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003871static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003872CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003873 const StandardConversionSequence& SCS1,
3874 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003875 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003876 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003877 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003878 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003879
3880 // Adjust the types we're converting from via the array-to-pointer
3881 // conversion, if we need to.
3882 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003883 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003884 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003885 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003886
3887 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003888 FromType1 = S.Context.getCanonicalType(FromType1);
3889 ToType1 = S.Context.getCanonicalType(ToType1);
3890 FromType2 = S.Context.getCanonicalType(FromType2);
3891 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003892
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003893 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003894 //
3895 // If class B is derived directly or indirectly from class A and
3896 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003897 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003898 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003899 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003900 SCS2.Second == ICK_Pointer_Conversion &&
3901 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3902 FromType1->isPointerType() && FromType2->isPointerType() &&
3903 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003904 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003905 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003906 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003907 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003908 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003909 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003910 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003911 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003912
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003913 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003914 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003915 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003916 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003917 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003918 return ImplicitConversionSequence::Worse;
3919 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003920
3921 // -- conversion of B* to A* is better than conversion of C* to A*,
3922 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003923 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003924 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003925 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003926 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003927 }
3928 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3929 SCS2.Second == ICK_Pointer_Conversion) {
3930 const ObjCObjectPointerType *FromPtr1
3931 = FromType1->getAs<ObjCObjectPointerType>();
3932 const ObjCObjectPointerType *FromPtr2
3933 = FromType2->getAs<ObjCObjectPointerType>();
3934 const ObjCObjectPointerType *ToPtr1
3935 = ToType1->getAs<ObjCObjectPointerType>();
3936 const ObjCObjectPointerType *ToPtr2
3937 = ToType2->getAs<ObjCObjectPointerType>();
3938
3939 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3940 // Apply the same conversion ranking rules for Objective-C pointer types
3941 // that we do for C++ pointers to class types. However, we employ the
3942 // Objective-C pseudo-subtyping relationship used for assignment of
3943 // Objective-C pointer types.
3944 bool FromAssignLeft
3945 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3946 bool FromAssignRight
3947 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3948 bool ToAssignLeft
3949 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3950 bool ToAssignRight
3951 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3952
3953 // A conversion to an a non-id object pointer type or qualified 'id'
3954 // type is better than a conversion to 'id'.
3955 if (ToPtr1->isObjCIdType() &&
3956 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3957 return ImplicitConversionSequence::Worse;
3958 if (ToPtr2->isObjCIdType() &&
3959 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3960 return ImplicitConversionSequence::Better;
3961
3962 // A conversion to a non-id object pointer type is better than a
3963 // conversion to a qualified 'id' type
3964 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3965 return ImplicitConversionSequence::Worse;
3966 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3967 return ImplicitConversionSequence::Better;
3968
3969 // A conversion to an a non-Class object pointer type or qualified 'Class'
3970 // type is better than a conversion to 'Class'.
3971 if (ToPtr1->isObjCClassType() &&
3972 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3973 return ImplicitConversionSequence::Worse;
3974 if (ToPtr2->isObjCClassType() &&
3975 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3976 return ImplicitConversionSequence::Better;
3977
3978 // A conversion to a non-Class object pointer type is better than a
3979 // conversion to a qualified 'Class' type.
3980 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3981 return ImplicitConversionSequence::Worse;
3982 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3983 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003984
Douglas Gregor058d3de2011-01-31 18:51:41 +00003985 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3986 if (S.Context.hasSameType(FromType1, FromType2) &&
3987 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3988 (ToAssignLeft != ToAssignRight))
3989 return ToAssignLeft? ImplicitConversionSequence::Worse
3990 : ImplicitConversionSequence::Better;
3991
3992 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3993 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3994 (FromAssignLeft != FromAssignRight))
3995 return FromAssignLeft? ImplicitConversionSequence::Better
3996 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003997 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003998 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003999
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004000 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004001 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4002 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4003 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004005 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004007 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004009 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004011 ToType2->getAs<MemberPointerType>();
4012 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4013 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4014 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4015 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4016 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4017 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4018 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4019 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004020 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004021 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004022 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004023 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004024 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004025 return ImplicitConversionSequence::Better;
4026 }
4027 // conversion of B::* to C::* is better than conversion of A::* to C::*
4028 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004029 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004030 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004031 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004032 return ImplicitConversionSequence::Worse;
4033 }
4034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035
Douglas Gregor5ab11652010-04-17 22:01:05 +00004036 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004037 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004038 // -- binding of an expression of type C to a reference of type
4039 // B& is better than binding an expression of type C to a
4040 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004041 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4042 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004043 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004044 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004045 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004046 return ImplicitConversionSequence::Worse;
4047 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004048
Douglas Gregor2fe98832008-11-03 19:09:14 +00004049 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004050 // -- binding of an expression of type B to a reference of type
4051 // A& is better than binding an expression of type C to a
4052 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004053 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4054 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004055 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004056 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004057 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004058 return ImplicitConversionSequence::Worse;
4059 }
4060 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004061
Douglas Gregor5c407d92008-10-23 00:40:37 +00004062 return ImplicitConversionSequence::Indistinguishable;
4063}
4064
Douglas Gregor45bb4832013-03-26 23:36:30 +00004065/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4066/// C++ class.
4067static bool isTypeValid(QualType T) {
4068 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4069 return !Record->isInvalidDecl();
4070
4071 return true;
4072}
4073
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004074/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4075/// determine whether they are reference-related,
4076/// reference-compatible, reference-compatible with added
4077/// qualification, or incompatible, for use in C++ initialization by
4078/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4079/// type, and the first type (T1) is the pointee type of the reference
4080/// type being initialized.
4081Sema::ReferenceCompareResult
4082Sema::CompareReferenceRelationship(SourceLocation Loc,
4083 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004084 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004085 bool &ObjCConversion,
4086 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004087 assert(!OrigT1->isReferenceType() &&
4088 "T1 must be the pointee type of the reference type");
4089 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4090
4091 QualType T1 = Context.getCanonicalType(OrigT1);
4092 QualType T2 = Context.getCanonicalType(OrigT2);
4093 Qualifiers T1Quals, T2Quals;
4094 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4095 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4096
4097 // C++ [dcl.init.ref]p4:
4098 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4099 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4100 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004101 DerivedToBase = false;
4102 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004103 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004104 if (UnqualT1 == UnqualT2) {
4105 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004106 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004107 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004108 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004109 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004110 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4111 UnqualT2->isObjCObjectOrInterfaceType() &&
4112 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4113 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004114 else
4115 return Ref_Incompatible;
4116
4117 // At this point, we know that T1 and T2 are reference-related (at
4118 // least).
4119
4120 // If the type is an array type, promote the element qualifiers to the type
4121 // for comparison.
4122 if (isa<ArrayType>(T1) && T1Quals)
4123 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4124 if (isa<ArrayType>(T2) && T2Quals)
4125 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4126
4127 // C++ [dcl.init.ref]p4:
4128 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4129 // reference-related to T2 and cv1 is the same cv-qualification
4130 // as, or greater cv-qualification than, cv2. For purposes of
4131 // overload resolution, cases for which cv1 is greater
4132 // cv-qualification than cv2 are identified as
4133 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004134 //
4135 // Note that we also require equivalence of Objective-C GC and address-space
4136 // qualifiers when performing these computations, so that e.g., an int in
4137 // address space 1 is not reference-compatible with an int in address
4138 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004139 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4140 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004141 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4142 ObjCLifetimeConversion = true;
4143
John McCall31168b02011-06-15 23:02:42 +00004144 T1Quals.removeObjCLifetime();
4145 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004146 }
4147
Douglas Gregord517d552011-04-28 17:56:11 +00004148 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004149 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004150 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004151 return Ref_Compatible_With_Added_Qualification;
4152 else
4153 return Ref_Related;
4154}
4155
Douglas Gregor836a7e82010-08-11 02:15:33 +00004156/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004157/// with DeclType. Return true if something definite is found.
4158static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004159FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4160 QualType DeclType, SourceLocation DeclLoc,
4161 Expr *Init, QualType T2, bool AllowRvalues,
4162 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004163 assert(T2->isRecordType() && "Can only find conversions of record types.");
4164 CXXRecordDecl *T2RecordDecl
4165 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4166
Richard Smith100b24a2014-04-17 01:52:14 +00004167 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004168 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4169 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004170 NamedDecl *D = *I;
4171 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4172 if (isa<UsingShadowDecl>(D))
4173 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4174
4175 FunctionTemplateDecl *ConvTemplate
4176 = dyn_cast<FunctionTemplateDecl>(D);
4177 CXXConversionDecl *Conv;
4178 if (ConvTemplate)
4179 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4180 else
4181 Conv = cast<CXXConversionDecl>(D);
4182
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004184 // explicit conversions, skip it.
4185 if (!AllowExplicit && Conv->isExplicit())
4186 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004187
Douglas Gregor836a7e82010-08-11 02:15:33 +00004188 if (AllowRvalues) {
4189 bool DerivedToBase = false;
4190 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004191 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004192
4193 // If we are initializing an rvalue reference, don't permit conversion
4194 // functions that return lvalues.
4195 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4196 const ReferenceType *RefType
4197 = Conv->getConversionType()->getAs<LValueReferenceType>();
4198 if (RefType && !RefType->getPointeeType()->isFunctionType())
4199 continue;
4200 }
4201
Douglas Gregor836a7e82010-08-11 02:15:33 +00004202 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004203 S.CompareReferenceRelationship(
4204 DeclLoc,
4205 Conv->getConversionType().getNonReferenceType()
4206 .getUnqualifiedType(),
4207 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004208 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004209 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004210 continue;
4211 } else {
4212 // If the conversion function doesn't return a reference type,
4213 // it can't be considered for this conversion. An rvalue reference
4214 // is only acceptable if its referencee is a function type.
4215
4216 const ReferenceType *RefType =
4217 Conv->getConversionType()->getAs<ReferenceType>();
4218 if (!RefType ||
4219 (!RefType->isLValueReferenceType() &&
4220 !RefType->getPointeeType()->isFunctionType()))
4221 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223
Douglas Gregor836a7e82010-08-11 02:15:33 +00004224 if (ConvTemplate)
4225 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004226 Init, DeclType, CandidateSet,
4227 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004228 else
4229 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004230 DeclType, CandidateSet,
4231 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004232 }
4233
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004234 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4235
Sebastian Redld92badf2010-06-30 18:13:39 +00004236 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004237 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004238 case OR_Success:
4239 // C++ [over.ics.ref]p1:
4240 //
4241 // [...] If the parameter binds directly to the result of
4242 // applying a conversion function to the argument
4243 // expression, the implicit conversion sequence is a
4244 // user-defined conversion sequence (13.3.3.1.2), with the
4245 // second standard conversion sequence either an identity
4246 // conversion or, if the conversion function returns an
4247 // entity of a type that is a derived class of the parameter
4248 // type, a derived-to-base Conversion.
4249 if (!Best->FinalConversion.DirectBinding)
4250 return false;
4251
4252 ICS.setUserDefined();
4253 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4254 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004255 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004256 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004257 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004258 ICS.UserDefined.EllipsisConversion = false;
4259 assert(ICS.UserDefined.After.ReferenceBinding &&
4260 ICS.UserDefined.After.DirectBinding &&
4261 "Expected a direct reference binding!");
4262 return true;
4263
4264 case OR_Ambiguous:
4265 ICS.setAmbiguous();
4266 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4267 Cand != CandidateSet.end(); ++Cand)
4268 if (Cand->Viable)
4269 ICS.Ambiguous.addConversion(Cand->Function);
4270 return true;
4271
4272 case OR_No_Viable_Function:
4273 case OR_Deleted:
4274 // There was no suitable conversion, or we found a deleted
4275 // conversion; continue with other checks.
4276 return false;
4277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
David Blaikie8a40f702012-01-17 06:56:22 +00004279 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004280}
4281
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004282/// \brief Compute an implicit conversion sequence for reference
4283/// initialization.
4284static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004285TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004286 SourceLocation DeclLoc,
4287 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004288 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004289 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4290
4291 // Most paths end in a failed conversion.
4292 ImplicitConversionSequence ICS;
4293 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4294
4295 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4296 QualType T2 = Init->getType();
4297
4298 // If the initializer is the address of an overloaded function, try
4299 // to resolve the overloaded function. If all goes well, T2 is the
4300 // type of the resulting function.
4301 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4302 DeclAccessPair Found;
4303 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4304 false, Found))
4305 T2 = Fn->getType();
4306 }
4307
4308 // Compute some basic properties of the types and the initializer.
4309 bool isRValRef = DeclType->isRValueReferenceType();
4310 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004311 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004312 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004313 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004314 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004315 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004316 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004317
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004318
Sebastian Redld92badf2010-06-30 18:13:39 +00004319 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004320 // A reference to type "cv1 T1" is initialized by an expression
4321 // of type "cv2 T2" as follows:
4322
Sebastian Redld92badf2010-06-30 18:13:39 +00004323 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004324 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004325 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4326 // reference-compatible with "cv2 T2," or
4327 //
4328 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4329 if (InitCategory.isLValue() &&
4330 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004331 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004332 // When a parameter of reference type binds directly (8.5.3)
4333 // to an argument expression, the implicit conversion sequence
4334 // is the identity conversion, unless the argument expression
4335 // has a type that is a derived class of the parameter type,
4336 // in which case the implicit conversion sequence is a
4337 // derived-to-base Conversion (13.3.3.1).
4338 ICS.setStandard();
4339 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004340 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4341 : ObjCConversion? ICK_Compatible_Conversion
4342 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004343 ICS.Standard.Third = ICK_Identity;
4344 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4345 ICS.Standard.setToType(0, T2);
4346 ICS.Standard.setToType(1, T1);
4347 ICS.Standard.setToType(2, T1);
4348 ICS.Standard.ReferenceBinding = true;
4349 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004350 ICS.Standard.IsLvalueReference = !isRValRef;
4351 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4352 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004353 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004354 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004355 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004356 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004357
Sebastian Redld92badf2010-06-30 18:13:39 +00004358 // Nothing more to do: the inaccessibility/ambiguity check for
4359 // derived-to-base conversions is suppressed when we're
4360 // computing the implicit conversion sequence (C++
4361 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004362 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004363 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004364
Sebastian Redld92badf2010-06-30 18:13:39 +00004365 // -- has a class type (i.e., T2 is a class type), where T1 is
4366 // not reference-related to T2, and can be implicitly
4367 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4368 // is reference-compatible with "cv3 T3" 92) (this
4369 // conversion is selected by enumerating the applicable
4370 // conversion functions (13.3.1.6) and choosing the best
4371 // one through overload resolution (13.3)),
4372 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004373 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004374 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004375 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4376 Init, T2, /*AllowRvalues=*/false,
4377 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004378 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004379 }
4380 }
4381
Sebastian Redld92badf2010-06-30 18:13:39 +00004382 // -- Otherwise, the reference shall be an lvalue reference to a
4383 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004384 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004385 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004386 return ICS;
4387
Douglas Gregorf143cd52011-01-24 16:14:37 +00004388 // -- If the initializer expression
4389 //
4390 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004391 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004392 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4393 (InitCategory.isXValue() ||
4394 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4395 (InitCategory.isLValue() && T2->isFunctionType()))) {
4396 ICS.setStandard();
4397 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004399 : ObjCConversion? ICK_Compatible_Conversion
4400 : ICK_Identity;
4401 ICS.Standard.Third = ICK_Identity;
4402 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4403 ICS.Standard.setToType(0, T2);
4404 ICS.Standard.setToType(1, T1);
4405 ICS.Standard.setToType(2, T1);
4406 ICS.Standard.ReferenceBinding = true;
4407 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4408 // binding unless we're binding to a class prvalue.
4409 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4410 // allow the use of rvalue references in C++98/03 for the benefit of
4411 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004413 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004414 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004415 ICS.Standard.IsLvalueReference = !isRValRef;
4416 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004418 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004419 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004420 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004421 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424
Douglas Gregorf143cd52011-01-24 16:14:37 +00004425 // -- has a class type (i.e., T2 is a class type), where T1 is not
4426 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427 // an xvalue, class prvalue, or function lvalue of type
4428 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004429 // "cv3 T3",
4430 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004432 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004434 // class subobject).
4435 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004436 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004437 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4438 Init, T2, /*AllowRvalues=*/true,
4439 AllowExplicit)) {
4440 // In the second case, if the reference is an rvalue reference
4441 // and the second standard conversion sequence of the
4442 // user-defined conversion sequence includes an lvalue-to-rvalue
4443 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004445 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4446 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4447
Douglas Gregor95273c32011-01-21 16:36:05 +00004448 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004449 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450
Richard Smith19172c42014-07-14 02:28:44 +00004451 // A temporary of function type cannot be created; don't even try.
4452 if (T1->isFunctionType())
4453 return ICS;
4454
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004455 // -- Otherwise, a temporary of type "cv1 T1" is created and
4456 // initialized from the initializer expression using the
4457 // rules for a non-reference copy initialization (8.5). The
4458 // reference is then bound to the temporary. If T1 is
4459 // reference-related to T2, cv1 must be the same
4460 // cv-qualification as, or greater cv-qualification than,
4461 // cv2; otherwise, the program is ill-formed.
4462 if (RefRelationship == Sema::Ref_Related) {
4463 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4464 // we would be reference-compatible or reference-compatible with
4465 // added qualification. But that wasn't the case, so the reference
4466 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004467 //
4468 // Note that we only want to check address spaces and cvr-qualifiers here.
4469 // ObjC GC and lifetime qualifiers aren't important.
4470 Qualifiers T1Quals = T1.getQualifiers();
4471 Qualifiers T2Quals = T2.getQualifiers();
4472 T1Quals.removeObjCGCAttr();
4473 T1Quals.removeObjCLifetime();
4474 T2Quals.removeObjCGCAttr();
4475 T2Quals.removeObjCLifetime();
4476 if (!T1Quals.compatiblyIncludes(T2Quals))
4477 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004478 }
4479
4480 // If at least one of the types is a class type, the types are not
4481 // related, and we aren't allowed any user conversions, the
4482 // reference binding fails. This case is important for breaking
4483 // recursion, since TryImplicitConversion below will attempt to
4484 // create a temporary through the use of a copy constructor.
4485 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4486 (T1->isRecordType() || T2->isRecordType()))
4487 return ICS;
4488
Douglas Gregorcba72b12011-01-21 05:18:22 +00004489 // If T1 is reference-related to T2 and the reference is an rvalue
4490 // reference, the initializer expression shall not be an lvalue.
4491 if (RefRelationship >= Sema::Ref_Related &&
4492 isRValRef && Init->Classify(S.Context).isLValue())
4493 return ICS;
4494
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004495 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004496 // When a parameter of reference type is not bound directly to
4497 // an argument expression, the conversion sequence is the one
4498 // required to convert the argument expression to the
4499 // underlying type of the reference according to
4500 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4501 // to copy-initializing a temporary of the underlying type with
4502 // the argument expression. Any difference in top-level
4503 // cv-qualification is subsumed by the initialization itself
4504 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004505 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4506 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004507 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004508 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004509 /*AllowObjCWritebackConversion=*/false,
4510 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004511
4512 // Of course, that's still a reference binding.
4513 if (ICS.isStandard()) {
4514 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004515 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004516 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004517 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004518 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004519 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004520 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004521 const ReferenceType *LValRefType =
4522 ICS.UserDefined.ConversionFunction->getReturnType()
4523 ->getAs<LValueReferenceType>();
4524
4525 // C++ [over.ics.ref]p3:
4526 // Except for an implicit object parameter, for which see 13.3.1, a
4527 // standard conversion sequence cannot be formed if it requires [...]
4528 // binding an rvalue reference to an lvalue other than a function
4529 // lvalue.
4530 // Note that the function case is not possible here.
4531 if (DeclType->isRValueReferenceType() && LValRefType) {
4532 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4533 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4534 // reference to an rvalue!
4535 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4536 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004537 }
Richard Smith19172c42014-07-14 02:28:44 +00004538
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004539 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004540 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004541 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004542 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4543 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004544 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4545 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004546 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004547
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004548 return ICS;
4549}
4550
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004551static ImplicitConversionSequence
4552TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4553 bool SuppressUserConversions,
4554 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004555 bool AllowObjCWritebackConversion,
4556 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004557
4558/// TryListConversion - Try to copy-initialize a value of type ToType from the
4559/// initializer list From.
4560static ImplicitConversionSequence
4561TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4562 bool SuppressUserConversions,
4563 bool InOverloadResolution,
4564 bool AllowObjCWritebackConversion) {
4565 // C++11 [over.ics.list]p1:
4566 // When an argument is an initializer list, it is not an expression and
4567 // special rules apply for converting it to a parameter type.
4568
4569 ImplicitConversionSequence Result;
4570 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4571
Sebastian Redl09edce02012-01-23 22:09:39 +00004572 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004573 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004574 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004575 return Result;
4576
Larisse Voufo19d08672015-01-27 18:47:05 +00004577 // Per DR1467:
4578 // If the parameter type is a class X and the initializer list has a single
4579 // element of type cv U, where U is X or a class derived from X, the
4580 // implicit conversion sequence is the one required to convert the element
4581 // to the parameter type.
4582 //
4583 // Otherwise, if the parameter type is a character array [... ]
4584 // and the initializer list has a single element that is an
4585 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4586 // implicit conversion sequence is the identity conversion.
4587 if (From->getNumInits() == 1) {
4588 if (ToType->isRecordType()) {
4589 QualType InitType = From->getInit(0)->getType();
4590 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004591 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004592 return TryCopyInitialization(S, From->getInit(0), ToType,
4593 SuppressUserConversions,
4594 InOverloadResolution,
4595 AllowObjCWritebackConversion);
4596 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004597 // FIXME: Check the other conditions here: array of character type,
4598 // initializer is a string literal.
4599 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004600 InitializedEntity Entity =
4601 InitializedEntity::InitializeParameter(S.Context, ToType,
4602 /*Consumed=*/false);
4603 if (S.CanPerformCopyInitialization(Entity, From)) {
4604 Result.setStandard();
4605 Result.Standard.setAsIdentityConversion();
4606 Result.Standard.setFromType(ToType);
4607 Result.Standard.setAllToTypes(ToType);
4608 return Result;
4609 }
4610 }
4611 }
4612
4613 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004614 // C++11 [over.ics.list]p2:
4615 // If the parameter type is std::initializer_list<X> or "array of X" and
4616 // all the elements can be implicitly converted to X, the implicit
4617 // conversion sequence is the worst conversion necessary to convert an
4618 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004619 //
4620 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004621 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004622 // list has exactly N elements or if it has fewer than N elements and X is
4623 // default-constructible, and if all the elements of the initializer list
4624 // can be implicitly converted to X, the implicit conversion sequence is
4625 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004626 //
4627 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004628 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004629 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004630 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004631 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004632 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004633 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004634 if (!X.isNull()) {
4635 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4636 Expr *Init = From->getInit(i);
4637 ImplicitConversionSequence ICS =
4638 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4639 InOverloadResolution,
4640 AllowObjCWritebackConversion);
4641 // If a single element isn't convertible, fail.
4642 if (ICS.isBad()) {
4643 Result = ICS;
4644 break;
4645 }
4646 // Otherwise, look for the worst conversion.
4647 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004648 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4649 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004650 ImplicitConversionSequence::Worse)
4651 Result = ICS;
4652 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004653
4654 // For an empty list, we won't have computed any conversion sequence.
4655 // Introduce the identity conversion sequence.
4656 if (From->getNumInits() == 0) {
4657 Result.setStandard();
4658 Result.Standard.setAsIdentityConversion();
4659 Result.Standard.setFromType(ToType);
4660 Result.Standard.setAllToTypes(ToType);
4661 }
4662
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004663 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004664 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004665 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004666
Larisse Voufo19d08672015-01-27 18:47:05 +00004667 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004668 // C++11 [over.ics.list]p3:
4669 // Otherwise, if the parameter is a non-aggregate class X and overload
4670 // resolution chooses a single best constructor [...] the implicit
4671 // conversion sequence is a user-defined conversion sequence. If multiple
4672 // constructors are viable but none is better than the others, the
4673 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004674 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4675 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004676 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4677 /*AllowExplicit=*/false,
4678 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004679 AllowObjCWritebackConversion,
4680 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004681 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004682
Larisse Voufo19d08672015-01-27 18:47:05 +00004683 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004684 // C++11 [over.ics.list]p4:
4685 // Otherwise, if the parameter has an aggregate type which can be
4686 // initialized from the initializer list [...] the implicit conversion
4687 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004688 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004689 // Type is an aggregate, argument is an init list. At this point it comes
4690 // down to checking whether the initialization works.
4691 // FIXME: Find out whether this parameter is consumed or not.
4692 InitializedEntity Entity =
4693 InitializedEntity::InitializeParameter(S.Context, ToType,
4694 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004695 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004696 Result.setUserDefined();
4697 Result.UserDefined.Before.setAsIdentityConversion();
4698 // Initializer lists don't have a type.
4699 Result.UserDefined.Before.setFromType(QualType());
4700 Result.UserDefined.Before.setAllToTypes(QualType());
4701
4702 Result.UserDefined.After.setAsIdentityConversion();
4703 Result.UserDefined.After.setFromType(ToType);
4704 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004705 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004706 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004707 return Result;
4708 }
4709
Larisse Voufo19d08672015-01-27 18:47:05 +00004710 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004711 // C++11 [over.ics.list]p5:
4712 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004713 if (ToType->isReferenceType()) {
4714 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4715 // mention initializer lists in any way. So we go by what list-
4716 // initialization would do and try to extrapolate from that.
4717
4718 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4719
4720 // If the initializer list has a single element that is reference-related
4721 // to the parameter type, we initialize the reference from that.
4722 if (From->getNumInits() == 1) {
4723 Expr *Init = From->getInit(0);
4724
4725 QualType T2 = Init->getType();
4726
4727 // If the initializer is the address of an overloaded function, try
4728 // to resolve the overloaded function. If all goes well, T2 is the
4729 // type of the resulting function.
4730 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4731 DeclAccessPair Found;
4732 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4733 Init, ToType, false, Found))
4734 T2 = Fn->getType();
4735 }
4736
4737 // Compute some basic properties of the types and the initializer.
4738 bool dummy1 = false;
4739 bool dummy2 = false;
4740 bool dummy3 = false;
4741 Sema::ReferenceCompareResult RefRelationship
4742 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4743 dummy2, dummy3);
4744
Richard Smith4d2bbd72013-09-06 01:22:42 +00004745 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004746 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4747 SuppressUserConversions,
4748 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004749 }
Sebastian Redldf888642011-12-03 14:54:30 +00004750 }
4751
4752 // Otherwise, we bind the reference to a temporary created from the
4753 // initializer list.
4754 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4755 InOverloadResolution,
4756 AllowObjCWritebackConversion);
4757 if (Result.isFailure())
4758 return Result;
4759 assert(!Result.isEllipsis() &&
4760 "Sub-initialization cannot result in ellipsis conversion.");
4761
4762 // Can we even bind to a temporary?
4763 if (ToType->isRValueReferenceType() ||
4764 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4765 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4766 Result.UserDefined.After;
4767 SCS.ReferenceBinding = true;
4768 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4769 SCS.BindsToRvalue = true;
4770 SCS.BindsToFunctionLvalue = false;
4771 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4772 SCS.ObjCLifetimeConversionBinding = false;
4773 } else
4774 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4775 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004776 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004777 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004778
Larisse Voufo19d08672015-01-27 18:47:05 +00004779 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004780 // C++11 [over.ics.list]p6:
4781 // Otherwise, if the parameter type is not a class:
4782 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004783 // - if the initializer list has one element that is not itself an
4784 // initializer list, the implicit conversion sequence is the one
4785 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004786 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004787 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004788 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4789 SuppressUserConversions,
4790 InOverloadResolution,
4791 AllowObjCWritebackConversion);
4792 // - if the initializer list has no elements, the implicit conversion
4793 // sequence is the identity conversion.
4794 else if (NumInits == 0) {
4795 Result.setStandard();
4796 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004797 Result.Standard.setFromType(ToType);
4798 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004799 }
4800 return Result;
4801 }
4802
Larisse Voufo19d08672015-01-27 18:47:05 +00004803 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004804 // C++11 [over.ics.list]p7:
4805 // In all cases other than those enumerated above, no conversion is possible
4806 return Result;
4807}
4808
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004809/// TryCopyInitialization - Try to copy-initialize a value of type
4810/// ToType from the expression From. Return the implicit conversion
4811/// sequence required to pass this argument, which may be a bad
4812/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004813/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004814/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004815static ImplicitConversionSequence
4816TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004818 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004819 bool AllowObjCWritebackConversion,
4820 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004821 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4822 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4823 InOverloadResolution,AllowObjCWritebackConversion);
4824
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004825 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004826 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004827 /*FIXME:*/From->getLocStart(),
4828 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004829 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004830
John McCall5c32be02010-08-24 20:38:10 +00004831 return TryImplicitConversion(S, From, ToType,
4832 SuppressUserConversions,
4833 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004834 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004835 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004836 AllowObjCWritebackConversion,
4837 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004838}
4839
Anna Zaks1b068122011-07-28 19:46:48 +00004840static bool TryCopyInitialization(const CanQualType FromQTy,
4841 const CanQualType ToQTy,
4842 Sema &S,
4843 SourceLocation Loc,
4844 ExprValueKind FromVK) {
4845 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4846 ImplicitConversionSequence ICS =
4847 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4848
4849 return !ICS.isBad();
4850}
4851
Douglas Gregor436424c2008-11-18 23:14:02 +00004852/// TryObjectArgumentInitialization - Try to initialize the object
4853/// parameter of the given member function (@c Method) from the
4854/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004855static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004856TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004857 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004858 CXXMethodDecl *Method,
4859 CXXRecordDecl *ActingContext) {
4860 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004861 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4862 // const volatile object.
4863 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4864 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004865 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004866
4867 // Set up the conversion sequence as a "bad" conversion, to allow us
4868 // to exit early.
4869 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004870
4871 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004872 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004873 FromType = PT->getPointeeType();
4874
Douglas Gregor02824322011-01-26 19:30:28 +00004875 // When we had a pointer, it's implicitly dereferenced, so we
4876 // better have an lvalue.
4877 assert(FromClassification.isLValue());
4878 }
4879
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004880 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004881
Douglas Gregor02824322011-01-26 19:30:28 +00004882 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004884 // parameter is
4885 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004886 // - "lvalue reference to cv X" for functions declared without a
4887 // ref-qualifier or with the & ref-qualifier
4888 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004889 // ref-qualifier
4890 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004892 // cv-qualification on the member function declaration.
4893 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004895 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004896 // (C++ [over.match.funcs]p5). We perform a simplified version of
4897 // reference binding here, that allows class rvalues to bind to
4898 // non-constant references.
4899
Douglas Gregor02824322011-01-26 19:30:28 +00004900 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004901 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004903 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004904 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004905 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004906 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004907 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004908 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004909
4910 // Check that we have either the same type or a derived type. It
4911 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004912 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004913 ImplicitConversionKind SecondKind;
4914 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4915 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004916 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004917 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004918 else {
John McCall65eb8792010-02-25 01:37:24 +00004919 ICS.setBad(BadConversionSequence::unrelated_class,
4920 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004921 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004922 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004923
Douglas Gregor02824322011-01-26 19:30:28 +00004924 // Check the ref-qualifier.
4925 switch (Method->getRefQualifier()) {
4926 case RQ_None:
4927 // Do nothing; we don't care about lvalueness or rvalueness.
4928 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004929
Douglas Gregor02824322011-01-26 19:30:28 +00004930 case RQ_LValue:
4931 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4932 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004934 ImplicitParamType);
4935 return ICS;
4936 }
4937 break;
4938
4939 case RQ_RValue:
4940 if (!FromClassification.isRValue()) {
4941 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004942 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004943 ImplicitParamType);
4944 return ICS;
4945 }
4946 break;
4947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004948
Douglas Gregor436424c2008-11-18 23:14:02 +00004949 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004950 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004951 ICS.Standard.setAsIdentityConversion();
4952 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004953 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004954 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004955 ICS.Standard.ReferenceBinding = true;
4956 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004957 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004958 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004959 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4960 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4961 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004962 return ICS;
4963}
4964
4965/// PerformObjectArgumentInitialization - Perform initialization of
4966/// the implicit object parameter for the given Method with the given
4967/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004968ExprResult
4969Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004971 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004972 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004973 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004974 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004975 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004976
Douglas Gregor02824322011-01-26 19:30:28 +00004977 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004978 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004979 FromRecordType = PT->getPointeeType();
4980 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004981 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004982 } else {
4983 FromRecordType = From->getType();
4984 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004985 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004986 }
4987
John McCall6e9f8f62009-12-03 04:06:58 +00004988 // Note that we always use the true parent context when performing
4989 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004990 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00004991 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4992 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004993 if (ICS.isBad()) {
4994 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4995 Qualifiers FromQs = FromRecordType.getQualifiers();
4996 Qualifiers ToQs = DestType.getQualifiers();
4997 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4998 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004999 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005000 diag::err_member_function_call_bad_cvr)
5001 << Method->getDeclName() << FromRecordType << (CVR - 1)
5002 << From->getSourceRange();
5003 Diag(Method->getLocation(), diag::note_previous_decl)
5004 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005005 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005006 }
5007 }
5008
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005009 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005010 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005011 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005012 }
Mike Stump11289f42009-09-09 15:08:12 +00005013
John Wiegley01296292011-04-08 18:41:53 +00005014 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5015 ExprResult FromRes =
5016 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5017 if (FromRes.isInvalid())
5018 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005019 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005020 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005021
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005022 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005023 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005024 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005025 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005026}
5027
Douglas Gregor5fb53972009-01-14 15:45:31 +00005028/// TryContextuallyConvertToBool - Attempt to contextually convert the
5029/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005030static ImplicitConversionSequence
5031TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005032 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005033 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005034 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005035 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005036 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005037 /*AllowObjCWritebackConversion=*/false,
5038 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005039}
5040
5041/// PerformContextuallyConvertToBool - Perform a contextual conversion
5042/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005043ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005044 if (checkPlaceholderForOverload(*this, From))
5045 return ExprError();
5046
John McCall5c32be02010-08-24 20:38:10 +00005047 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005048 if (!ICS.isBad())
5049 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005050
Fariborz Jahanian76197412009-11-18 18:26:29 +00005051 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005052 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005053 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005054 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005055 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005056}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057
Richard Smithf8379a02012-01-18 23:55:52 +00005058/// Check that the specified conversion is permitted in a converted constant
5059/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5060/// is acceptable.
5061static bool CheckConvertedConstantConversions(Sema &S,
5062 StandardConversionSequence &SCS) {
5063 // Since we know that the target type is an integral or unscoped enumeration
5064 // type, most conversion kinds are impossible. All possible First and Third
5065 // conversions are fine.
5066 switch (SCS.Second) {
5067 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005068 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005069 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005070 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005071 return true;
5072
5073 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005074 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005075 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5076 // conversion, so we allow it in a converted constant expression.
5077 //
5078 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5079 // a lot of popular code. We should at least add a warning for this
5080 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005081 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5082 SCS.getToType(2)->isBooleanType();
5083
Richard Smith410cc892014-11-26 03:26:53 +00005084 case ICK_Pointer_Conversion:
5085 case ICK_Pointer_Member:
5086 // C++1z: null pointer conversions and null member pointer conversions are
5087 // only permitted if the source type is std::nullptr_t.
5088 return SCS.getFromType()->isNullPtrType();
5089
5090 case ICK_Floating_Promotion:
5091 case ICK_Complex_Promotion:
5092 case ICK_Floating_Conversion:
5093 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005094 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005095 case ICK_Compatible_Conversion:
5096 case ICK_Derived_To_Base:
5097 case ICK_Vector_Conversion:
5098 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005099 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005100 case ICK_Block_Pointer_Conversion:
5101 case ICK_TransparentUnionConversion:
5102 case ICK_Writeback_Conversion:
5103 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005104 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005105 return false;
5106
5107 case ICK_Lvalue_To_Rvalue:
5108 case ICK_Array_To_Pointer:
5109 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005110 llvm_unreachable("found a first conversion kind in Second");
5111
Richard Smithf8379a02012-01-18 23:55:52 +00005112 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005113 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005114
5115 case ICK_Num_Conversion_Kinds:
5116 break;
5117 }
5118
5119 llvm_unreachable("unknown conversion kind");
5120}
5121
5122/// CheckConvertedConstantExpression - Check that the expression From is a
5123/// converted constant expression of type T, perform the conversion and produce
5124/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005125static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5126 QualType T, APValue &Value,
5127 Sema::CCEKind CCE,
5128 bool RequireInt) {
5129 assert(S.getLangOpts().CPlusPlus11 &&
5130 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005131
Richard Smith410cc892014-11-26 03:26:53 +00005132 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005133 return ExprError();
5134
Richard Smith410cc892014-11-26 03:26:53 +00005135 // C++1z [expr.const]p3:
5136 // A converted constant expression of type T is an expression,
5137 // implicitly converted to type T, where the converted
5138 // expression is a constant expression and the implicit conversion
5139 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005140 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005141 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005142 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005143 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005144 /*AllowObjcWritebackConversion=*/false,
5145 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005146 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005147 switch (ICS.getKind()) {
5148 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005149 SCS = &ICS.Standard;
5150 break;
5151 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005152 // We are converting to a non-class type, so the Before sequence
5153 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005154 SCS = &ICS.UserDefined.After;
5155 break;
5156 case ImplicitConversionSequence::AmbiguousConversion:
5157 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005158 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5159 return S.Diag(From->getLocStart(),
5160 diag::err_typecheck_converted_constant_expression)
5161 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005162 return ExprError();
5163
5164 case ImplicitConversionSequence::EllipsisConversion:
5165 llvm_unreachable("ellipsis conversion in converted constant expression");
5166 }
5167
Richard Smith410cc892014-11-26 03:26:53 +00005168 // Check that we would only use permitted conversions.
5169 if (!CheckConvertedConstantConversions(S, *SCS)) {
5170 return S.Diag(From->getLocStart(),
5171 diag::err_typecheck_converted_constant_expression_disallowed)
5172 << From->getType() << From->getSourceRange() << T;
5173 }
5174 // [...] and where the reference binding (if any) binds directly.
5175 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5176 return S.Diag(From->getLocStart(),
5177 diag::err_typecheck_converted_constant_expression_indirect)
5178 << From->getType() << From->getSourceRange() << T;
5179 }
5180
5181 ExprResult Result =
5182 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005183 if (Result.isInvalid())
5184 return Result;
5185
5186 // Check for a narrowing implicit conversion.
5187 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005188 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005189 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005190 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005191 case NK_Variable_Narrowing:
5192 // Implicit conversion to a narrower type, and the value is not a constant
5193 // expression. We'll diagnose this in a moment.
5194 case NK_Not_Narrowing:
5195 break;
5196
5197 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005198 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005199 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005200 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005201 break;
5202
5203 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005204 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005205 << CCE << /*Constant*/0 << From->getType() << T;
5206 break;
5207 }
5208
5209 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005210 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005211 Expr::EvalResult Eval;
5212 Eval.Diag = &Notes;
5213
Richard Smith410cc892014-11-26 03:26:53 +00005214 if ((T->isReferenceType()
5215 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5216 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5217 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005218 // The expression can't be folded, so we can't keep it at this position in
5219 // the AST.
5220 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005221 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005222 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005223
5224 if (Notes.empty()) {
5225 // It's a constant expression.
5226 return Result;
5227 }
Richard Smithf8379a02012-01-18 23:55:52 +00005228 }
5229
5230 // It's not a constant expression. Produce an appropriate diagnostic.
5231 if (Notes.size() == 1 &&
5232 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005233 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005234 else {
Richard Smith410cc892014-11-26 03:26:53 +00005235 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005236 << CCE << From->getSourceRange();
5237 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005238 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005239 }
Richard Smith410cc892014-11-26 03:26:53 +00005240 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005241}
5242
Richard Smith410cc892014-11-26 03:26:53 +00005243ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5244 APValue &Value, CCEKind CCE) {
5245 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5246}
5247
5248ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5249 llvm::APSInt &Value,
5250 CCEKind CCE) {
5251 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5252
5253 APValue V;
5254 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5255 if (!R.isInvalid())
5256 Value = V.getInt();
5257 return R;
5258}
5259
5260
John McCallfec112d2011-09-09 06:11:02 +00005261/// dropPointerConversions - If the given standard conversion sequence
5262/// involves any pointer conversions, remove them. This may change
5263/// the result type of the conversion sequence.
5264static void dropPointerConversion(StandardConversionSequence &SCS) {
5265 if (SCS.Second == ICK_Pointer_Conversion) {
5266 SCS.Second = ICK_Identity;
5267 SCS.Third = ICK_Identity;
5268 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5269 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005270}
John McCall5c32be02010-08-24 20:38:10 +00005271
John McCallfec112d2011-09-09 06:11:02 +00005272/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5273/// convert the expression From to an Objective-C pointer type.
5274static ImplicitConversionSequence
5275TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5276 // Do an implicit conversion to 'id'.
5277 QualType Ty = S.Context.getObjCIdType();
5278 ImplicitConversionSequence ICS
5279 = TryImplicitConversion(S, From, Ty,
5280 // FIXME: Are these flags correct?
5281 /*SuppressUserConversions=*/false,
5282 /*AllowExplicit=*/true,
5283 /*InOverloadResolution=*/false,
5284 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005285 /*AllowObjCWritebackConversion=*/false,
5286 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005287
5288 // Strip off any final conversions to 'id'.
5289 switch (ICS.getKind()) {
5290 case ImplicitConversionSequence::BadConversion:
5291 case ImplicitConversionSequence::AmbiguousConversion:
5292 case ImplicitConversionSequence::EllipsisConversion:
5293 break;
5294
5295 case ImplicitConversionSequence::UserDefinedConversion:
5296 dropPointerConversion(ICS.UserDefined.After);
5297 break;
5298
5299 case ImplicitConversionSequence::StandardConversion:
5300 dropPointerConversion(ICS.Standard);
5301 break;
5302 }
5303
5304 return ICS;
5305}
5306
5307/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5308/// conversion of the expression From to an Objective-C pointer type.
5309ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005310 if (checkPlaceholderForOverload(*this, From))
5311 return ExprError();
5312
John McCall8b07ec22010-05-15 11:32:37 +00005313 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005314 ImplicitConversionSequence ICS =
5315 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005316 if (!ICS.isBad())
5317 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005318 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005319}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005320
Richard Smith8dd34252012-02-04 07:07:42 +00005321/// Determine whether the provided type is an integral type, or an enumeration
5322/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005323bool Sema::ICEConvertDiagnoser::match(QualType T) {
5324 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5325 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005326}
5327
Larisse Voufo236bec22013-06-10 06:50:24 +00005328static ExprResult
5329diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5330 Sema::ContextualImplicitConverter &Converter,
5331 QualType T, UnresolvedSetImpl &ViableConversions) {
5332
5333 if (Converter.Suppress)
5334 return ExprError();
5335
5336 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5337 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5338 CXXConversionDecl *Conv =
5339 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5340 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5341 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5342 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005343 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005344}
5345
5346static bool
5347diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5348 Sema::ContextualImplicitConverter &Converter,
5349 QualType T, bool HadMultipleCandidates,
5350 UnresolvedSetImpl &ExplicitConversions) {
5351 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5352 DeclAccessPair Found = ExplicitConversions[0];
5353 CXXConversionDecl *Conversion =
5354 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5355
5356 // The user probably meant to invoke the given explicit
5357 // conversion; use it.
5358 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5359 std::string TypeStr;
5360 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5361
5362 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5363 << FixItHint::CreateInsertion(From->getLocStart(),
5364 "static_cast<" + TypeStr + ">(")
5365 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005366 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005367 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5368
5369 // If we aren't in a SFINAE context, build a call to the
5370 // explicit conversion function.
5371 if (SemaRef.isSFINAEContext())
5372 return true;
5373
Craig Topperc3ec1492014-05-26 06:22:03 +00005374 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005375 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5376 HadMultipleCandidates);
5377 if (Result.isInvalid())
5378 return true;
5379 // Record usage of conversion in an implicit cast.
5380 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005381 CK_UserDefinedConversion, Result.get(),
5382 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005383 }
5384 return false;
5385}
5386
5387static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5388 Sema::ContextualImplicitConverter &Converter,
5389 QualType T, bool HadMultipleCandidates,
5390 DeclAccessPair &Found) {
5391 CXXConversionDecl *Conversion =
5392 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005393 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005394
5395 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5396 if (!Converter.SuppressConversion) {
5397 if (SemaRef.isSFINAEContext())
5398 return true;
5399
5400 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5401 << From->getSourceRange();
5402 }
5403
5404 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5405 HadMultipleCandidates);
5406 if (Result.isInvalid())
5407 return true;
5408 // Record usage of conversion in an implicit cast.
5409 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005410 CK_UserDefinedConversion, Result.get(),
5411 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005412 return false;
5413}
5414
5415static ExprResult finishContextualImplicitConversion(
5416 Sema &SemaRef, SourceLocation Loc, Expr *From,
5417 Sema::ContextualImplicitConverter &Converter) {
5418 if (!Converter.match(From->getType()) && !Converter.Suppress)
5419 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5420 << From->getSourceRange();
5421
5422 return SemaRef.DefaultLvalueConversion(From);
5423}
5424
5425static void
5426collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5427 UnresolvedSetImpl &ViableConversions,
5428 OverloadCandidateSet &CandidateSet) {
5429 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5430 DeclAccessPair FoundDecl = ViableConversions[I];
5431 NamedDecl *D = FoundDecl.getDecl();
5432 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5433 if (isa<UsingShadowDecl>(D))
5434 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5435
5436 CXXConversionDecl *Conv;
5437 FunctionTemplateDecl *ConvTemplate;
5438 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5439 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5440 else
5441 Conv = cast<CXXConversionDecl>(D);
5442
5443 if (ConvTemplate)
5444 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005445 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5446 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005447 else
5448 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005449 ToType, CandidateSet,
5450 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005451 }
5452}
5453
Richard Smithccc11812013-05-21 19:05:48 +00005454/// \brief Attempt to convert the given expression to a type which is accepted
5455/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005456///
Richard Smithccc11812013-05-21 19:05:48 +00005457/// This routine will attempt to convert an expression of class type to a
5458/// type accepted by the specified converter. In C++11 and before, the class
5459/// must have a single non-explicit conversion function converting to a matching
5460/// type. In C++1y, there can be multiple such conversion functions, but only
5461/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005462///
Douglas Gregor4799d032010-06-30 00:20:43 +00005463/// \param Loc The source location of the construct that requires the
5464/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005465///
James Dennett18348b62012-06-22 08:52:37 +00005466/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005467///
Richard Smithccc11812013-05-21 19:05:48 +00005468/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005469///
Douglas Gregor4799d032010-06-30 00:20:43 +00005470/// \returns The expression, converted to an integral or enumeration type if
5471/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005472ExprResult Sema::PerformContextualImplicitConversion(
5473 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005474 // We can't perform any more checking for type-dependent expressions.
5475 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005476 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005477
Eli Friedman1da70392012-01-26 00:26:18 +00005478 // Process placeholders immediately.
5479 if (From->hasPlaceholderType()) {
5480 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005481 if (result.isInvalid())
5482 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005483 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005484 }
5485
Richard Smithccc11812013-05-21 19:05:48 +00005486 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005487 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005488 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005489 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005490
5491 // FIXME: Check for missing '()' if T is a function type?
5492
Richard Smithccc11812013-05-21 19:05:48 +00005493 // We can only perform contextual implicit conversions on objects of class
5494 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005495 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005496 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005497 if (!Converter.Suppress)
5498 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005499 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005502 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005503 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005504 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005505 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005506
5507 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005508 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005509
Craig Toppere14c0f82014-03-12 04:55:44 +00005510 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005511 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005512 }
Richard Smithccc11812013-05-21 19:05:48 +00005513 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005514
Richard Smithdb0ac552015-12-18 22:40:25 +00005515 if (Converter.Suppress ? !isCompleteType(Loc, T)
5516 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005517 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005519 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005520 UnresolvedSet<4>
5521 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005522 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005523 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005524 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525
Larisse Voufo236bec22013-06-10 06:50:24 +00005526 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005527 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005528
Larisse Voufo236bec22013-06-10 06:50:24 +00005529 // To check that there is only one target type, in C++1y:
5530 QualType ToType;
5531 bool HasUniqueTargetType = true;
5532
5533 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005534 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005535 NamedDecl *D = (*I)->getUnderlyingDecl();
5536 CXXConversionDecl *Conversion;
5537 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5538 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005539 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005540 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5541 else
5542 continue; // C++11 does not consider conversion operator templates(?).
5543 } else
5544 Conversion = cast<CXXConversionDecl>(D);
5545
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005546 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005547 "Conversion operator templates are considered potentially "
5548 "viable in C++1y");
5549
5550 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5551 if (Converter.match(CurToType) || ConvTemplate) {
5552
5553 if (Conversion->isExplicit()) {
5554 // FIXME: For C++1y, do we need this restriction?
5555 // cf. diagnoseNoViableConversion()
5556 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005557 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005558 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005559 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005560 if (ToType.isNull())
5561 ToType = CurToType.getUnqualifiedType();
5562 else if (HasUniqueTargetType &&
5563 (CurToType.getUnqualifiedType() != ToType))
5564 HasUniqueTargetType = false;
5565 }
5566 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005567 }
Richard Smith8dd34252012-02-04 07:07:42 +00005568 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005570
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005571 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005572 // C++1y [conv]p6:
5573 // ... An expression e of class type E appearing in such a context
5574 // is said to be contextually implicitly converted to a specified
5575 // type T and is well-formed if and only if e can be implicitly
5576 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005577 // for conversion functions whose return type is cv T or reference to
5578 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005579 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580
Larisse Voufo236bec22013-06-10 06:50:24 +00005581 // If no unique T is found:
5582 if (ToType.isNull()) {
5583 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5584 HadMultipleCandidates,
5585 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005586 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005587 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005589
Larisse Voufo236bec22013-06-10 06:50:24 +00005590 // If more than one unique Ts are found:
5591 if (!HasUniqueTargetType)
5592 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5593 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005594
Larisse Voufo236bec22013-06-10 06:50:24 +00005595 // If one unique T is found:
5596 // First, build a candidate set from the previously recorded
5597 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005598 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005599 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5600 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601
Larisse Voufo236bec22013-06-10 06:50:24 +00005602 // Then, perform overload resolution over the candidate set.
5603 OverloadCandidateSet::iterator Best;
5604 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5605 case OR_Success: {
5606 // Apply this conversion.
5607 DeclAccessPair Found =
5608 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5609 if (recordConversion(*this, Loc, From, Converter, T,
5610 HadMultipleCandidates, Found))
5611 return ExprError();
5612 break;
5613 }
5614 case OR_Ambiguous:
5615 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5616 ViableConversions);
5617 case OR_No_Viable_Function:
5618 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5619 HadMultipleCandidates,
5620 ExplicitConversions))
5621 return ExprError();
5622 // fall through 'OR_Deleted' case.
5623 case OR_Deleted:
5624 // We'll complain below about a non-integral condition type.
5625 break;
5626 }
5627 } else {
5628 switch (ViableConversions.size()) {
5629 case 0: {
5630 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5631 HadMultipleCandidates,
5632 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005633 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634
Larisse Voufo236bec22013-06-10 06:50:24 +00005635 // We'll complain below about a non-integral condition type.
5636 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005637 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005638 case 1: {
5639 // Apply this conversion.
5640 DeclAccessPair Found = ViableConversions[0];
5641 if (recordConversion(*this, Loc, From, Converter, T,
5642 HadMultipleCandidates, Found))
5643 return ExprError();
5644 break;
5645 }
5646 default:
5647 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5648 ViableConversions);
5649 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005650 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005651
Larisse Voufo236bec22013-06-10 06:50:24 +00005652 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005653}
5654
Richard Smith100b24a2014-04-17 01:52:14 +00005655/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5656/// an acceptable non-member overloaded operator for a call whose
5657/// arguments have types T1 (and, if non-empty, T2). This routine
5658/// implements the check in C++ [over.match.oper]p3b2 concerning
5659/// enumeration types.
5660static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5661 FunctionDecl *Fn,
5662 ArrayRef<Expr *> Args) {
5663 QualType T1 = Args[0]->getType();
5664 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5665
5666 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5667 return true;
5668
5669 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5670 return true;
5671
5672 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5673 if (Proto->getNumParams() < 1)
5674 return false;
5675
5676 if (T1->isEnumeralType()) {
5677 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5678 if (Context.hasSameUnqualifiedType(T1, ArgType))
5679 return true;
5680 }
5681
5682 if (Proto->getNumParams() < 2)
5683 return false;
5684
5685 if (!T2.isNull() && T2->isEnumeralType()) {
5686 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5687 if (Context.hasSameUnqualifiedType(T2, ArgType))
5688 return true;
5689 }
5690
5691 return false;
5692}
5693
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005694/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005695/// candidate functions, using the given function call arguments. If
5696/// @p SuppressUserConversions, then don't allow user-defined
5697/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005698///
James Dennett2a4d13c2012-06-15 07:13:21 +00005699/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005700/// based on an incomplete set of function arguments. This feature is used by
5701/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005702void
5703Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005704 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005705 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005706 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005707 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005708 bool PartialOverloading,
5709 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005710 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005711 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005712 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005713 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005714 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005715
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005716 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005717 if (!isa<CXXConstructorDecl>(Method)) {
5718 // If we get here, it's because we're calling a member function
5719 // that is named without a member access expression (e.g.,
5720 // "this->f") that was either written explicitly or created
5721 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005722 // function, e.g., X::f(). We use an empty type for the implied
5723 // object argument (C++ [over.call.func]p3), and the acting context
5724 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005725 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005727 Args, CandidateSet, SuppressUserConversions,
5728 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005729 return;
5730 }
5731 // We treat a constructor like a non-member function, since its object
5732 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005733 }
5734
Douglas Gregorff7028a2009-11-13 23:59:09 +00005735 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005736 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005737
Richard Smith100b24a2014-04-17 01:52:14 +00005738 // C++ [over.match.oper]p3:
5739 // if no operand has a class type, only those non-member functions in the
5740 // lookup set that have a first parameter of type T1 or "reference to
5741 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5742 // is a right operand) a second parameter of type T2 or "reference to
5743 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5744 // candidate functions.
5745 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5746 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5747 return;
5748
Richard Smith8b86f2d2013-11-04 01:48:18 +00005749 // C++11 [class.copy]p11: [DR1402]
5750 // A defaulted move constructor that is defined as deleted is ignored by
5751 // overload resolution.
5752 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5753 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5754 Constructor->isMoveConstructor())
5755 return;
5756
Douglas Gregor27381f32009-11-23 12:27:39 +00005757 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005758 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005759
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005760 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005761 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005762 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005763 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005764 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005765 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005766 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005767 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005768
John McCall578a1f82014-12-14 01:46:53 +00005769 if (Constructor) {
5770 // C++ [class.copy]p3:
5771 // A member function template is never instantiated to perform the copy
5772 // of a class object to an object of its class type.
5773 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005774 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005775 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005776 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5777 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005778 Candidate.Viable = false;
5779 Candidate.FailureKind = ovl_fail_illegal_constructor;
5780 return;
5781 }
5782 }
5783
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005784 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005785
5786 // (C++ 13.3.2p2): A candidate function having fewer than m
5787 // parameters is viable only if it has an ellipsis in its parameter
5788 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005789 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005790 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005791 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005792 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005793 return;
5794 }
5795
5796 // (C++ 13.3.2p2): A candidate function having more than m parameters
5797 // is viable only if the (m+1)st parameter has a default argument
5798 // (8.3.6). For the purposes of overload resolution, the
5799 // parameter list is truncated on the right, so that there are
5800 // exactly m parameters.
5801 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005802 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005803 // Not enough arguments.
5804 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005805 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005806 return;
5807 }
5808
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005809 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005810 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005811 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005812 // Skip the check for callers that are implicit members, because in this
5813 // case we may not yet know what the member's target is; the target is
5814 // inferred for the member automatically, based on the bases and fields of
5815 // the class.
5816 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005817 Candidate.Viable = false;
5818 Candidate.FailureKind = ovl_fail_bad_target;
5819 return;
5820 }
5821
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005822 // Determine the implicit conversion sequences for each of the
5823 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005824 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005825 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005826 // (C++ 13.3.2p3): for F to be a viable function, there shall
5827 // exist for each argument an implicit conversion sequence
5828 // (13.3.3.1) that converts that argument to the corresponding
5829 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005830 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005831 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005832 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005833 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005834 /*InOverloadResolution=*/true,
5835 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005836 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005837 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005838 if (Candidate.Conversions[ArgIdx].isBad()) {
5839 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005840 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005841 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005842 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005843 } else {
5844 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5845 // argument for which there is no corresponding parameter is
5846 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005847 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005848 }
5849 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005850
5851 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5852 Candidate.Viable = false;
5853 Candidate.FailureKind = ovl_fail_enable_if;
5854 Candidate.DeductionFailure.Data = FailedAttr;
5855 return;
5856 }
5857}
5858
Manman Rend2a3cd72016-04-07 19:30:20 +00005859ObjCMethodDecl *
5860Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5861 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5862 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005863 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00005864
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005865 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5866 bool Match = true;
5867 ObjCMethodDecl *Method = Methods[b];
5868 unsigned NumNamedArgs = Sel.getNumArgs();
5869 // Method might have more arguments than selector indicates. This is due
5870 // to addition of c-style arguments in method.
5871 if (Method->param_size() > NumNamedArgs)
5872 NumNamedArgs = Method->param_size();
5873 if (Args.size() < NumNamedArgs)
5874 continue;
5875
5876 for (unsigned i = 0; i < NumNamedArgs; i++) {
5877 // We can't do any type-checking on a type-dependent argument.
5878 if (Args[i]->isTypeDependent()) {
5879 Match = false;
5880 break;
5881 }
5882
5883 ParmVarDecl *param = Method->parameters()[i];
5884 Expr *argExpr = Args[i];
5885 assert(argExpr && "SelectBestMethod(): missing expression");
5886
5887 // Strip the unbridged-cast placeholder expression off unless it's
5888 // a consumed argument.
5889 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5890 !param->hasAttr<CFConsumedAttr>())
5891 argExpr = stripARCUnbridgedCast(argExpr);
5892
5893 // If the parameter is __unknown_anytype, move on to the next method.
5894 if (param->getType() == Context.UnknownAnyTy) {
5895 Match = false;
5896 break;
5897 }
George Burgess IV45461812015-10-11 20:13:20 +00005898
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005899 ImplicitConversionSequence ConversionState
5900 = TryCopyInitialization(*this, argExpr, param->getType(),
5901 /*SuppressUserConversions*/false,
5902 /*InOverloadResolution=*/true,
5903 /*AllowObjCWritebackConversion=*/
5904 getLangOpts().ObjCAutoRefCount,
5905 /*AllowExplicit*/false);
5906 if (ConversionState.isBad()) {
5907 Match = false;
5908 break;
5909 }
5910 }
5911 // Promote additional arguments to variadic methods.
5912 if (Match && Method->isVariadic()) {
5913 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5914 if (Args[i]->isTypeDependent()) {
5915 Match = false;
5916 break;
5917 }
5918 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5919 nullptr);
5920 if (Arg.isInvalid()) {
5921 Match = false;
5922 break;
5923 }
5924 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005925 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005926 // Check for extra arguments to non-variadic methods.
5927 if (Args.size() != NumNamedArgs)
5928 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005929 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5930 // Special case when selectors have no argument. In this case, select
5931 // one with the most general result type of 'id'.
5932 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5933 QualType ReturnT = Methods[b]->getReturnType();
5934 if (ReturnT->isObjCIdType())
5935 return Methods[b];
5936 }
5937 }
5938 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005939
5940 if (Match)
5941 return Method;
5942 }
5943 return nullptr;
5944}
5945
George Burgess IV2a6150d2015-10-16 01:17:38 +00005946// specific_attr_iterator iterates over enable_if attributes in reverse, and
5947// enable_if is order-sensitive. As a result, we need to reverse things
5948// sometimes. Size of 4 elements is arbitrary.
5949static SmallVector<EnableIfAttr *, 4>
5950getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5951 SmallVector<EnableIfAttr *, 4> Result;
5952 if (!Function->hasAttrs())
5953 return Result;
5954
5955 const auto &FuncAttrs = Function->getAttrs();
5956 for (Attr *Attr : FuncAttrs)
5957 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5958 Result.push_back(EnableIf);
5959
5960 std::reverse(Result.begin(), Result.end());
5961 return Result;
5962}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005963
5964EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5965 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005966 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5967 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005968 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005969
5970 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005971 SmallVector<Expr *, 16> ConvertedArgs;
5972 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005973 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005974
5975 // Convert the arguments.
George Burgess IVe96abf72016-02-24 22:31:14 +00005976 for (unsigned I = 0, E = Args.size(); I != E; ++I) {
5977 ExprResult R;
5978 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005979 !cast<CXXMethodDecl>(Function)->isStatic() &&
5980 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005981 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00005982 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5983 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005984 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00005985 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5986 Context, Function->getParamDecl(I)),
5987 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005988 }
George Burgess IVe96abf72016-02-24 22:31:14 +00005989
5990 if (R.isInvalid()) {
5991 InitializationFailed = true;
5992 break;
5993 }
5994
5995 ContainsValueDependentExpr |= R.get()->isValueDependent();
5996 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005997 }
5998
5999 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006000 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006001
Nick Lewyckye283c552015-08-25 22:33:16 +00006002 // Push default arguments if needed.
6003 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6004 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6005 ParmVarDecl *P = Function->getParamDecl(i);
6006 ExprResult R = PerformCopyInitialization(
6007 InitializedEntity::InitializeParameter(Context,
6008 Function->getParamDecl(i)),
6009 SourceLocation(),
6010 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6011 : P->getDefaultArg());
6012 if (R.isInvalid()) {
6013 InitializationFailed = true;
6014 break;
6015 }
6016 ContainsValueDependentExpr |= R.get()->isValueDependent();
6017 ConvertedArgs.push_back(R.get());
6018 }
6019
6020 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006021 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006022 }
6023
George Burgess IV2a6150d2015-10-16 01:17:38 +00006024 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006025 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006026 if (EIA->getCond()->isValueDependent()) {
6027 // Don't even try now, we'll examine it after instantiation.
6028 continue;
6029 }
6030
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006031 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006032 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6033 if (!ContainsValueDependentExpr)
6034 return EIA;
6035 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006036 return EIA;
6037 }
6038 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006039 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006040}
6041
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006042/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006043/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006044void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006045 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006046 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006047 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006048 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006049 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006050 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006051 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6052 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006053 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006054 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006055 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006056 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006057 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006058 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006059 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006060 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006061 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006062 } else {
John McCalla0296f72010-03-19 07:35:19 +00006063 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006064 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6065 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006066 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006067 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006068 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006069 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006070 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006071 CandidateSet, SuppressUserConversions,
6072 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006073 else
John McCalla0296f72010-03-19 07:35:19 +00006074 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006075 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006076 CandidateSet, SuppressUserConversions,
6077 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006078 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006079 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006080}
6081
John McCallf0f1cf02009-11-17 07:50:12 +00006082/// AddMethodCandidate - Adds a named decl (which is some kind of
6083/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006084void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006085 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006086 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006087 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006088 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006089 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006090 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006091 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006092
6093 if (isa<UsingShadowDecl>(Decl))
6094 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006095
John McCallf0f1cf02009-11-17 07:50:12 +00006096 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6097 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6098 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006099 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006100 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006101 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006102 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006103 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006104 } else {
John McCalla0296f72010-03-19 07:35:19 +00006105 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006106 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006107 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006108 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006109 }
6110}
6111
Douglas Gregor436424c2008-11-18 23:14:02 +00006112/// AddMethodCandidate - Adds the given C++ member function to the set
6113/// of candidate functions, using the given function call arguments
6114/// and the object argument (@c Object). For example, in a call
6115/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6116/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6117/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006118/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006119void
John McCalla0296f72010-03-19 07:35:19 +00006120Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006121 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006122 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006123 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006124 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006125 bool SuppressUserConversions,
6126 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006127 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006128 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006129 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006130 assert(!isa<CXXConstructorDecl>(Method) &&
6131 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006132
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006133 if (!CandidateSet.isNewCandidate(Method))
6134 return;
6135
Richard Smith8b86f2d2013-11-04 01:48:18 +00006136 // C++11 [class.copy]p23: [DR1402]
6137 // A defaulted move assignment operator that is defined as deleted is
6138 // ignored by overload resolution.
6139 if (Method->isDefaulted() && Method->isDeleted() &&
6140 Method->isMoveAssignmentOperator())
6141 return;
6142
Douglas Gregor27381f32009-11-23 12:27:39 +00006143 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006144 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006145
Douglas Gregor436424c2008-11-18 23:14:02 +00006146 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006147 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006148 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006149 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006150 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006151 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006152 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006153
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006154 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006155
6156 // (C++ 13.3.2p2): A candidate function having fewer than m
6157 // parameters is viable only if it has an ellipsis in its parameter
6158 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006159 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6160 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006161 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006162 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006163 return;
6164 }
6165
6166 // (C++ 13.3.2p2): A candidate function having more than m parameters
6167 // is viable only if the (m+1)st parameter has a default argument
6168 // (8.3.6). For the purposes of overload resolution, the
6169 // parameter list is truncated on the right, so that there are
6170 // exactly m parameters.
6171 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006172 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006173 // Not enough arguments.
6174 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006175 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006176 return;
6177 }
6178
6179 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006180
John McCall6e9f8f62009-12-03 04:06:58 +00006181 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006182 // The implicit object argument is ignored.
6183 Candidate.IgnoreObjectArgument = true;
6184 else {
6185 // Determine the implicit conversion sequence for the object
6186 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006187 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6188 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6189 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006190 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006191 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006192 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006193 return;
6194 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006195 }
6196
Eli Bendersky291a57e2014-09-25 23:59:08 +00006197 // (CUDA B.1): Check for invalid calls between targets.
6198 if (getLangOpts().CUDA)
6199 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6200 if (CheckCUDATarget(Caller, Method)) {
6201 Candidate.Viable = false;
6202 Candidate.FailureKind = ovl_fail_bad_target;
6203 return;
6204 }
6205
Douglas Gregor436424c2008-11-18 23:14:02 +00006206 // Determine the implicit conversion sequences for each of the
6207 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006208 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006209 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006210 // (C++ 13.3.2p3): for F to be a viable function, there shall
6211 // exist for each argument an implicit conversion sequence
6212 // (13.3.3.1) that converts that argument to the corresponding
6213 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006214 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006215 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006216 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006217 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006218 /*InOverloadResolution=*/true,
6219 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006220 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006221 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006222 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006223 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006224 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006225 }
6226 } else {
6227 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6228 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006229 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006230 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006231 }
6232 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006233
6234 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6235 Candidate.Viable = false;
6236 Candidate.FailureKind = ovl_fail_enable_if;
6237 Candidate.DeductionFailure.Data = FailedAttr;
6238 return;
6239 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006240}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006241
Douglas Gregor97628d62009-08-21 00:16:32 +00006242/// \brief Add a C++ member function template as a candidate to the candidate
6243/// set, using template argument deduction to produce an appropriate member
6244/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006245void
Douglas Gregor97628d62009-08-21 00:16:32 +00006246Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006247 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006248 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006249 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006250 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006251 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006252 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006253 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006254 bool SuppressUserConversions,
6255 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006256 if (!CandidateSet.isNewCandidate(MethodTmpl))
6257 return;
6258
Douglas Gregor97628d62009-08-21 00:16:32 +00006259 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006260 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006261 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006262 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006263 // candidate functions in the usual way.113) A given name can refer to one
6264 // or more function templates and also to a set of overloaded non-template
6265 // functions. In such a case, the candidate functions generated from each
6266 // function template are combined with the set of non-template candidate
6267 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006268 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006269 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006270 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006271 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006272 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006273 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006274 Candidate.FoundDecl = FoundDecl;
6275 Candidate.Function = MethodTmpl->getTemplatedDecl();
6276 Candidate.Viable = false;
6277 Candidate.FailureKind = ovl_fail_bad_deduction;
6278 Candidate.IsSurrogate = false;
6279 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006280 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006281 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006282 Info);
6283 return;
6284 }
Mike Stump11289f42009-09-09 15:08:12 +00006285
Douglas Gregor97628d62009-08-21 00:16:32 +00006286 // Add the function template specialization produced by template argument
6287 // deduction as a candidate.
6288 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006289 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006290 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006291 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006292 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006293 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006294}
6295
Douglas Gregor05155d82009-08-21 23:19:43 +00006296/// \brief Add a C++ function template specialization as a candidate
6297/// in the candidate set, using template argument deduction to produce
6298/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006299void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006300Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006301 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006302 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006303 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006304 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006305 bool SuppressUserConversions,
6306 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006307 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6308 return;
6309
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006310 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006311 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006312 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006313 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006314 // candidate functions in the usual way.113) A given name can refer to one
6315 // or more function templates and also to a set of overloaded non-template
6316 // functions. In such a case, the candidate functions generated from each
6317 // function template are combined with the set of non-template candidate
6318 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006319 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006320 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006321 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006322 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006323 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006324 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006325 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006326 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6327 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006328 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006329 Candidate.IsSurrogate = false;
6330 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006331 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006332 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006333 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006334 return;
6335 }
Mike Stump11289f42009-09-09 15:08:12 +00006336
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006337 // Add the function template specialization produced by template argument
6338 // deduction as a candidate.
6339 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006340 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006341 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006342}
Mike Stump11289f42009-09-09 15:08:12 +00006343
Douglas Gregor4b60a152013-11-07 22:34:54 +00006344/// Determine whether this is an allowable conversion from the result
6345/// of an explicit conversion operator to the expected type, per C++
6346/// [over.match.conv]p1 and [over.match.ref]p1.
6347///
6348/// \param ConvType The return type of the conversion function.
6349///
6350/// \param ToType The type we are converting to.
6351///
6352/// \param AllowObjCPointerConversion Allow a conversion from one
6353/// Objective-C pointer to another.
6354///
6355/// \returns true if the conversion is allowable, false otherwise.
6356static bool isAllowableExplicitConversion(Sema &S,
6357 QualType ConvType, QualType ToType,
6358 bool AllowObjCPointerConversion) {
6359 QualType ToNonRefType = ToType.getNonReferenceType();
6360
6361 // Easy case: the types are the same.
6362 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6363 return true;
6364
6365 // Allow qualification conversions.
6366 bool ObjCLifetimeConversion;
6367 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6368 ObjCLifetimeConversion))
6369 return true;
6370
6371 // If we're not allowed to consider Objective-C pointer conversions,
6372 // we're done.
6373 if (!AllowObjCPointerConversion)
6374 return false;
6375
6376 // Is this an Objective-C pointer conversion?
6377 bool IncompatibleObjC = false;
6378 QualType ConvertedType;
6379 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6380 IncompatibleObjC);
6381}
6382
Douglas Gregora1f013e2008-11-07 22:36:19 +00006383/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006384/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006385/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006386/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006387/// (which may or may not be the same type as the type that the
6388/// conversion function produces).
6389void
6390Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006391 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006392 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006393 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006394 OverloadCandidateSet& CandidateSet,
6395 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006396 assert(!Conversion->getDescribedFunctionTemplate() &&
6397 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006398 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006399 if (!CandidateSet.isNewCandidate(Conversion))
6400 return;
6401
Richard Smith2a7d4812013-05-04 07:00:32 +00006402 // If the conversion function has an undeduced return type, trigger its
6403 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006404 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006405 if (DeduceReturnType(Conversion, From->getExprLoc()))
6406 return;
6407 ConvType = Conversion->getConversionType().getNonReferenceType();
6408 }
6409
Richard Smith089c3162013-09-21 21:55:46 +00006410 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6411 // operator is only a candidate if its return type is the target type or
6412 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006413 if (Conversion->isExplicit() &&
6414 !isAllowableExplicitConversion(*this, ConvType, ToType,
6415 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006416 return;
6417
Douglas Gregor27381f32009-11-23 12:27:39 +00006418 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006419 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006420
Douglas Gregora1f013e2008-11-07 22:36:19 +00006421 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006422 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006423 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006424 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006425 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006426 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006427 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006428 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006429 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006430 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006431 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006432
Douglas Gregor6affc782010-08-19 15:37:02 +00006433 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006434 // For conversion functions, the function is considered to be a member of
6435 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006436 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006437 //
6438 // Determine the implicit conversion sequence for the implicit
6439 // object parameter.
6440 QualType ImplicitParamType = From->getType();
6441 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6442 ImplicitParamType = FromPtrType->getPointeeType();
6443 CXXRecordDecl *ConversionContext
6444 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006445
Richard Smith0f59cb32015-12-18 21:45:41 +00006446 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6447 *this, CandidateSet.getLocation(), From->getType(),
6448 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449
John McCall0d1da222010-01-12 00:44:57 +00006450 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006451 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006452 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006453 return;
6454 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006455
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006456 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006457 // derived to base as such conversions are given Conversion Rank. They only
6458 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6459 QualType FromCanon
6460 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6461 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006462 if (FromCanon == ToCanon ||
6463 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006464 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006465 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006466 return;
6467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006468
Douglas Gregora1f013e2008-11-07 22:36:19 +00006469 // To determine what the conversion from the result of calling the
6470 // conversion function to the type we're eventually trying to
6471 // convert to (ToType), we need to synthesize a call to the
6472 // conversion function and attempt copy initialization from it. This
6473 // makes sure that we get the right semantics with respect to
6474 // lvalues/rvalues and the type. Fortunately, we can allocate this
6475 // call on the stack and we don't need its arguments to be
6476 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006477 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006478 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006479 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6480 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006481 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006482 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006483
Richard Smith48d24642011-07-13 22:53:21 +00006484 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006485 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006486 Candidate.Viable = false;
6487 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6488 return;
6489 }
6490
Richard Smith48d24642011-07-13 22:53:21 +00006491 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006492
Mike Stump11289f42009-09-09 15:08:12 +00006493 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006494 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6495 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006496 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006497 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006498 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006499 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006500 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006501 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006502 /*InOverloadResolution=*/false,
6503 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006504
John McCall0d1da222010-01-12 00:44:57 +00006505 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006506 case ImplicitConversionSequence::StandardConversion:
6507 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006508
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006509 // C++ [over.ics.user]p3:
6510 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006511 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006512 // shall have exact match rank.
6513 if (Conversion->getPrimaryTemplate() &&
6514 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6515 Candidate.Viable = false;
6516 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006517 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006519
Douglas Gregorcba72b12011-01-21 05:18:22 +00006520 // C++0x [dcl.init.ref]p5:
6521 // In the second case, if the reference is an rvalue reference and
6522 // the second standard conversion sequence of the user-defined
6523 // conversion sequence includes an lvalue-to-rvalue conversion, the
6524 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006525 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006526 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6527 Candidate.Viable = false;
6528 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006529 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006530 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006531 break;
6532
6533 case ImplicitConversionSequence::BadConversion:
6534 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006535 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006536 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006537
6538 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006539 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006540 "Can only end up with a standard conversion sequence or failure");
6541 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006542
Craig Topper5fc8fc22014-08-27 06:28:36 +00006543 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006544 Candidate.Viable = false;
6545 Candidate.FailureKind = ovl_fail_enable_if;
6546 Candidate.DeductionFailure.Data = FailedAttr;
6547 return;
6548 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006549}
6550
Douglas Gregor05155d82009-08-21 23:19:43 +00006551/// \brief Adds a conversion function template specialization
6552/// candidate to the overload set, using template argument deduction
6553/// to deduce the template arguments of the conversion function
6554/// template from the type that we are converting to (C++
6555/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006556void
Douglas Gregor05155d82009-08-21 23:19:43 +00006557Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006558 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006559 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006560 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006561 OverloadCandidateSet &CandidateSet,
6562 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006563 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6564 "Only conversion function templates permitted here");
6565
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006566 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6567 return;
6568
Craig Toppere6706e42012-09-19 02:26:47 +00006569 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006570 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006571 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006572 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006573 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006574 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006575 Candidate.FoundDecl = FoundDecl;
6576 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6577 Candidate.Viable = false;
6578 Candidate.FailureKind = ovl_fail_bad_deduction;
6579 Candidate.IsSurrogate = false;
6580 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006581 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006582 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006583 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006584 return;
6585 }
Mike Stump11289f42009-09-09 15:08:12 +00006586
Douglas Gregor05155d82009-08-21 23:19:43 +00006587 // Add the conversion function template specialization produced by
6588 // template argument deduction as a candidate.
6589 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006590 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006591 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006592}
6593
Douglas Gregorab7897a2008-11-19 22:57:39 +00006594/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6595/// converts the given @c Object to a function pointer via the
6596/// conversion function @c Conversion, and then attempts to call it
6597/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6598/// the type of function that we'll eventually be calling.
6599void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006600 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006601 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006602 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006603 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006604 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006605 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006606 if (!CandidateSet.isNewCandidate(Conversion))
6607 return;
6608
Douglas Gregor27381f32009-11-23 12:27:39 +00006609 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006610 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006611
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006612 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006613 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006614 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006615 Candidate.Surrogate = Conversion;
6616 Candidate.Viable = true;
6617 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006618 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006619 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006620
6621 // Determine the implicit conversion sequence for the implicit
6622 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006623 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6624 *this, CandidateSet.getLocation(), Object->getType(),
6625 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006626 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006627 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006628 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006629 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006630 return;
6631 }
6632
6633 // The first conversion is actually a user-defined conversion whose
6634 // first conversion is ObjectInit's standard conversion (which is
6635 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006636 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006637 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006638 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006639 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006640 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006641 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006642 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006643 = Candidate.Conversions[0].UserDefined.Before;
6644 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6645
Mike Stump11289f42009-09-09 15:08:12 +00006646 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006647 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006648
6649 // (C++ 13.3.2p2): A candidate function having fewer than m
6650 // parameters is viable only if it has an ellipsis in its parameter
6651 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006652 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006653 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006654 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006655 return;
6656 }
6657
6658 // Function types don't have any default arguments, so just check if
6659 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006660 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006661 // Not enough arguments.
6662 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006663 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006664 return;
6665 }
6666
6667 // Determine the implicit conversion sequences for each of the
6668 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006669 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006670 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006671 // (C++ 13.3.2p3): for F to be a viable function, there shall
6672 // exist for each argument an implicit conversion sequence
6673 // (13.3.3.1) that converts that argument to the corresponding
6674 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006675 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006676 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006677 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006678 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006679 /*InOverloadResolution=*/false,
6680 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006681 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006682 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006683 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006684 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006685 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006686 }
6687 } else {
6688 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6689 // argument for which there is no corresponding parameter is
6690 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006691 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006692 }
6693 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006694
Craig Topper5fc8fc22014-08-27 06:28:36 +00006695 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006696 Candidate.Viable = false;
6697 Candidate.FailureKind = ovl_fail_enable_if;
6698 Candidate.DeductionFailure.Data = FailedAttr;
6699 return;
6700 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006701}
6702
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006703/// \brief Add overload candidates for overloaded operators that are
6704/// member functions.
6705///
6706/// Add the overloaded operator candidates that are member functions
6707/// for the operator Op that was used in an operator expression such
6708/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6709/// CandidateSet will store the added overload candidates. (C++
6710/// [over.match.oper]).
6711void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6712 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006713 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006714 OverloadCandidateSet& CandidateSet,
6715 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006716 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6717
6718 // C++ [over.match.oper]p3:
6719 // For a unary operator @ with an operand of a type whose
6720 // cv-unqualified version is T1, and for a binary operator @ with
6721 // a left operand of a type whose cv-unqualified version is T1 and
6722 // a right operand of a type whose cv-unqualified version is T2,
6723 // three sets of candidate functions, designated member
6724 // candidates, non-member candidates and built-in candidates, are
6725 // constructed as follows:
6726 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006727
Richard Smith0feaf0c2013-04-20 12:41:22 +00006728 // -- If T1 is a complete class type or a class currently being
6729 // defined, the set of member candidates is the result of the
6730 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6731 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006732 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006733 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006734 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006735 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006736 // If the type is neither complete nor being defined, bail out now.
6737 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006738 return;
Mike Stump11289f42009-09-09 15:08:12 +00006739
John McCall27b18f82009-11-17 02:14:36 +00006740 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6741 LookupQualifiedName(Operators, T1Rec->getDecl());
6742 Operators.suppressDiagnostics();
6743
Mike Stump11289f42009-09-09 15:08:12 +00006744 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006745 OperEnd = Operators.end();
6746 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006747 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006748 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006749 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006750 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006751 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006752 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006753 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006754}
6755
Douglas Gregora11693b2008-11-12 17:17:38 +00006756/// AddBuiltinCandidate - Add a candidate for a built-in
6757/// operator. ResultTy and ParamTys are the result and parameter types
6758/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006759/// arguments being passed to the candidate. IsAssignmentOperator
6760/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006761/// operator. NumContextualBoolArguments is the number of arguments
6762/// (at the beginning of the argument list) that will be contextually
6763/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006764void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006765 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006766 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006767 bool IsAssignmentOperator,
6768 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006769 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006770 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006771
Douglas Gregora11693b2008-11-12 17:17:38 +00006772 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006773 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006774 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6775 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006776 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006777 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006778 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006780 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6781
6782 // Determine the implicit conversion sequences for each of the
6783 // arguments.
6784 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006785 Candidate.ExplicitCallArguments = Args.size();
6786 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006787 // C++ [over.match.oper]p4:
6788 // For the built-in assignment operators, conversions of the
6789 // left operand are restricted as follows:
6790 // -- no temporaries are introduced to hold the left operand, and
6791 // -- no user-defined conversions are applied to the left
6792 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006793 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006794 //
6795 // We block these conversions by turning off user-defined
6796 // conversions, since that is the only way that initialization of
6797 // a reference to a non-class type can occur from something that
6798 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006799 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006800 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006801 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006802 Candidate.Conversions[ArgIdx]
6803 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006804 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006805 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006806 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006807 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006808 /*InOverloadResolution=*/false,
6809 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006810 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006811 }
John McCall0d1da222010-01-12 00:44:57 +00006812 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006813 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006814 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006815 break;
6816 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006817 }
6818}
6819
Craig Toppercd7b0332013-07-01 06:29:40 +00006820namespace {
6821
Douglas Gregora11693b2008-11-12 17:17:38 +00006822/// BuiltinCandidateTypeSet - A set of types that will be used for the
6823/// candidate operator functions for built-in operators (C++
6824/// [over.built]). The types are separated into pointer types and
6825/// enumeration types.
6826class BuiltinCandidateTypeSet {
6827 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006828 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6829 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006830
6831 /// PointerTypes - The set of pointer types that will be used in the
6832 /// built-in candidates.
6833 TypeSet PointerTypes;
6834
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006835 /// MemberPointerTypes - The set of member pointer types that will be
6836 /// used in the built-in candidates.
6837 TypeSet MemberPointerTypes;
6838
Douglas Gregora11693b2008-11-12 17:17:38 +00006839 /// EnumerationTypes - The set of enumeration types that will be
6840 /// used in the built-in candidates.
6841 TypeSet EnumerationTypes;
6842
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006844 /// candidates.
6845 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006846
6847 /// \brief A flag indicating non-record types are viable candidates
6848 bool HasNonRecordTypes;
6849
6850 /// \brief A flag indicating whether either arithmetic or enumeration types
6851 /// were present in the candidate set.
6852 bool HasArithmeticOrEnumeralTypes;
6853
Douglas Gregor80af3132011-05-21 23:15:46 +00006854 /// \brief A flag indicating whether the nullptr type was present in the
6855 /// candidate set.
6856 bool HasNullPtrType;
6857
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006858 /// Sema - The semantic analysis instance where we are building the
6859 /// candidate type set.
6860 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006861
Douglas Gregora11693b2008-11-12 17:17:38 +00006862 /// Context - The AST context in which we will build the type sets.
6863 ASTContext &Context;
6864
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006865 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6866 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006867 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006868
6869public:
6870 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006871 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006872
Mike Stump11289f42009-09-09 15:08:12 +00006873 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006874 : HasNonRecordTypes(false),
6875 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006876 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006877 SemaRef(SemaRef),
6878 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006879
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006880 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006881 SourceLocation Loc,
6882 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006883 bool AllowExplicitConversions,
6884 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006885
6886 /// pointer_begin - First pointer type found;
6887 iterator pointer_begin() { return PointerTypes.begin(); }
6888
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006889 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006890 iterator pointer_end() { return PointerTypes.end(); }
6891
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006892 /// member_pointer_begin - First member pointer type found;
6893 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6894
6895 /// member_pointer_end - Past the last member pointer type found;
6896 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6897
Douglas Gregora11693b2008-11-12 17:17:38 +00006898 /// enumeration_begin - First enumeration type found;
6899 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6900
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006901 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006902 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006903
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006904 iterator vector_begin() { return VectorTypes.begin(); }
6905 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006906
6907 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6908 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006909 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006910};
6911
Craig Toppercd7b0332013-07-01 06:29:40 +00006912} // end anonymous namespace
6913
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006914/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006915/// the set of pointer types along with any more-qualified variants of
6916/// that type. For example, if @p Ty is "int const *", this routine
6917/// will add "int const *", "int const volatile *", "int const
6918/// restrict *", and "int const volatile restrict *" to the set of
6919/// pointer types. Returns true if the add of @p Ty itself succeeded,
6920/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006921///
6922/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006923bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006924BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6925 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006926
Douglas Gregora11693b2008-11-12 17:17:38 +00006927 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00006928 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006929 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006930
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006931 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006932 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006933 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006934 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006935 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6936 PointeeTy = PTy->getPointeeType();
6937 buildObjCPtr = true;
6938 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006939 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006940 }
6941
Sebastian Redl4990a632009-11-18 20:39:26 +00006942 // Don't add qualified variants of arrays. For one, they're not allowed
6943 // (the qualifier would sink to the element type), and for another, the
6944 // only overload situation where it matters is subscript or pointer +- int,
6945 // and those shouldn't have qualifier variants anyway.
6946 if (PointeeTy->isArrayType())
6947 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006948
John McCall8ccfcb52009-09-24 19:53:00 +00006949 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006950 bool hasVolatile = VisibleQuals.hasVolatile();
6951 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952
John McCall8ccfcb52009-09-24 19:53:00 +00006953 // Iterate through all strict supersets of BaseCVR.
6954 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6955 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006956 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006957 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006958
6959 // Skip over restrict if no restrict found anywhere in the types, or if
6960 // the type cannot be restrict-qualified.
6961 if ((CVR & Qualifiers::Restrict) &&
6962 (!hasRestrict ||
6963 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6964 continue;
6965
6966 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006967 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006968
6969 // Build qualified pointer type.
6970 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006971 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006972 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006973 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006974 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6975
6976 // Insert qualified pointer type.
6977 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006978 }
6979
6980 return true;
6981}
6982
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006983/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6984/// to the set of pointer types along with any more-qualified variants of
6985/// that type. For example, if @p Ty is "int const *", this routine
6986/// will add "int const *", "int const volatile *", "int const
6987/// restrict *", and "int const volatile restrict *" to the set of
6988/// pointer types. Returns true if the add of @p Ty itself succeeded,
6989/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006990///
6991/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006992bool
6993BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6994 QualType Ty) {
6995 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00006996 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006997 return false;
6998
John McCall8ccfcb52009-09-24 19:53:00 +00006999 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7000 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007001
John McCall8ccfcb52009-09-24 19:53:00 +00007002 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007003 // Don't add qualified variants of arrays. For one, they're not allowed
7004 // (the qualifier would sink to the element type), and for another, the
7005 // only overload situation where it matters is subscript or pointer +- int,
7006 // and those shouldn't have qualifier variants anyway.
7007 if (PointeeTy->isArrayType())
7008 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007009 const Type *ClassTy = PointerTy->getClass();
7010
7011 // Iterate through all strict supersets of the pointee type's CVR
7012 // qualifiers.
7013 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7014 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7015 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007016
John McCall8ccfcb52009-09-24 19:53:00 +00007017 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007018 MemberPointerTypes.insert(
7019 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007020 }
7021
7022 return true;
7023}
7024
Douglas Gregora11693b2008-11-12 17:17:38 +00007025/// AddTypesConvertedFrom - Add each of the types to which the type @p
7026/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007027/// primarily interested in pointer types and enumeration types. We also
7028/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007029/// AllowUserConversions is true if we should look at the conversion
7030/// functions of a class type, and AllowExplicitConversions if we
7031/// should also include the explicit conversion functions of a class
7032/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007033void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007034BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007035 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007036 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007037 bool AllowExplicitConversions,
7038 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007039 // Only deal with canonical types.
7040 Ty = Context.getCanonicalType(Ty);
7041
7042 // Look through reference types; they aren't part of the type of an
7043 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007044 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007045 Ty = RefTy->getPointeeType();
7046
John McCall33ddac02011-01-19 10:06:00 +00007047 // If we're dealing with an array type, decay to the pointer.
7048 if (Ty->isArrayType())
7049 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7050
7051 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007052 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007053
Chandler Carruth00a38332010-12-13 01:44:01 +00007054 // Flag if we ever add a non-record type.
7055 const RecordType *TyRec = Ty->getAs<RecordType>();
7056 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7057
Chandler Carruth00a38332010-12-13 01:44:01 +00007058 // Flag if we encounter an arithmetic type.
7059 HasArithmeticOrEnumeralTypes =
7060 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7061
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007062 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7063 PointerTypes.insert(Ty);
7064 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007065 // Insert our type, and its more-qualified variants, into the set
7066 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007067 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007068 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007069 } else if (Ty->isMemberPointerType()) {
7070 // Member pointers are far easier, since the pointee can't be converted.
7071 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7072 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007073 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007074 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007075 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007076 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007077 // We treat vector types as arithmetic types in many contexts as an
7078 // extension.
7079 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007080 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007081 } else if (Ty->isNullPtrType()) {
7082 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007083 } else if (AllowUserConversions && TyRec) {
7084 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007085 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007086 return;
Mike Stump11289f42009-09-09 15:08:12 +00007087
Chandler Carruth00a38332010-12-13 01:44:01 +00007088 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007089 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007090 if (isa<UsingShadowDecl>(D))
7091 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007092
Chandler Carruth00a38332010-12-13 01:44:01 +00007093 // Skip conversion function templates; they don't tell us anything
7094 // about which builtin types we can convert to.
7095 if (isa<FunctionTemplateDecl>(D))
7096 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007097
Chandler Carruth00a38332010-12-13 01:44:01 +00007098 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7099 if (AllowExplicitConversions || !Conv->isExplicit()) {
7100 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7101 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007102 }
7103 }
7104 }
7105}
7106
Douglas Gregor84605ae2009-08-24 13:43:27 +00007107/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7108/// the volatile- and non-volatile-qualified assignment operators for the
7109/// given type to the candidate set.
7110static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7111 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007112 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007113 OverloadCandidateSet &CandidateSet) {
7114 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007115
Douglas Gregor84605ae2009-08-24 13:43:27 +00007116 // T& operator=(T&, T)
7117 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7118 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007119 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007120 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007121
Douglas Gregor84605ae2009-08-24 13:43:27 +00007122 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7123 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007124 ParamTypes[0]
7125 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007126 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007127 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007128 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007129 }
7130}
Mike Stump11289f42009-09-09 15:08:12 +00007131
Sebastian Redl1054fae2009-10-25 17:03:50 +00007132/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7133/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007134static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7135 Qualifiers VRQuals;
7136 const RecordType *TyRec;
7137 if (const MemberPointerType *RHSMPType =
7138 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007139 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007140 else
7141 TyRec = ArgExpr->getType()->getAs<RecordType>();
7142 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007143 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007144 VRQuals.addVolatile();
7145 VRQuals.addRestrict();
7146 return VRQuals;
7147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007148
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007149 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007150 if (!ClassDecl->hasDefinition())
7151 return VRQuals;
7152
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007153 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007154 if (isa<UsingShadowDecl>(D))
7155 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7156 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007157 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7158 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7159 CanTy = ResTypeRef->getPointeeType();
7160 // Need to go down the pointer/mempointer chain and add qualifiers
7161 // as see them.
7162 bool done = false;
7163 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007164 if (CanTy.isRestrictQualified())
7165 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007166 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7167 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007168 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007169 CanTy->getAs<MemberPointerType>())
7170 CanTy = ResTypeMPtr->getPointeeType();
7171 else
7172 done = true;
7173 if (CanTy.isVolatileQualified())
7174 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007175 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7176 return VRQuals;
7177 }
7178 }
7179 }
7180 return VRQuals;
7181}
John McCall52872982010-11-13 05:51:15 +00007182
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007183namespace {
John McCall52872982010-11-13 05:51:15 +00007184
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007185/// \brief Helper class to manage the addition of builtin operator overload
7186/// candidates. It provides shared state and utility methods used throughout
7187/// the process, as well as a helper method to add each group of builtin
7188/// operator overloads from the standard to a candidate set.
7189class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007190 // Common instance state available to all overload candidate addition methods.
7191 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007192 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007193 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007194 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007195 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007196 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007197
Chandler Carruthc6586e52010-12-12 10:35:00 +00007198 // Define some constants used to index and iterate over the arithemetic types
7199 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007200 // The "promoted arithmetic types" are the arithmetic
7201 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007202 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007203 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007204 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007205 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007206 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007207 LastPromotedArithmeticType = 11;
7208 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007209
Chandler Carruthc6586e52010-12-12 10:35:00 +00007210 /// \brief Get the canonical type for a given arithmetic type index.
7211 CanQualType getArithmeticType(unsigned index) {
7212 assert(index < NumArithmeticTypes);
7213 static CanQualType ASTContext::* const
7214 ArithmeticTypes[NumArithmeticTypes] = {
7215 // Start of promoted types.
7216 &ASTContext::FloatTy,
7217 &ASTContext::DoubleTy,
7218 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007219
Chandler Carruthc6586e52010-12-12 10:35:00 +00007220 // Start of integral types.
7221 &ASTContext::IntTy,
7222 &ASTContext::LongTy,
7223 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007224 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007225 &ASTContext::UnsignedIntTy,
7226 &ASTContext::UnsignedLongTy,
7227 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007228 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007229 // End of promoted types.
7230
7231 &ASTContext::BoolTy,
7232 &ASTContext::CharTy,
7233 &ASTContext::WCharTy,
7234 &ASTContext::Char16Ty,
7235 &ASTContext::Char32Ty,
7236 &ASTContext::SignedCharTy,
7237 &ASTContext::ShortTy,
7238 &ASTContext::UnsignedCharTy,
7239 &ASTContext::UnsignedShortTy,
7240 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007241 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007242 };
7243 return S.Context.*ArithmeticTypes[index];
7244 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007245
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007246 /// \brief Gets the canonical type resulting from the usual arithemetic
7247 /// converions for the given arithmetic types.
7248 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7249 // Accelerator table for performing the usual arithmetic conversions.
7250 // The rules are basically:
7251 // - if either is floating-point, use the wider floating-point
7252 // - if same signedness, use the higher rank
7253 // - if same size, use unsigned of the higher rank
7254 // - use the larger type
7255 // These rules, together with the axiom that higher ranks are
7256 // never smaller, are sufficient to precompute all of these results
7257 // *except* when dealing with signed types of higher rank.
7258 // (we could precompute SLL x UI for all known platforms, but it's
7259 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007260 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007261 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007262 Dep=-1,
7263 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007264 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007265 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007266 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007267/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7268/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7269/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7270/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7271/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7272/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7273/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7274/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7275/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7276/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7277/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007278 };
7279
7280 assert(L < LastPromotedArithmeticType);
7281 assert(R < LastPromotedArithmeticType);
7282 int Idx = ConversionsTable[L][R];
7283
7284 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007285 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007286
7287 // Slow path: we need to compare widths.
7288 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007289 CanQualType LT = getArithmeticType(L),
7290 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007291 unsigned LW = S.Context.getIntWidth(LT),
7292 RW = S.Context.getIntWidth(RT);
7293
7294 // If they're different widths, use the signed type.
7295 if (LW > RW) return LT;
7296 else if (LW < RW) return RT;
7297
7298 // Otherwise, use the unsigned type of the signed type's rank.
7299 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7300 assert(L == SLL || R == SLL);
7301 return S.Context.UnsignedLongLongTy;
7302 }
7303
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007304 /// \brief Helper method to factor out the common pattern of adding overloads
7305 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007306 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007307 bool HasVolatile,
7308 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007309 QualType ParamTypes[2] = {
7310 S.Context.getLValueReferenceType(CandidateTy),
7311 S.Context.IntTy
7312 };
7313
7314 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007315 if (Args.size() == 1)
7316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007317 else
Richard Smithe54c3072013-05-05 15:51:06 +00007318 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007319
7320 // Use a heuristic to reduce number of builtin candidates in the set:
7321 // add volatile version only if there are conversions to a volatile type.
7322 if (HasVolatile) {
7323 ParamTypes[0] =
7324 S.Context.getLValueReferenceType(
7325 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007326 if (Args.size() == 1)
7327 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007328 else
Richard Smithe54c3072013-05-05 15:51:06 +00007329 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007330 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007331
7332 // Add restrict version only if there are conversions to a restrict type
7333 // and our candidate type is a non-restrict-qualified pointer.
7334 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7335 !CandidateTy.isRestrictQualified()) {
7336 ParamTypes[0]
7337 = S.Context.getLValueReferenceType(
7338 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007339 if (Args.size() == 1)
7340 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007341 else
Richard Smithe54c3072013-05-05 15:51:06 +00007342 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007343
7344 if (HasVolatile) {
7345 ParamTypes[0]
7346 = S.Context.getLValueReferenceType(
7347 S.Context.getCVRQualifiedType(CandidateTy,
7348 (Qualifiers::Volatile |
7349 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007350 if (Args.size() == 1)
7351 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007352 else
Richard Smithe54c3072013-05-05 15:51:06 +00007353 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007354 }
7355 }
7356
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007357 }
7358
7359public:
7360 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007361 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007362 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007363 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007364 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007365 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007366 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007367 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007368 HasArithmeticOrEnumeralCandidateType(
7369 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007370 CandidateTypes(CandidateTypes),
7371 CandidateSet(CandidateSet) {
7372 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007373 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007374 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007375 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007376 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007377 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007378 assert(getArithmeticType(FirstPromotedArithmeticType)
7379 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007380 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007381 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007382 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007383 "Invalid last promoted arithmetic type");
7384 }
7385
7386 // C++ [over.built]p3:
7387 //
7388 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7389 // is either volatile or empty, there exist candidate operator
7390 // functions of the form
7391 //
7392 // VQ T& operator++(VQ T&);
7393 // T operator++(VQ T&, int);
7394 //
7395 // C++ [over.built]p4:
7396 //
7397 // For every pair (T, VQ), where T is an arithmetic type other
7398 // than bool, and VQ is either volatile or empty, there exist
7399 // candidate operator functions of the form
7400 //
7401 // VQ T& operator--(VQ T&);
7402 // T operator--(VQ T&, int);
7403 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007404 if (!HasArithmeticOrEnumeralCandidateType)
7405 return;
7406
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007407 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7408 Arith < NumArithmeticTypes; ++Arith) {
7409 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007410 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007411 VisibleTypeConversionsQuals.hasVolatile(),
7412 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007413 }
7414 }
7415
7416 // C++ [over.built]p5:
7417 //
7418 // For every pair (T, VQ), where T is a cv-qualified or
7419 // cv-unqualified object type, and VQ is either volatile or
7420 // empty, there exist candidate operator functions of the form
7421 //
7422 // T*VQ& operator++(T*VQ&);
7423 // T*VQ& operator--(T*VQ&);
7424 // T* operator++(T*VQ&, int);
7425 // T* operator--(T*VQ&, int);
7426 void addPlusPlusMinusMinusPointerOverloads() {
7427 for (BuiltinCandidateTypeSet::iterator
7428 Ptr = CandidateTypes[0].pointer_begin(),
7429 PtrEnd = CandidateTypes[0].pointer_end();
7430 Ptr != PtrEnd; ++Ptr) {
7431 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007432 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007433 continue;
7434
7435 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007436 (!(*Ptr).isVolatileQualified() &&
7437 VisibleTypeConversionsQuals.hasVolatile()),
7438 (!(*Ptr).isRestrictQualified() &&
7439 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007440 }
7441 }
7442
7443 // C++ [over.built]p6:
7444 // For every cv-qualified or cv-unqualified object type T, there
7445 // exist candidate operator functions of the form
7446 //
7447 // T& operator*(T*);
7448 //
7449 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007450 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007451 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007452 // T& operator*(T*);
7453 void addUnaryStarPointerOverloads() {
7454 for (BuiltinCandidateTypeSet::iterator
7455 Ptr = CandidateTypes[0].pointer_begin(),
7456 PtrEnd = CandidateTypes[0].pointer_end();
7457 Ptr != PtrEnd; ++Ptr) {
7458 QualType ParamTy = *Ptr;
7459 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007460 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7461 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007462
Douglas Gregor02824322011-01-26 19:30:28 +00007463 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7464 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7465 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007466
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007467 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007468 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007469 }
7470 }
7471
7472 // C++ [over.built]p9:
7473 // For every promoted arithmetic type T, there exist candidate
7474 // operator functions of the form
7475 //
7476 // T operator+(T);
7477 // T operator-(T);
7478 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007479 if (!HasArithmeticOrEnumeralCandidateType)
7480 return;
7481
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007482 for (unsigned Arith = FirstPromotedArithmeticType;
7483 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007484 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007485 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007486 }
7487
7488 // Extension: We also add these operators for vector types.
7489 for (BuiltinCandidateTypeSet::iterator
7490 Vec = CandidateTypes[0].vector_begin(),
7491 VecEnd = CandidateTypes[0].vector_end();
7492 Vec != VecEnd; ++Vec) {
7493 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007494 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007495 }
7496 }
7497
7498 // C++ [over.built]p8:
7499 // For every type T, there exist candidate operator functions of
7500 // the form
7501 //
7502 // T* operator+(T*);
7503 void addUnaryPlusPointerOverloads() {
7504 for (BuiltinCandidateTypeSet::iterator
7505 Ptr = CandidateTypes[0].pointer_begin(),
7506 PtrEnd = CandidateTypes[0].pointer_end();
7507 Ptr != PtrEnd; ++Ptr) {
7508 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007509 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 }
7511 }
7512
7513 // C++ [over.built]p10:
7514 // For every promoted integral type T, there exist candidate
7515 // operator functions of the form
7516 //
7517 // T operator~(T);
7518 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007519 if (!HasArithmeticOrEnumeralCandidateType)
7520 return;
7521
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007522 for (unsigned Int = FirstPromotedIntegralType;
7523 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007524 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007525 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007526 }
7527
7528 // Extension: We also add this operator for vector types.
7529 for (BuiltinCandidateTypeSet::iterator
7530 Vec = CandidateTypes[0].vector_begin(),
7531 VecEnd = CandidateTypes[0].vector_end();
7532 Vec != VecEnd; ++Vec) {
7533 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007534 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007535 }
7536 }
7537
7538 // C++ [over.match.oper]p16:
7539 // For every pointer to member type T, there exist candidate operator
7540 // functions of the form
7541 //
7542 // bool operator==(T,T);
7543 // bool operator!=(T,T);
7544 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7545 /// Set of (canonical) types that we've already handled.
7546 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7547
Richard Smithe54c3072013-05-05 15:51:06 +00007548 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007549 for (BuiltinCandidateTypeSet::iterator
7550 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7551 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7552 MemPtr != MemPtrEnd;
7553 ++MemPtr) {
7554 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007555 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007556 continue;
7557
7558 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007559 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007560 }
7561 }
7562 }
7563
7564 // C++ [over.built]p15:
7565 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007566 // For every T, where T is an enumeration type, a pointer type, or
7567 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007568 //
7569 // bool operator<(T, T);
7570 // bool operator>(T, T);
7571 // bool operator<=(T, T);
7572 // bool operator>=(T, T);
7573 // bool operator==(T, T);
7574 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007575 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007576 // C++ [over.match.oper]p3:
7577 // [...]the built-in candidates include all of the candidate operator
7578 // functions defined in 13.6 that, compared to the given operator, [...]
7579 // do not have the same parameter-type-list as any non-template non-member
7580 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007581 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007582 // Note that in practice, this only affects enumeration types because there
7583 // aren't any built-in candidates of record type, and a user-defined operator
7584 // must have an operand of record or enumeration type. Also, the only other
7585 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007586 // cannot be overloaded for enumeration types, so this is the only place
7587 // where we must suppress candidates like this.
7588 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7589 UserDefinedBinaryOperators;
7590
Richard Smithe54c3072013-05-05 15:51:06 +00007591 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007592 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7593 CandidateTypes[ArgIdx].enumeration_end()) {
7594 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7595 CEnd = CandidateSet.end();
7596 C != CEnd; ++C) {
7597 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7598 continue;
7599
Eli Friedman14f082b2012-09-18 21:52:24 +00007600 if (C->Function->isFunctionTemplateSpecialization())
7601 continue;
7602
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007603 QualType FirstParamType =
7604 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7605 QualType SecondParamType =
7606 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7607
7608 // Skip if either parameter isn't of enumeral type.
7609 if (!FirstParamType->isEnumeralType() ||
7610 !SecondParamType->isEnumeralType())
7611 continue;
7612
7613 // Add this operator to the set of known user-defined operators.
7614 UserDefinedBinaryOperators.insert(
7615 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7616 S.Context.getCanonicalType(SecondParamType)));
7617 }
7618 }
7619 }
7620
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007621 /// Set of (canonical) types that we've already handled.
7622 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7623
Richard Smithe54c3072013-05-05 15:51:06 +00007624 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007625 for (BuiltinCandidateTypeSet::iterator
7626 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7627 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7628 Ptr != PtrEnd; ++Ptr) {
7629 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007630 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007631 continue;
7632
7633 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007634 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007635 }
7636 for (BuiltinCandidateTypeSet::iterator
7637 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7638 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7639 Enum != EnumEnd; ++Enum) {
7640 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7641
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007642 // Don't add the same builtin candidate twice, or if a user defined
7643 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007644 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007645 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7646 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007647 continue;
7648
7649 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007650 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007651 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007652
7653 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7654 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007655 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007656 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007657 NullPtrTy))) {
7658 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007659 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007660 CandidateSet);
7661 }
7662 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007663 }
7664 }
7665
7666 // C++ [over.built]p13:
7667 //
7668 // For every cv-qualified or cv-unqualified object type T
7669 // there exist candidate operator functions of the form
7670 //
7671 // T* operator+(T*, ptrdiff_t);
7672 // T& operator[](T*, ptrdiff_t); [BELOW]
7673 // T* operator-(T*, ptrdiff_t);
7674 // T* operator+(ptrdiff_t, T*);
7675 // T& operator[](ptrdiff_t, T*); [BELOW]
7676 //
7677 // C++ [over.built]p14:
7678 //
7679 // For every T, where T is a pointer to object type, there
7680 // exist candidate operator functions of the form
7681 //
7682 // ptrdiff_t operator-(T, T);
7683 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7684 /// Set of (canonical) types that we've already handled.
7685 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7686
7687 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007688 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007689 S.Context.getPointerDiffType(),
7690 S.Context.getPointerDiffType(),
7691 };
7692 for (BuiltinCandidateTypeSet::iterator
7693 Ptr = CandidateTypes[Arg].pointer_begin(),
7694 PtrEnd = CandidateTypes[Arg].pointer_end();
7695 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007696 QualType PointeeTy = (*Ptr)->getPointeeType();
7697 if (!PointeeTy->isObjectType())
7698 continue;
7699
Eric Christopher9207a522015-08-21 16:24:01 +00007700 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007701 if (Arg == 0 || Op == OO_Plus) {
7702 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7703 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007704 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007705 }
7706 if (Op == OO_Minus) {
7707 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007708 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007709 continue;
7710
7711 QualType ParamTypes[2] = { *Ptr, *Ptr };
7712 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007713 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007714 }
7715 }
7716 }
7717 }
7718
7719 // C++ [over.built]p12:
7720 //
7721 // For every pair of promoted arithmetic types L and R, there
7722 // exist candidate operator functions of the form
7723 //
7724 // LR operator*(L, R);
7725 // LR operator/(L, R);
7726 // LR operator+(L, R);
7727 // LR operator-(L, R);
7728 // bool operator<(L, R);
7729 // bool operator>(L, R);
7730 // bool operator<=(L, R);
7731 // bool operator>=(L, R);
7732 // bool operator==(L, R);
7733 // bool operator!=(L, R);
7734 //
7735 // where LR is the result of the usual arithmetic conversions
7736 // between types L and R.
7737 //
7738 // C++ [over.built]p24:
7739 //
7740 // For every pair of promoted arithmetic types L and R, there exist
7741 // candidate operator functions of the form
7742 //
7743 // LR operator?(bool, L, R);
7744 //
7745 // where LR is the result of the usual arithmetic conversions
7746 // between types L and R.
7747 // Our candidates ignore the first parameter.
7748 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007749 if (!HasArithmeticOrEnumeralCandidateType)
7750 return;
7751
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007752 for (unsigned Left = FirstPromotedArithmeticType;
7753 Left < LastPromotedArithmeticType; ++Left) {
7754 for (unsigned Right = FirstPromotedArithmeticType;
7755 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007756 QualType LandR[2] = { getArithmeticType(Left),
7757 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007758 QualType Result =
7759 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007760 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007761 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007762 }
7763 }
7764
7765 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7766 // conditional operator for vector types.
7767 for (BuiltinCandidateTypeSet::iterator
7768 Vec1 = CandidateTypes[0].vector_begin(),
7769 Vec1End = CandidateTypes[0].vector_end();
7770 Vec1 != Vec1End; ++Vec1) {
7771 for (BuiltinCandidateTypeSet::iterator
7772 Vec2 = CandidateTypes[1].vector_begin(),
7773 Vec2End = CandidateTypes[1].vector_end();
7774 Vec2 != Vec2End; ++Vec2) {
7775 QualType LandR[2] = { *Vec1, *Vec2 };
7776 QualType Result = S.Context.BoolTy;
7777 if (!isComparison) {
7778 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7779 Result = *Vec1;
7780 else
7781 Result = *Vec2;
7782 }
7783
Richard Smithe54c3072013-05-05 15:51:06 +00007784 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007785 }
7786 }
7787 }
7788
7789 // C++ [over.built]p17:
7790 //
7791 // For every pair of promoted integral types L and R, there
7792 // exist candidate operator functions of the form
7793 //
7794 // LR operator%(L, R);
7795 // LR operator&(L, R);
7796 // LR operator^(L, R);
7797 // LR operator|(L, R);
7798 // L operator<<(L, R);
7799 // L operator>>(L, R);
7800 //
7801 // where LR is the result of the usual arithmetic conversions
7802 // between types L and R.
7803 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007804 if (!HasArithmeticOrEnumeralCandidateType)
7805 return;
7806
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007807 for (unsigned Left = FirstPromotedIntegralType;
7808 Left < LastPromotedIntegralType; ++Left) {
7809 for (unsigned Right = FirstPromotedIntegralType;
7810 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007811 QualType LandR[2] = { getArithmeticType(Left),
7812 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007813 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7814 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007815 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007816 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007817 }
7818 }
7819 }
7820
7821 // C++ [over.built]p20:
7822 //
7823 // For every pair (T, VQ), where T is an enumeration or
7824 // pointer to member type and VQ is either volatile or
7825 // empty, there exist candidate operator functions of the form
7826 //
7827 // VQ T& operator=(VQ T&, T);
7828 void addAssignmentMemberPointerOrEnumeralOverloads() {
7829 /// Set of (canonical) types that we've already handled.
7830 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7831
7832 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7833 for (BuiltinCandidateTypeSet::iterator
7834 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7835 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7836 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007837 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007838 continue;
7839
Richard Smithe54c3072013-05-05 15:51:06 +00007840 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007841 }
7842
7843 for (BuiltinCandidateTypeSet::iterator
7844 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7845 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7846 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007847 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007848 continue;
7849
Richard Smithe54c3072013-05-05 15:51:06 +00007850 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007851 }
7852 }
7853 }
7854
7855 // C++ [over.built]p19:
7856 //
7857 // For every pair (T, VQ), where T is any type and VQ is either
7858 // volatile or empty, there exist candidate operator functions
7859 // of the form
7860 //
7861 // T*VQ& operator=(T*VQ&, T*);
7862 //
7863 // C++ [over.built]p21:
7864 //
7865 // For every pair (T, VQ), where T is a cv-qualified or
7866 // cv-unqualified object type and VQ is either volatile or
7867 // empty, there exist candidate operator functions of the form
7868 //
7869 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7870 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7871 void addAssignmentPointerOverloads(bool isEqualOp) {
7872 /// Set of (canonical) types that we've already handled.
7873 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7874
7875 for (BuiltinCandidateTypeSet::iterator
7876 Ptr = CandidateTypes[0].pointer_begin(),
7877 PtrEnd = CandidateTypes[0].pointer_end();
7878 Ptr != PtrEnd; ++Ptr) {
7879 // If this is operator=, keep track of the builtin candidates we added.
7880 if (isEqualOp)
7881 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007882 else if (!(*Ptr)->getPointeeType()->isObjectType())
7883 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884
7885 // non-volatile version
7886 QualType ParamTypes[2] = {
7887 S.Context.getLValueReferenceType(*Ptr),
7888 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7889 };
Richard Smithe54c3072013-05-05 15:51:06 +00007890 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007891 /*IsAssigmentOperator=*/ isEqualOp);
7892
Douglas Gregor5bee2582012-06-04 00:15:09 +00007893 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7894 VisibleTypeConversionsQuals.hasVolatile();
7895 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007896 // volatile version
7897 ParamTypes[0] =
7898 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007900 /*IsAssigmentOperator=*/isEqualOp);
7901 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007902
7903 if (!(*Ptr).isRestrictQualified() &&
7904 VisibleTypeConversionsQuals.hasRestrict()) {
7905 // restrict version
7906 ParamTypes[0]
7907 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007908 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007909 /*IsAssigmentOperator=*/isEqualOp);
7910
7911 if (NeedVolatile) {
7912 // volatile restrict version
7913 ParamTypes[0]
7914 = S.Context.getLValueReferenceType(
7915 S.Context.getCVRQualifiedType(*Ptr,
7916 (Qualifiers::Volatile |
7917 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007918 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007919 /*IsAssigmentOperator=*/isEqualOp);
7920 }
7921 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007922 }
7923
7924 if (isEqualOp) {
7925 for (BuiltinCandidateTypeSet::iterator
7926 Ptr = CandidateTypes[1].pointer_begin(),
7927 PtrEnd = CandidateTypes[1].pointer_end();
7928 Ptr != PtrEnd; ++Ptr) {
7929 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007930 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007931 continue;
7932
Chandler Carruth8e543b32010-12-12 08:17:55 +00007933 QualType ParamTypes[2] = {
7934 S.Context.getLValueReferenceType(*Ptr),
7935 *Ptr,
7936 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007937
7938 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007939 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007940 /*IsAssigmentOperator=*/true);
7941
Douglas Gregor5bee2582012-06-04 00:15:09 +00007942 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7943 VisibleTypeConversionsQuals.hasVolatile();
7944 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007945 // volatile version
7946 ParamTypes[0] =
7947 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007948 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7949 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007950 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007951
7952 if (!(*Ptr).isRestrictQualified() &&
7953 VisibleTypeConversionsQuals.hasRestrict()) {
7954 // restrict version
7955 ParamTypes[0]
7956 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007957 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7958 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007959
7960 if (NeedVolatile) {
7961 // volatile restrict version
7962 ParamTypes[0]
7963 = S.Context.getLValueReferenceType(
7964 S.Context.getCVRQualifiedType(*Ptr,
7965 (Qualifiers::Volatile |
7966 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007967 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7968 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007969 }
7970 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007971 }
7972 }
7973 }
7974
7975 // C++ [over.built]p18:
7976 //
7977 // For every triple (L, VQ, R), where L is an arithmetic type,
7978 // VQ is either volatile or empty, and R is a promoted
7979 // arithmetic type, there exist candidate operator functions of
7980 // the form
7981 //
7982 // VQ L& operator=(VQ L&, R);
7983 // VQ L& operator*=(VQ L&, R);
7984 // VQ L& operator/=(VQ L&, R);
7985 // VQ L& operator+=(VQ L&, R);
7986 // VQ L& operator-=(VQ L&, R);
7987 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007988 if (!HasArithmeticOrEnumeralCandidateType)
7989 return;
7990
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007991 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7992 for (unsigned Right = FirstPromotedArithmeticType;
7993 Right < LastPromotedArithmeticType; ++Right) {
7994 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007995 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007996
7997 // Add this built-in operator as a candidate (VQ is empty).
7998 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007999 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008000 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008001 /*IsAssigmentOperator=*/isEqualOp);
8002
8003 // Add this built-in operator as a candidate (VQ is 'volatile').
8004 if (VisibleTypeConversionsQuals.hasVolatile()) {
8005 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008006 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008007 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008009 /*IsAssigmentOperator=*/isEqualOp);
8010 }
8011 }
8012 }
8013
8014 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8015 for (BuiltinCandidateTypeSet::iterator
8016 Vec1 = CandidateTypes[0].vector_begin(),
8017 Vec1End = CandidateTypes[0].vector_end();
8018 Vec1 != Vec1End; ++Vec1) {
8019 for (BuiltinCandidateTypeSet::iterator
8020 Vec2 = CandidateTypes[1].vector_begin(),
8021 Vec2End = CandidateTypes[1].vector_end();
8022 Vec2 != Vec2End; ++Vec2) {
8023 QualType ParamTypes[2];
8024 ParamTypes[1] = *Vec2;
8025 // Add this built-in operator as a candidate (VQ is empty).
8026 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008027 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008028 /*IsAssigmentOperator=*/isEqualOp);
8029
8030 // Add this built-in operator as a candidate (VQ is 'volatile').
8031 if (VisibleTypeConversionsQuals.hasVolatile()) {
8032 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8033 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008034 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008035 /*IsAssigmentOperator=*/isEqualOp);
8036 }
8037 }
8038 }
8039 }
8040
8041 // C++ [over.built]p22:
8042 //
8043 // For every triple (L, VQ, R), where L is an integral type, VQ
8044 // is either volatile or empty, and R is a promoted integral
8045 // type, there exist candidate operator functions of the form
8046 //
8047 // VQ L& operator%=(VQ L&, R);
8048 // VQ L& operator<<=(VQ L&, R);
8049 // VQ L& operator>>=(VQ L&, R);
8050 // VQ L& operator&=(VQ L&, R);
8051 // VQ L& operator^=(VQ L&, R);
8052 // VQ L& operator|=(VQ L&, R);
8053 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008054 if (!HasArithmeticOrEnumeralCandidateType)
8055 return;
8056
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008057 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8058 for (unsigned Right = FirstPromotedIntegralType;
8059 Right < LastPromotedIntegralType; ++Right) {
8060 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008061 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008062
8063 // Add this built-in operator as a candidate (VQ is empty).
8064 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008065 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008066 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008067 if (VisibleTypeConversionsQuals.hasVolatile()) {
8068 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008069 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008070 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8071 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008072 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008073 }
8074 }
8075 }
8076 }
8077
8078 // C++ [over.operator]p23:
8079 //
8080 // There also exist candidate operator functions of the form
8081 //
8082 // bool operator!(bool);
8083 // bool operator&&(bool, bool);
8084 // bool operator||(bool, bool);
8085 void addExclaimOverload() {
8086 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008087 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008088 /*IsAssignmentOperator=*/false,
8089 /*NumContextualBoolArguments=*/1);
8090 }
8091 void addAmpAmpOrPipePipeOverload() {
8092 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008093 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008094 /*IsAssignmentOperator=*/false,
8095 /*NumContextualBoolArguments=*/2);
8096 }
8097
8098 // C++ [over.built]p13:
8099 //
8100 // For every cv-qualified or cv-unqualified object type T there
8101 // exist candidate operator functions of the form
8102 //
8103 // T* operator+(T*, ptrdiff_t); [ABOVE]
8104 // T& operator[](T*, ptrdiff_t);
8105 // T* operator-(T*, ptrdiff_t); [ABOVE]
8106 // T* operator+(ptrdiff_t, T*); [ABOVE]
8107 // T& operator[](ptrdiff_t, T*);
8108 void addSubscriptOverloads() {
8109 for (BuiltinCandidateTypeSet::iterator
8110 Ptr = CandidateTypes[0].pointer_begin(),
8111 PtrEnd = CandidateTypes[0].pointer_end();
8112 Ptr != PtrEnd; ++Ptr) {
8113 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8114 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008115 if (!PointeeType->isObjectType())
8116 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008117
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008118 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8119
8120 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008121 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008122 }
8123
8124 for (BuiltinCandidateTypeSet::iterator
8125 Ptr = CandidateTypes[1].pointer_begin(),
8126 PtrEnd = CandidateTypes[1].pointer_end();
8127 Ptr != PtrEnd; ++Ptr) {
8128 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8129 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008130 if (!PointeeType->isObjectType())
8131 continue;
8132
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008133 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8134
8135 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008136 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008137 }
8138 }
8139
8140 // C++ [over.built]p11:
8141 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8142 // C1 is the same type as C2 or is a derived class of C2, T is an object
8143 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8144 // there exist candidate operator functions of the form
8145 //
8146 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8147 //
8148 // where CV12 is the union of CV1 and CV2.
8149 void addArrowStarOverloads() {
8150 for (BuiltinCandidateTypeSet::iterator
8151 Ptr = CandidateTypes[0].pointer_begin(),
8152 PtrEnd = CandidateTypes[0].pointer_end();
8153 Ptr != PtrEnd; ++Ptr) {
8154 QualType C1Ty = (*Ptr);
8155 QualType C1;
8156 QualifierCollector Q1;
8157 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8158 if (!isa<RecordType>(C1))
8159 continue;
8160 // heuristic to reduce number of builtin candidates in the set.
8161 // Add volatile/restrict version only if there are conversions to a
8162 // volatile/restrict type.
8163 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8164 continue;
8165 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8166 continue;
8167 for (BuiltinCandidateTypeSet::iterator
8168 MemPtr = CandidateTypes[1].member_pointer_begin(),
8169 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8170 MemPtr != MemPtrEnd; ++MemPtr) {
8171 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8172 QualType C2 = QualType(mptr->getClass(), 0);
8173 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008174 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008175 break;
8176 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8177 // build CV12 T&
8178 QualType T = mptr->getPointeeType();
8179 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8180 T.isVolatileQualified())
8181 continue;
8182 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8183 T.isRestrictQualified())
8184 continue;
8185 T = Q1.apply(S.Context, T);
8186 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008187 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008188 }
8189 }
8190 }
8191
8192 // Note that we don't consider the first argument, since it has been
8193 // contextually converted to bool long ago. The candidates below are
8194 // therefore added as binary.
8195 //
8196 // C++ [over.built]p25:
8197 // For every type T, where T is a pointer, pointer-to-member, or scoped
8198 // enumeration type, there exist candidate operator functions of the form
8199 //
8200 // T operator?(bool, T, T);
8201 //
8202 void addConditionalOperatorOverloads() {
8203 /// Set of (canonical) types that we've already handled.
8204 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8205
8206 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8207 for (BuiltinCandidateTypeSet::iterator
8208 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8209 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8210 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008211 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008212 continue;
8213
8214 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008215 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008216 }
8217
8218 for (BuiltinCandidateTypeSet::iterator
8219 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8220 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8221 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008222 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008223 continue;
8224
8225 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008226 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008227 }
8228
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008229 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008230 for (BuiltinCandidateTypeSet::iterator
8231 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8232 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8233 Enum != EnumEnd; ++Enum) {
8234 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8235 continue;
8236
David Blaikie82e95a32014-11-19 07:49:47 +00008237 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008238 continue;
8239
8240 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008241 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008242 }
8243 }
8244 }
8245 }
8246};
8247
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008248} // end anonymous namespace
8249
8250/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8251/// operator overloads to the candidate set (C++ [over.built]), based
8252/// on the operator @p Op and the arguments given. For example, if the
8253/// operator is a binary '+', this routine might add "int
8254/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008255void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8256 SourceLocation OpLoc,
8257 ArrayRef<Expr *> Args,
8258 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008259 // Find all of the types that the arguments can convert to, but only
8260 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008261 // that make use of these types. Also record whether we encounter non-record
8262 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008263 Qualifiers VisibleTypeConversionsQuals;
8264 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008265 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008266 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008267
8268 bool HasNonRecordCandidateType = false;
8269 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008270 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008271 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008272 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008273 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8274 OpLoc,
8275 true,
8276 (Op == OO_Exclaim ||
8277 Op == OO_AmpAmp ||
8278 Op == OO_PipePipe),
8279 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008280 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8281 CandidateTypes[ArgIdx].hasNonRecordTypes();
8282 HasArithmeticOrEnumeralCandidateType =
8283 HasArithmeticOrEnumeralCandidateType ||
8284 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008285 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008286
Chandler Carruth00a38332010-12-13 01:44:01 +00008287 // Exit early when no non-record types have been added to the candidate set
8288 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008289 //
8290 // We can't exit early for !, ||, or &&, since there we have always have
8291 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008292 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008293 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008294 return;
8295
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008296 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008297 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008298 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008299 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008300 CandidateTypes, CandidateSet);
8301
8302 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008303 switch (Op) {
8304 case OO_None:
8305 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008306 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008307
Chandler Carruth5184de02010-12-12 08:51:33 +00008308 case OO_New:
8309 case OO_Delete:
8310 case OO_Array_New:
8311 case OO_Array_Delete:
8312 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008313 llvm_unreachable(
8314 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008315
8316 case OO_Comma:
8317 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008318 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008319 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008320 // -- For the operator ',', the unary operator '&', the
8321 // operator '->', or the operator 'co_await', the
8322 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008323 break;
8324
8325 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008326 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008327 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008328 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008329
8330 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008331 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008332 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008333 } else {
8334 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8335 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8336 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008337 break;
8338
Chandler Carruth5184de02010-12-12 08:51:33 +00008339 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008340 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008341 OpBuilder.addUnaryStarPointerOverloads();
8342 else
8343 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8344 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008345
Chandler Carruth5184de02010-12-12 08:51:33 +00008346 case OO_Slash:
8347 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008348 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008349
8350 case OO_PlusPlus:
8351 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008352 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8353 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008354 break;
8355
Douglas Gregor84605ae2009-08-24 13:43:27 +00008356 case OO_EqualEqual:
8357 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008358 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008359 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008360
Douglas Gregora11693b2008-11-12 17:17:38 +00008361 case OO_Less:
8362 case OO_Greater:
8363 case OO_LessEqual:
8364 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008365 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008366 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8367 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008368
Douglas Gregora11693b2008-11-12 17:17:38 +00008369 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008370 case OO_Caret:
8371 case OO_Pipe:
8372 case OO_LessLess:
8373 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008374 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008375 break;
8376
Chandler Carruth5184de02010-12-12 08:51:33 +00008377 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008378 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008379 // C++ [over.match.oper]p3:
8380 // -- For the operator ',', the unary operator '&', or the
8381 // operator '->', the built-in candidates set is empty.
8382 break;
8383
8384 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8385 break;
8386
8387 case OO_Tilde:
8388 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8389 break;
8390
Douglas Gregora11693b2008-11-12 17:17:38 +00008391 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008392 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008393 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008394
8395 case OO_PlusEqual:
8396 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008397 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008398 // Fall through.
8399
8400 case OO_StarEqual:
8401 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008402 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008403 break;
8404
8405 case OO_PercentEqual:
8406 case OO_LessLessEqual:
8407 case OO_GreaterGreaterEqual:
8408 case OO_AmpEqual:
8409 case OO_CaretEqual:
8410 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008411 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008412 break;
8413
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008414 case OO_Exclaim:
8415 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008416 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008417
Douglas Gregora11693b2008-11-12 17:17:38 +00008418 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008419 case OO_PipePipe:
8420 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008421 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008422
8423 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008424 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008425 break;
8426
8427 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008428 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008429 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008430
8431 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008432 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008433 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8434 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008435 }
8436}
8437
Douglas Gregore254f902009-02-04 00:32:51 +00008438/// \brief Add function candidates found via argument-dependent lookup
8439/// to the set of overloading candidates.
8440///
8441/// This routine performs argument-dependent name lookup based on the
8442/// given function name (which may also be an operator name) and adds
8443/// all of the overload candidates found by ADL to the overload
8444/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008445void
Douglas Gregore254f902009-02-04 00:32:51 +00008446Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008447 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008448 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008449 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008450 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008451 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008452 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008453
John McCall91f61fc2010-01-26 06:04:06 +00008454 // FIXME: This approach for uniquing ADL results (and removing
8455 // redundant candidates from the set) relies on pointer-equality,
8456 // which means we need to key off the canonical decl. However,
8457 // always going back to the canonical decl might not get us the
8458 // right set of default arguments. What default arguments are
8459 // we supposed to consider on ADL candidates, anyway?
8460
Douglas Gregorcabea402009-09-22 15:41:20 +00008461 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008462 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008463
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008464 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008465 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8466 CandEnd = CandidateSet.end();
8467 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008468 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008469 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008470 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008471 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008472 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008473
8474 // For each of the ADL candidates we found, add it to the overload
8475 // set.
John McCall8fe68082010-01-26 07:16:45 +00008476 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008477 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008478 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008479 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008480 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008481
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008482 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8483 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008484 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008485 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008486 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008487 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008488 }
Douglas Gregore254f902009-02-04 00:32:51 +00008489}
8490
George Burgess IV2a6150d2015-10-16 01:17:38 +00008491// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8492// Cand2 for overloading. This function assumes that all of the enable_if attrs
8493// on Cand1 and Cand2 have conditions that evaluate to true.
8494//
8495// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8496// Cand1's first N enable_if attributes have precisely the same conditions as
8497// Cand2's first N enable_if attributes (where N = the number of enable_if
8498// attributes on Cand2), and Cand1 has more than N enable_if attributes.
George Burgess IV6da4c202016-03-23 02:33:58 +00008499static bool hasBetterEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
George Burgess IV2a6150d2015-10-16 01:17:38 +00008500 const FunctionDecl *Cand2) {
8501
8502 // FIXME: The next several lines are just
8503 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8504 // instead of reverse order which is how they're stored in the AST.
8505 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8506 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8507
8508 // Candidate 1 is better if it has strictly more attributes and
8509 // the common sequence is identical.
8510 if (Cand1Attrs.size() <= Cand2Attrs.size())
8511 return false;
8512
8513 auto Cand1I = Cand1Attrs.begin();
8514 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8515 for (auto &Cand2A : Cand2Attrs) {
8516 Cand1ID.clear();
8517 Cand2ID.clear();
8518
8519 auto &Cand1A = *Cand1I++;
8520 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8521 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8522 if (Cand1ID != Cand2ID)
8523 return false;
8524 }
8525
8526 return true;
8527}
8528
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008529/// isBetterOverloadCandidate - Determines whether the first overload
8530/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008531bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8532 const OverloadCandidate &Cand2,
8533 SourceLocation Loc,
8534 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008535 // Define viable functions to be better candidates than non-viable
8536 // functions.
8537 if (!Cand2.Viable)
8538 return Cand1.Viable;
8539 else if (!Cand1.Viable)
8540 return false;
8541
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008542 // C++ [over.match.best]p1:
8543 //
8544 // -- if F is a static member function, ICS1(F) is defined such
8545 // that ICS1(F) is neither better nor worse than ICS1(G) for
8546 // any function G, and, symmetrically, ICS1(G) is neither
8547 // better nor worse than ICS1(F).
8548 unsigned StartArg = 0;
8549 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8550 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008551
Douglas Gregord3cb3562009-07-07 23:38:56 +00008552 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008553 // A viable function F1 is defined to be a better function than another
8554 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008555 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008556 unsigned NumArgs = Cand1.NumConversions;
8557 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008558 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008559 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008560 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008561 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008562 Cand2.Conversions[ArgIdx])) {
8563 case ImplicitConversionSequence::Better:
8564 // Cand1 has a better conversion sequence.
8565 HasBetterConversion = true;
8566 break;
8567
8568 case ImplicitConversionSequence::Worse:
8569 // Cand1 can't be better than Cand2.
8570 return false;
8571
8572 case ImplicitConversionSequence::Indistinguishable:
8573 // Do nothing.
8574 break;
8575 }
8576 }
8577
Mike Stump11289f42009-09-09 15:08:12 +00008578 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008579 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008580 if (HasBetterConversion)
8581 return true;
8582
Douglas Gregora1f013e2008-11-07 22:36:19 +00008583 // -- the context is an initialization by user-defined conversion
8584 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8585 // from the return type of F1 to the destination type (i.e.,
8586 // the type of the entity being initialized) is a better
8587 // conversion sequence than the standard conversion sequence
8588 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008589 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008590 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008591 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008592 // First check whether we prefer one of the conversion functions over the
8593 // other. This only distinguishes the results in non-standard, extension
8594 // cases such as the conversion from a lambda closure type to a function
8595 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008596 ImplicitConversionSequence::CompareKind Result =
8597 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8598 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008599 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008600 Cand1.FinalConversion,
8601 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008602
Richard Smithec2748a2014-05-17 04:36:39 +00008603 if (Result != ImplicitConversionSequence::Indistinguishable)
8604 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008605
8606 // FIXME: Compare kind of reference binding if conversion functions
8607 // convert to a reference type used in direct reference binding, per
8608 // C++14 [over.match.best]p1 section 2 bullet 3.
8609 }
8610
8611 // -- F1 is a non-template function and F2 is a function template
8612 // specialization, or, if not that,
8613 bool Cand1IsSpecialization = Cand1.Function &&
8614 Cand1.Function->getPrimaryTemplate();
8615 bool Cand2IsSpecialization = Cand2.Function &&
8616 Cand2.Function->getPrimaryTemplate();
8617 if (Cand1IsSpecialization != Cand2IsSpecialization)
8618 return Cand2IsSpecialization;
8619
8620 // -- F1 and F2 are function template specializations, and the function
8621 // template for F1 is more specialized than the template for F2
8622 // according to the partial ordering rules described in 14.5.5.2, or,
8623 // if not that,
8624 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8625 if (FunctionTemplateDecl *BetterTemplate
8626 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8627 Cand2.Function->getPrimaryTemplate(),
8628 Loc,
8629 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8630 : TPOC_Call,
8631 Cand1.ExplicitCallArguments,
8632 Cand2.ExplicitCallArguments))
8633 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008634 }
8635
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008636 // Check for enable_if value-based overload resolution.
8637 if (Cand1.Function && Cand2.Function &&
8638 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008639 Cand2.Function->hasAttr<EnableIfAttr>()))
8640 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008641
Justin Lebar25c4a812016-03-29 16:24:16 +00008642 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008643 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8644 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8645 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8646 }
8647
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008648 bool HasPS1 = Cand1.Function != nullptr &&
8649 functionHasPassObjectSizeParams(Cand1.Function);
8650 bool HasPS2 = Cand2.Function != nullptr &&
8651 functionHasPassObjectSizeParams(Cand2.Function);
8652 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008653}
8654
Richard Smith2dbe4042015-11-04 19:26:32 +00008655/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008656/// name lookup and overload resolution. This applies when the same internal/no
8657/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008658/// the same header). In such a case, we don't consider the declarations to
8659/// declare the same entity, but we also don't want lookups with both
8660/// declarations visible to be ambiguous in some cases (this happens when using
8661/// a modularized libstdc++).
8662bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8663 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008664 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8665 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8666 if (!VA || !VB)
8667 return false;
8668
8669 // The declarations must be declaring the same name as an internal linkage
8670 // entity in different modules.
8671 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8672 VB->getDeclContext()->getRedeclContext()) ||
8673 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8674 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8675 VA->isExternallyVisible() || VB->isExternallyVisible())
8676 return false;
8677
8678 // Check that the declarations appear to be equivalent.
8679 //
8680 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8681 // For constants and functions, we should check the initializer or body is
8682 // the same. For non-constant variables, we shouldn't allow it at all.
8683 if (Context.hasSameType(VA->getType(), VB->getType()))
8684 return true;
8685
8686 // Enum constants within unnamed enumerations will have different types, but
8687 // may still be similar enough to be interchangeable for our purposes.
8688 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8689 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8690 // Only handle anonymous enums. If the enumerations were named and
8691 // equivalent, they would have been merged to the same type.
8692 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8693 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8694 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8695 !Context.hasSameType(EnumA->getIntegerType(),
8696 EnumB->getIntegerType()))
8697 return false;
8698 // Allow this only if the value is the same for both enumerators.
8699 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8700 }
8701 }
8702
8703 // Nothing else is sufficiently similar.
8704 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008705}
8706
8707void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8708 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8709 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8710
8711 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8712 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8713 << !M << (M ? M->getFullModuleName() : "");
8714
8715 for (auto *E : Equiv) {
8716 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8717 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8718 << !M << (M ? M->getFullModuleName() : "");
8719 }
Richard Smith896c66e2015-10-21 07:13:52 +00008720}
8721
Mike Stump11289f42009-09-09 15:08:12 +00008722/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008723/// within an overload candidate set.
8724///
James Dennettffad8b72012-06-22 08:10:18 +00008725/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008726/// which overload resolution occurs.
8727///
James Dennettffad8b72012-06-22 08:10:18 +00008728/// \param Best If overload resolution was successful or found a deleted
8729/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008730///
8731/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008732OverloadingResult
8733OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008734 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008735 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008736 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8737 std::transform(begin(), end(), std::back_inserter(Candidates),
8738 [](OverloadCandidate &Cand) { return &Cand; });
8739
8740 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA
8741 // but accepted by both clang and NVCC. However during a particular
8742 // compilation mode only one call variant is viable. We need to
8743 // exclude non-viable overload candidates from consideration based
8744 // only on their host/device attributes. Specifically, if one
8745 // candidate call is WrongSide and the other is SameSide, we ignore
8746 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008747 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008748 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8749 bool ContainsSameSideCandidate =
8750 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8751 return Cand->Function &&
8752 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8753 Sema::CFP_SameSide;
8754 });
8755 if (ContainsSameSideCandidate) {
8756 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8757 return Cand->Function &&
8758 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8759 Sema::CFP_WrongSide;
8760 };
8761 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8762 IsWrongSideCandidate),
8763 Candidates.end());
8764 }
8765 }
8766
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008767 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008768 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008769 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008770 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008771 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008772 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008773 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008774
8775 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008776 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008777 return OR_No_Viable_Function;
8778
Richard Smith2dbe4042015-11-04 19:26:32 +00008779 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008780
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008781 // Make sure that this function is better than every other viable
8782 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008783 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008784 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008785 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008786 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008787 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008788 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8789 Cand->Function)) {
8790 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008791 continue;
8792 }
8793
John McCall5c32be02010-08-24 20:38:10 +00008794 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008795 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008796 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008797 }
Mike Stump11289f42009-09-09 15:08:12 +00008798
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008799 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008800 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008801 (Best->Function->isDeleted() ||
8802 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008803 return OR_Deleted;
8804
Richard Smith2dbe4042015-11-04 19:26:32 +00008805 if (!EquivalentCands.empty())
8806 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8807 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008808
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008809 return OR_Success;
8810}
8811
John McCall53262c92010-01-12 02:15:36 +00008812namespace {
8813
8814enum OverloadCandidateKind {
8815 oc_function,
8816 oc_method,
8817 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008818 oc_function_template,
8819 oc_method_template,
8820 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008821 oc_implicit_default_constructor,
8822 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008823 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008824 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008825 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008826 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008827};
8828
John McCalle1ac8d12010-01-13 00:25:19 +00008829OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8830 FunctionDecl *Fn,
8831 std::string &Description) {
8832 bool isTemplate = false;
8833
8834 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8835 isTemplate = true;
8836 Description = S.getTemplateArgumentBindingsText(
8837 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8838 }
John McCallfd0b2f82010-01-06 09:43:14 +00008839
8840 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008841 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008842 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008843
Sebastian Redl08905022011-02-05 19:23:19 +00008844 if (Ctor->getInheritedConstructor())
8845 return oc_implicit_inherited_constructor;
8846
Alexis Hunt119c10e2011-05-25 23:16:36 +00008847 if (Ctor->isDefaultConstructor())
8848 return oc_implicit_default_constructor;
8849
8850 if (Ctor->isMoveConstructor())
8851 return oc_implicit_move_constructor;
8852
8853 assert(Ctor->isCopyConstructor() &&
8854 "unexpected sort of implicit constructor");
8855 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008856 }
8857
8858 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8859 // This actually gets spelled 'candidate function' for now, but
8860 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008861 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008862 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008863
Alexis Hunt119c10e2011-05-25 23:16:36 +00008864 if (Meth->isMoveAssignmentOperator())
8865 return oc_implicit_move_assignment;
8866
Douglas Gregor12695102012-02-10 08:36:38 +00008867 if (Meth->isCopyAssignmentOperator())
8868 return oc_implicit_copy_assignment;
8869
8870 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8871 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008872 }
8873
John McCalle1ac8d12010-01-13 00:25:19 +00008874 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008875}
8876
Larisse Voufo98b20f12013-07-19 23:00:19 +00008877void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008878 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8879 if (!Ctor) return;
8880
8881 Ctor = Ctor->getInheritedConstructor();
8882 if (!Ctor) return;
8883
8884 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8885}
8886
John McCall53262c92010-01-12 02:15:36 +00008887} // end anonymous namespace
8888
George Burgess IV5f21c712015-10-12 19:57:04 +00008889static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8890 const FunctionDecl *FD) {
8891 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8892 bool AlwaysTrue;
8893 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8894 return false;
8895 if (!AlwaysTrue)
8896 return false;
8897 }
8898 return true;
8899}
8900
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008901/// \brief Returns true if we can take the address of the function.
8902///
8903/// \param Complain - If true, we'll emit a diagnostic
8904/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8905/// we in overload resolution?
8906/// \param Loc - The location of the statement we're complaining about. Ignored
8907/// if we're not complaining, or if we're in overload resolution.
8908static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8909 bool Complain,
8910 bool InOverloadResolution,
8911 SourceLocation Loc) {
8912 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8913 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008914 if (InOverloadResolution)
8915 S.Diag(FD->getLocStart(),
8916 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8917 else
8918 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8919 }
8920 return false;
8921 }
8922
8923 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8924 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8925 if (I == FD->param_end())
8926 return true;
8927
8928 if (Complain) {
8929 // Add one to ParamNo because it's user-facing
8930 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8931 if (InOverloadResolution)
8932 S.Diag(FD->getLocation(),
8933 diag::note_ovl_candidate_has_pass_object_size_params)
8934 << ParamNo;
8935 else
8936 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8937 << FD << ParamNo;
8938 }
8939 return false;
8940}
8941
8942static bool checkAddressOfCandidateIsAvailable(Sema &S,
8943 const FunctionDecl *FD) {
8944 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8945 /*InOverloadResolution=*/true,
8946 /*Loc=*/SourceLocation());
8947}
8948
8949bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8950 bool Complain,
8951 SourceLocation Loc) {
8952 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8953 /*InOverloadResolution=*/false,
8954 Loc);
8955}
8956
John McCall53262c92010-01-12 02:15:36 +00008957// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008958void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8959 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008960 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8961 return;
8962
John McCalle1ac8d12010-01-13 00:25:19 +00008963 std::string FnDesc;
8964 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008965 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8966 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008967
8968 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008969 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008970 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008971}
8972
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008973// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008974// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008975void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8976 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008977 assert(OverloadedExpr->getType() == Context.OverloadTy);
8978
8979 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8980 OverloadExpr *OvlExpr = Ovl.Expression;
8981
8982 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8983 IEnd = OvlExpr->decls_end();
8984 I != IEnd; ++I) {
8985 if (FunctionTemplateDecl *FunTmpl =
8986 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008987 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8988 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008989 } else if (FunctionDecl *Fun
8990 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008991 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008992 }
8993 }
8994}
8995
John McCall0d1da222010-01-12 00:44:57 +00008996/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8997/// "lead" diagnostic; it will be given two arguments, the source and
8998/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008999void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9000 Sema &S,
9001 SourceLocation CaretLoc,
9002 const PartialDiagnostic &PDiag) const {
9003 S.Diag(CaretLoc, PDiag)
9004 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009005 // FIXME: The note limiting machinery is borrowed from
9006 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9007 // refactoring here.
9008 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9009 unsigned CandsShown = 0;
9010 AmbiguousConversionSequence::const_iterator I, E;
9011 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9012 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9013 break;
9014 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00009015 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00009016 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009017 if (I != E)
9018 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009019}
9020
Richard Smith17c00b42014-11-12 01:24:00 +00009021static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009022 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009023 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9024 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009025 assert(Cand->Function && "for now, candidate must be a function");
9026 FunctionDecl *Fn = Cand->Function;
9027
9028 // There's a conversion slot for the object argument if this is a
9029 // non-constructor method. Note that 'I' corresponds the
9030 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009031 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009032 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009033 if (I == 0)
9034 isObjectArgument = true;
9035 else
9036 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009037 }
9038
John McCalle1ac8d12010-01-13 00:25:19 +00009039 std::string FnDesc;
9040 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9041
John McCall6a61b522010-01-13 09:16:55 +00009042 Expr *FromExpr = Conv.Bad.FromExpr;
9043 QualType FromTy = Conv.Bad.getFromType();
9044 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009045
John McCallfb7ad0f2010-02-02 02:42:52 +00009046 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009047 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009048 Expr *E = FromExpr->IgnoreParens();
9049 if (isa<UnaryOperator>(E))
9050 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009051 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009052
9053 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9054 << (unsigned) FnKind << FnDesc
9055 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9056 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009057 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00009058 return;
9059 }
9060
John McCall6d174642010-01-23 08:10:49 +00009061 // Do some hand-waving analysis to see if the non-viability is due
9062 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009063 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9064 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9065 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9066 CToTy = RT->getPointeeType();
9067 else {
9068 // TODO: detect and diagnose the full richness of const mismatches.
9069 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009070 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9071 CFromTy = FromPT->getPointeeType();
9072 CToTy = ToPT->getPointeeType();
9073 }
John McCall47000992010-01-14 03:28:57 +00009074 }
9075
9076 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9077 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009078 Qualifiers FromQs = CFromTy.getQualifiers();
9079 Qualifiers ToQs = CToTy.getQualifiers();
9080
9081 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9083 << (unsigned) FnKind << FnDesc
9084 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9085 << FromTy
9086 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9087 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009088 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009089 return;
9090 }
9091
John McCall31168b02011-06-15 23:02:42 +00009092 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009094 << (unsigned) FnKind << FnDesc
9095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9096 << FromTy
9097 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9098 << (unsigned) isObjectArgument << I+1;
9099 MaybeEmitInheritedConstructorNote(S, Fn);
9100 return;
9101 }
9102
Douglas Gregoraec25842011-04-26 23:16:46 +00009103 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9105 << (unsigned) FnKind << FnDesc
9106 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9107 << FromTy
9108 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9109 << (unsigned) isObjectArgument << I+1;
9110 MaybeEmitInheritedConstructorNote(S, Fn);
9111 return;
9112 }
9113
John McCall47000992010-01-14 03:28:57 +00009114 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9115 assert(CVR && "unexpected qualifiers mismatch");
9116
9117 if (isObjectArgument) {
9118 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9119 << (unsigned) FnKind << FnDesc
9120 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9121 << FromTy << (CVR - 1);
9122 } else {
9123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9124 << (unsigned) FnKind << FnDesc
9125 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9126 << FromTy << (CVR - 1) << I+1;
9127 }
Sebastian Redl08905022011-02-05 19:23:19 +00009128 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009129 return;
9130 }
9131
Sebastian Redla72462c2011-09-24 17:48:32 +00009132 // Special diagnostic for failure to convert an initializer list, since
9133 // telling the user that it has type void is not useful.
9134 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9136 << (unsigned) FnKind << FnDesc
9137 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9138 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9139 MaybeEmitInheritedConstructorNote(S, Fn);
9140 return;
9141 }
9142
John McCall6d174642010-01-23 08:10:49 +00009143 // Diagnose references or pointers to incomplete types differently,
9144 // since it's far from impossible that the incompleteness triggered
9145 // the failure.
9146 QualType TempFromTy = FromTy.getNonReferenceType();
9147 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9148 TempFromTy = PTy->getPointeeType();
9149 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009150 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009151 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9152 << (unsigned) FnKind << FnDesc
9153 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009154 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9155 << (unsigned) (Cand->Fix.Kind);
9156
Sebastian Redl08905022011-02-05 19:23:19 +00009157 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009158 return;
9159 }
9160
Douglas Gregor56f2e342010-06-30 23:01:39 +00009161 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009162 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009163 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9164 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9165 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9166 FromPtrTy->getPointeeType()) &&
9167 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9168 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009169 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009170 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009171 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009172 }
9173 } else if (const ObjCObjectPointerType *FromPtrTy
9174 = FromTy->getAs<ObjCObjectPointerType>()) {
9175 if (const ObjCObjectPointerType *ToPtrTy
9176 = ToTy->getAs<ObjCObjectPointerType>())
9177 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9178 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9179 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9180 FromPtrTy->getPointeeType()) &&
9181 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009182 BaseToDerivedConversion = 2;
9183 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009184 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9185 !FromTy->isIncompleteType() &&
9186 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009187 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009188 BaseToDerivedConversion = 3;
9189 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9190 ToTy.getNonReferenceType().getCanonicalType() ==
9191 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009192 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9193 << (unsigned) FnKind << FnDesc
9194 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9195 << (unsigned) isObjectArgument << I + 1;
9196 MaybeEmitInheritedConstructorNote(S, Fn);
9197 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009198 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009200
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009201 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009202 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009203 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009204 << (unsigned) FnKind << FnDesc
9205 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009206 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009207 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009208 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009209 return;
9210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009211
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009212 if (isa<ObjCObjectPointerType>(CFromTy) &&
9213 isa<PointerType>(CToTy)) {
9214 Qualifiers FromQs = CFromTy.getQualifiers();
9215 Qualifiers ToQs = CToTy.getQualifiers();
9216 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9217 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9218 << (unsigned) FnKind << FnDesc
9219 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9220 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9221 MaybeEmitInheritedConstructorNote(S, Fn);
9222 return;
9223 }
9224 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009225
9226 if (TakingCandidateAddress &&
9227 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9228 return;
9229
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009230 // Emit the generic diagnostic and, optionally, add the hints to it.
9231 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9232 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009233 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009234 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9235 << (unsigned) (Cand->Fix.Kind);
9236
9237 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009238 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9239 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009240 FDiag << *HI;
9241 S.Diag(Fn->getLocation(), FDiag);
9242
Sebastian Redl08905022011-02-05 19:23:19 +00009243 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009244}
9245
Larisse Voufo98b20f12013-07-19 23:00:19 +00009246/// Additional arity mismatch diagnosis specific to a function overload
9247/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9248/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009249static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9250 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009251 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009252 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009253
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009254 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009255 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009256 // right number of arguments, because only overloaded operators have
9257 // the weird behavior of overloading member and non-member functions.
9258 // Just don't report anything.
9259 if (Fn->isInvalidDecl() &&
9260 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009261 return true;
9262
9263 if (NumArgs < MinParams) {
9264 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9265 (Cand->FailureKind == ovl_fail_bad_deduction &&
9266 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9267 } else {
9268 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9269 (Cand->FailureKind == ovl_fail_bad_deduction &&
9270 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9271 }
9272
9273 return false;
9274}
9275
9276/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009277static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009278 assert(isa<FunctionDecl>(D) &&
9279 "The templated declaration should at least be a function"
9280 " when diagnosing bad template argument deduction due to too many"
9281 " or too few arguments");
9282
9283 FunctionDecl *Fn = cast<FunctionDecl>(D);
9284
9285 // TODO: treat calls to a missing default constructor as a special case
9286 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9287 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009288
John McCall6a61b522010-01-13 09:16:55 +00009289 // at least / at most / exactly
9290 unsigned mode, modeCount;
9291 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009292 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9293 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009294 mode = 0; // "at least"
9295 else
9296 mode = 2; // "exactly"
9297 modeCount = MinParams;
9298 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009299 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009300 mode = 1; // "at most"
9301 else
9302 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009303 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009304 }
9305
9306 std::string Description;
9307 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9308
Richard Smith10ff50d2012-05-11 05:16:41 +00009309 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9310 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009311 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9312 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009313 else
9314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009315 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9316 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009317 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009318}
9319
Larisse Voufo98b20f12013-07-19 23:00:19 +00009320/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009321static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9322 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009323 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9324 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9325}
Larisse Voufo47c08452013-07-19 22:53:23 +00009326
Richard Smith17c00b42014-11-12 01:24:00 +00009327static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009328 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9329 return FD->getDescribedFunctionTemplate();
9330 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9331 return RD->getDescribedClassTemplate();
9332
9333 llvm_unreachable("Unsupported: Getting the described template declaration"
9334 " for bad deduction diagnosis");
9335}
9336
9337/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009338static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9339 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009340 unsigned NumArgs,
9341 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009342 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009343 NamedDecl *ParamD;
9344 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9345 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9346 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009347 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009348 case Sema::TDK_Success:
9349 llvm_unreachable("TDK_success while diagnosing bad deduction");
9350
9351 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009352 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009353 S.Diag(Templated->getLocation(),
9354 diag::note_ovl_candidate_incomplete_deduction)
9355 << ParamD->getDeclName();
9356 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009357 return;
9358 }
9359
John McCall42d7d192010-08-05 09:05:08 +00009360 case Sema::TDK_Underqualified: {
9361 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9362 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9363
Larisse Voufo98b20f12013-07-19 23:00:19 +00009364 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009365
9366 // Param will have been canonicalized, but it should just be a
9367 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009368 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009369 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009370 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009371 assert(S.Context.hasSameType(Param, NonCanonParam));
9372
9373 // Arg has also been canonicalized, but there's nothing we can do
9374 // about that. It also doesn't matter as much, because it won't
9375 // have any template parameters in it (because deduction isn't
9376 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009377 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009378
Larisse Voufo98b20f12013-07-19 23:00:19 +00009379 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9380 << ParamD->getDeclName() << Arg << NonCanonParam;
9381 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009382 return;
9383 }
9384
9385 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009386 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009387 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009388 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009389 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009390 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009391 which = 1;
9392 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009393 which = 2;
9394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009395
Larisse Voufo98b20f12013-07-19 23:00:19 +00009396 S.Diag(Templated->getLocation(),
9397 diag::note_ovl_candidate_inconsistent_deduction)
9398 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9399 << *DeductionFailure.getSecondArg();
9400 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009401 return;
9402 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009403
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009404 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009405 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009406 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009407 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009408 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009409 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009410 else {
9411 int index = 0;
9412 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9413 index = TTP->getIndex();
9414 else if (NonTypeTemplateParmDecl *NTTP
9415 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9416 index = NTTP->getIndex();
9417 else
9418 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009419 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009420 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009421 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009422 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009423 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009424 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009425
Douglas Gregor02eb4832010-05-08 18:13:28 +00009426 case Sema::TDK_TooManyArguments:
9427 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009428 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009429 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009430
9431 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009432 S.Diag(Templated->getLocation(),
9433 diag::note_ovl_candidate_instantiation_depth);
9434 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009435 return;
9436
9437 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009438 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009439 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009440 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009441 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009442 TemplateArgString = " ";
9443 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009444 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009445 }
9446
Richard Smith6f8d2c62012-05-09 05:17:00 +00009447 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009448 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009449 if (PDiag && PDiag->second.getDiagID() ==
9450 diag::err_typename_nested_not_found_enable_if) {
9451 // FIXME: Use the source range of the condition, and the fully-qualified
9452 // name of the enable_if template. These are both present in PDiag.
9453 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9454 << "'enable_if'" << TemplateArgString;
9455 return;
9456 }
9457
Richard Smith9ca64612012-05-07 09:03:25 +00009458 // Format the SFINAE diagnostic into the argument string.
9459 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9460 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009461 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009462 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009463 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009464 SFINAEArgString = ": ";
9465 R = SourceRange(PDiag->first, PDiag->first);
9466 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9467 }
9468
Larisse Voufo98b20f12013-07-19 23:00:19 +00009469 S.Diag(Templated->getLocation(),
9470 diag::note_ovl_candidate_substitution_failure)
9471 << TemplateArgString << SFINAEArgString << R;
9472 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009473 return;
9474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009475
Richard Smith8c6eeb92013-01-31 04:03:12 +00009476 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009477 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9478 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009479 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009480 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009481 return;
9482 }
9483
Richard Smith9b534542015-12-31 02:02:54 +00009484 case Sema::TDK_DeducedMismatch: {
9485 // Format the template argument list into the argument string.
9486 SmallString<128> TemplateArgString;
9487 if (TemplateArgumentList *Args =
9488 DeductionFailure.getTemplateArgumentList()) {
9489 TemplateArgString = " ";
9490 TemplateArgString += S.getTemplateArgumentBindingsText(
9491 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9492 }
9493
9494 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9495 << (*DeductionFailure.getCallArgIndex() + 1)
9496 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9497 << TemplateArgString;
9498 break;
9499 }
9500
Richard Trieue3732352013-04-08 21:11:40 +00009501 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009502 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009503 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9504 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009505 if (FirstTA.getKind() == TemplateArgument::Template &&
9506 SecondTA.getKind() == TemplateArgument::Template) {
9507 TemplateName FirstTN = FirstTA.getAsTemplate();
9508 TemplateName SecondTN = SecondTA.getAsTemplate();
9509 if (FirstTN.getKind() == TemplateName::Template &&
9510 SecondTN.getKind() == TemplateName::Template) {
9511 if (FirstTN.getAsTemplateDecl()->getName() ==
9512 SecondTN.getAsTemplateDecl()->getName()) {
9513 // FIXME: This fixes a bad diagnostic where both templates are named
9514 // the same. This particular case is a bit difficult since:
9515 // 1) It is passed as a string to the diagnostic printer.
9516 // 2) The diagnostic printer only attempts to find a better
9517 // name for types, not decls.
9518 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009519 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009520 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9521 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9522 return;
9523 }
9524 }
9525 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009526
9527 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9528 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9529 return;
9530
Faisal Vali2b391ab2013-09-26 19:54:12 +00009531 // FIXME: For generic lambda parameters, check if the function is a lambda
9532 // call operator, and if so, emit a prettier and more informative
9533 // diagnostic that mentions 'auto' and lambda in addition to
9534 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009535 S.Diag(Templated->getLocation(),
9536 diag::note_ovl_candidate_non_deduced_mismatch)
9537 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009538 return;
Richard Trieue3732352013-04-08 21:11:40 +00009539 }
John McCall8b9ed552010-02-01 18:53:26 +00009540 // TODO: diagnose these individually, then kill off
9541 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009542 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009543 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9544 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009545 return;
9546 }
9547}
9548
Larisse Voufo98b20f12013-07-19 23:00:19 +00009549/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009550static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009551 unsigned NumArgs,
9552 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009553 unsigned TDK = Cand->DeductionFailure.Result;
9554 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9555 if (CheckArityMismatch(S, Cand, NumArgs))
9556 return;
9557 }
9558 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009559 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009560}
9561
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009562/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009563static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009564 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9565 FunctionDecl *Callee = Cand->Function;
9566
9567 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9568 CalleeTarget = S.IdentifyCUDATarget(Callee);
9569
9570 std::string FnDesc;
9571 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9572
9573 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009574 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9575
9576 // This could be an implicit constructor for which we could not infer the
9577 // target due to a collsion. Diagnose that case.
9578 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9579 if (Meth != nullptr && Meth->isImplicit()) {
9580 CXXRecordDecl *ParentClass = Meth->getParent();
9581 Sema::CXXSpecialMember CSM;
9582
9583 switch (FnKind) {
9584 default:
9585 return;
9586 case oc_implicit_default_constructor:
9587 CSM = Sema::CXXDefaultConstructor;
9588 break;
9589 case oc_implicit_copy_constructor:
9590 CSM = Sema::CXXCopyConstructor;
9591 break;
9592 case oc_implicit_move_constructor:
9593 CSM = Sema::CXXMoveConstructor;
9594 break;
9595 case oc_implicit_copy_assignment:
9596 CSM = Sema::CXXCopyAssignment;
9597 break;
9598 case oc_implicit_move_assignment:
9599 CSM = Sema::CXXMoveAssignment;
9600 break;
9601 };
9602
9603 bool ConstRHS = false;
9604 if (Meth->getNumParams()) {
9605 if (const ReferenceType *RT =
9606 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9607 ConstRHS = RT->getPointeeType().isConstQualified();
9608 }
9609 }
9610
9611 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9612 /* ConstRHS */ ConstRHS,
9613 /* Diagnose */ true);
9614 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009615}
9616
Richard Smith17c00b42014-11-12 01:24:00 +00009617static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009618 FunctionDecl *Callee = Cand->Function;
9619 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9620
9621 S.Diag(Callee->getLocation(),
9622 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9623 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9624}
9625
John McCall8b9ed552010-02-01 18:53:26 +00009626/// Generates a 'note' diagnostic for an overload candidate. We've
9627/// already generated a primary error at the call site.
9628///
9629/// It really does need to be a single diagnostic with its caret
9630/// pointed at the candidate declaration. Yes, this creates some
9631/// major challenges of technical writing. Yes, this makes pointing
9632/// out problems with specific arguments quite awkward. It's still
9633/// better than generating twenty screens of text for every failed
9634/// overload.
9635///
9636/// It would be great to be able to express per-candidate problems
9637/// more richly for those diagnostic clients that cared, but we'd
9638/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009639static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009640 unsigned NumArgs,
9641 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009642 FunctionDecl *Fn = Cand->Function;
9643
John McCall12f97bc2010-01-08 04:41:39 +00009644 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009645 if (Cand->Viable && (Fn->isDeleted() ||
9646 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009647 std::string FnDesc;
9648 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009649
9650 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009651 << FnKind << FnDesc
9652 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009653 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009654 return;
John McCall12f97bc2010-01-08 04:41:39 +00009655 }
9656
John McCalle1ac8d12010-01-13 00:25:19 +00009657 // We don't really have anything else to say about viable candidates.
9658 if (Cand->Viable) {
9659 S.NoteOverloadCandidate(Fn);
9660 return;
9661 }
John McCall0d1da222010-01-12 00:44:57 +00009662
John McCall6a61b522010-01-13 09:16:55 +00009663 switch (Cand->FailureKind) {
9664 case ovl_fail_too_many_arguments:
9665 case ovl_fail_too_few_arguments:
9666 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009667
John McCall6a61b522010-01-13 09:16:55 +00009668 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009669 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009670
John McCall578a1f82014-12-14 01:46:53 +00009671 case ovl_fail_illegal_constructor: {
9672 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9673 << (Fn->getPrimaryTemplate() ? 1 : 0);
9674 MaybeEmitInheritedConstructorNote(S, Fn);
9675 return;
9676 }
9677
John McCallfe796dd2010-01-23 05:17:32 +00009678 case ovl_fail_trivial_conversion:
9679 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009680 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009681 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009682
John McCall65eb8792010-02-25 01:37:24 +00009683 case ovl_fail_bad_conversion: {
9684 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009685 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009686 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009687 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009688
John McCall6a61b522010-01-13 09:16:55 +00009689 // FIXME: this currently happens when we're called from SemaInit
9690 // when user-conversion overload fails. Figure out how to handle
9691 // those conditions and diagnose them well.
9692 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009693 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009694
9695 case ovl_fail_bad_target:
9696 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009697
9698 case ovl_fail_enable_if:
9699 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009700
9701 case ovl_fail_addr_not_available: {
9702 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9703 (void)Available;
9704 assert(!Available);
9705 break;
9706 }
John McCall65eb8792010-02-25 01:37:24 +00009707 }
John McCalld3224162010-01-08 00:58:21 +00009708}
9709
Richard Smith17c00b42014-11-12 01:24:00 +00009710static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009711 // Desugar the type of the surrogate down to a function type,
9712 // retaining as many typedefs as possible while still showing
9713 // the function type (and, therefore, its parameter types).
9714 QualType FnType = Cand->Surrogate->getConversionType();
9715 bool isLValueReference = false;
9716 bool isRValueReference = false;
9717 bool isPointer = false;
9718 if (const LValueReferenceType *FnTypeRef =
9719 FnType->getAs<LValueReferenceType>()) {
9720 FnType = FnTypeRef->getPointeeType();
9721 isLValueReference = true;
9722 } else if (const RValueReferenceType *FnTypeRef =
9723 FnType->getAs<RValueReferenceType>()) {
9724 FnType = FnTypeRef->getPointeeType();
9725 isRValueReference = true;
9726 }
9727 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9728 FnType = FnTypePtr->getPointeeType();
9729 isPointer = true;
9730 }
9731 // Desugar down to a function type.
9732 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9733 // Reconstruct the pointer/reference as appropriate.
9734 if (isPointer) FnType = S.Context.getPointerType(FnType);
9735 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9736 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9737
9738 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9739 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009740 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009741}
9742
Richard Smith17c00b42014-11-12 01:24:00 +00009743static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9744 SourceLocation OpLoc,
9745 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009746 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009747 std::string TypeStr("operator");
9748 TypeStr += Opc;
9749 TypeStr += "(";
9750 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009751 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009752 TypeStr += ")";
9753 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9754 } else {
9755 TypeStr += ", ";
9756 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9757 TypeStr += ")";
9758 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9759 }
9760}
9761
Richard Smith17c00b42014-11-12 01:24:00 +00009762static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9763 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009764 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009765 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9766 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009767 if (ICS.isBad()) break; // all meaningless after first invalid
9768 if (!ICS.isAmbiguous()) continue;
9769
John McCall5c32be02010-08-24 20:38:10 +00009770 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009771 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009772 }
9773}
9774
Larisse Voufo98b20f12013-07-19 23:00:19 +00009775static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009776 if (Cand->Function)
9777 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009778 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009779 return Cand->Surrogate->getLocation();
9780 return SourceLocation();
9781}
9782
Larisse Voufo98b20f12013-07-19 23:00:19 +00009783static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009784 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009785 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009786 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009787
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009788 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009789 case Sema::TDK_Incomplete:
9790 return 1;
9791
9792 case Sema::TDK_Underqualified:
9793 case Sema::TDK_Inconsistent:
9794 return 2;
9795
9796 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009797 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009798 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009799 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009800 return 3;
9801
9802 case Sema::TDK_InstantiationDepth:
9803 case Sema::TDK_FailedOverloadResolution:
9804 return 4;
9805
9806 case Sema::TDK_InvalidExplicitArguments:
9807 return 5;
9808
9809 case Sema::TDK_TooManyArguments:
9810 case Sema::TDK_TooFewArguments:
9811 return 6;
9812 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009813 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009814}
9815
Richard Smith17c00b42014-11-12 01:24:00 +00009816namespace {
John McCallad2587a2010-01-12 00:48:53 +00009817struct CompareOverloadCandidatesForDisplay {
9818 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009819 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009820 size_t NumArgs;
9821
Richard Smith0f59cb32015-12-18 21:45:41 +00009822 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009823 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009824
9825 bool operator()(const OverloadCandidate *L,
9826 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009827 // Fast-path this check.
9828 if (L == R) return false;
9829
John McCall12f97bc2010-01-08 04:41:39 +00009830 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009831 if (L->Viable) {
9832 if (!R->Viable) return true;
9833
9834 // TODO: introduce a tri-valued comparison for overload
9835 // candidates. Would be more worthwhile if we had a sort
9836 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009837 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9838 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009839 } else if (R->Viable)
9840 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009841
John McCall3712d9e2010-01-15 23:32:50 +00009842 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009843
John McCall3712d9e2010-01-15 23:32:50 +00009844 // Criteria by which we can sort non-viable candidates:
9845 if (!L->Viable) {
9846 // 1. Arity mismatches come after other candidates.
9847 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009848 L->FailureKind == ovl_fail_too_few_arguments) {
9849 if (R->FailureKind == ovl_fail_too_many_arguments ||
9850 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009851 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9852 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9853 if (LDist == RDist) {
9854 if (L->FailureKind == R->FailureKind)
9855 // Sort non-surrogates before surrogates.
9856 return !L->IsSurrogate && R->IsSurrogate;
9857 // Sort candidates requiring fewer parameters than there were
9858 // arguments given after candidates requiring more parameters
9859 // than there were arguments given.
9860 return L->FailureKind == ovl_fail_too_many_arguments;
9861 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009862 return LDist < RDist;
9863 }
John McCall3712d9e2010-01-15 23:32:50 +00009864 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009865 }
John McCall3712d9e2010-01-15 23:32:50 +00009866 if (R->FailureKind == ovl_fail_too_many_arguments ||
9867 R->FailureKind == ovl_fail_too_few_arguments)
9868 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009869
John McCallfe796dd2010-01-23 05:17:32 +00009870 // 2. Bad conversions come first and are ordered by the number
9871 // of bad conversions and quality of good conversions.
9872 if (L->FailureKind == ovl_fail_bad_conversion) {
9873 if (R->FailureKind != ovl_fail_bad_conversion)
9874 return true;
9875
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009876 // The conversion that can be fixed with a smaller number of changes,
9877 // comes first.
9878 unsigned numLFixes = L->Fix.NumConversionsFixed;
9879 unsigned numRFixes = R->Fix.NumConversionsFixed;
9880 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9881 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009882 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009883 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009884 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009885
John McCallfe796dd2010-01-23 05:17:32 +00009886 // If there's any ordering between the defined conversions...
9887 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009888 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009889
9890 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009891 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009892 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009893 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009894 L->Conversions[I],
9895 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009896 case ImplicitConversionSequence::Better:
9897 leftBetter++;
9898 break;
9899
9900 case ImplicitConversionSequence::Worse:
9901 leftBetter--;
9902 break;
9903
9904 case ImplicitConversionSequence::Indistinguishable:
9905 break;
9906 }
9907 }
9908 if (leftBetter > 0) return true;
9909 if (leftBetter < 0) return false;
9910
9911 } else if (R->FailureKind == ovl_fail_bad_conversion)
9912 return false;
9913
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009914 if (L->FailureKind == ovl_fail_bad_deduction) {
9915 if (R->FailureKind != ovl_fail_bad_deduction)
9916 return true;
9917
9918 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9919 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009920 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009921 } else if (R->FailureKind == ovl_fail_bad_deduction)
9922 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009923
John McCall3712d9e2010-01-15 23:32:50 +00009924 // TODO: others?
9925 }
9926
9927 // Sort everything else by location.
9928 SourceLocation LLoc = GetLocationForCandidate(L);
9929 SourceLocation RLoc = GetLocationForCandidate(R);
9930
9931 // Put candidates without locations (e.g. builtins) at the end.
9932 if (LLoc.isInvalid()) return false;
9933 if (RLoc.isInvalid()) return true;
9934
9935 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009936 }
9937};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009938}
John McCall12f97bc2010-01-08 04:41:39 +00009939
John McCallfe796dd2010-01-23 05:17:32 +00009940/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009941/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009942static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9943 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009944 assert(!Cand->Viable);
9945
9946 // Don't do anything on failures other than bad conversion.
9947 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9948
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009949 // We only want the FixIts if all the arguments can be corrected.
9950 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009951 // Use a implicit copy initialization to check conversion fixes.
9952 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009953
John McCallfe796dd2010-01-23 05:17:32 +00009954 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009955 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009956 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009957 while (true) {
9958 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9959 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009960 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009961 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009962 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009963 }
John McCallfe796dd2010-01-23 05:17:32 +00009964 }
9965
9966 if (ConvIdx == ConvCount)
9967 return;
9968
John McCall65eb8792010-02-25 01:37:24 +00009969 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9970 "remaining conversion is initialized?");
9971
Douglas Gregoradc7a702010-04-16 17:45:54 +00009972 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009973 // operation somehow.
9974 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009975
9976 const FunctionProtoType* Proto;
9977 unsigned ArgIdx = ConvIdx;
9978
9979 if (Cand->IsSurrogate) {
9980 QualType ConvType
9981 = Cand->Surrogate->getConversionType().getNonReferenceType();
9982 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9983 ConvType = ConvPtrType->getPointeeType();
9984 Proto = ConvType->getAs<FunctionProtoType>();
9985 ArgIdx--;
9986 } else if (Cand->Function) {
9987 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9988 if (isa<CXXMethodDecl>(Cand->Function) &&
9989 !isa<CXXConstructorDecl>(Cand->Function))
9990 ArgIdx--;
9991 } else {
9992 // Builtin binary operator with a bad first conversion.
9993 assert(ConvCount <= 3);
9994 for (; ConvIdx != ConvCount; ++ConvIdx)
9995 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009996 = TryCopyInitialization(S, Args[ConvIdx],
9997 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009998 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009999 /*InOverloadResolution*/ true,
10000 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +000010001 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010002 return;
10003 }
10004
10005 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010006 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +000010007 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010008 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +000010009 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10010 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10011 /*InOverloadResolution=*/true,
10012 /*AllowObjCWritebackConversion=*/
10013 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010014 // Store the FixIt in the candidate if it exists.
10015 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010016 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010017 }
John McCallfe796dd2010-01-23 05:17:32 +000010018 else
10019 Cand->Conversions[ConvIdx].setEllipsis();
10020 }
10021}
10022
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010023/// PrintOverloadCandidates - When overload resolution fails, prints
10024/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010025/// set.
John McCall5c32be02010-08-24 20:38:10 +000010026void OverloadCandidateSet::NoteCandidates(Sema &S,
10027 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010028 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +000010029 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +000010030 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +000010031 // Sort the candidates by viability and position. Sorting directly would
10032 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010033 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010034 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10035 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +000010036 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010037 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010038 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010039 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010040 if (Cand->Function || Cand->IsSurrogate)
10041 Cands.push_back(Cand);
10042 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10043 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010044 }
10045 }
10046
John McCallad2587a2010-01-12 00:48:53 +000010047 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010048 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010049
John McCall0d1da222010-01-12 00:44:57 +000010050 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010051
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010052 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010053 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010054 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010055 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10056 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010057
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010058 // Set an arbitrary limit on the number of candidate functions we'll spam
10059 // the user with. FIXME: This limit should depend on details of the
10060 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010061 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010062 break;
10063 }
10064 ++CandsShown;
10065
John McCalld3224162010-01-08 00:58:21 +000010066 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010067 NoteFunctionCandidate(S, Cand, Args.size(),
10068 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010069 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010070 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010071 else {
10072 assert(Cand->Viable &&
10073 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010074 // Generally we only see ambiguities including viable builtin
10075 // operators if overload resolution got screwed up by an
10076 // ambiguous user-defined conversion.
10077 //
10078 // FIXME: It's quite possible for different conversions to see
10079 // different ambiguities, though.
10080 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010081 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010082 ReportedAmbiguousConversions = true;
10083 }
John McCalld3224162010-01-08 00:58:21 +000010084
John McCall0d1da222010-01-12 00:44:57 +000010085 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010086 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010087 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010088 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010089
10090 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010091 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010092}
10093
Larisse Voufo98b20f12013-07-19 23:00:19 +000010094static SourceLocation
10095GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10096 return Cand->Specialization ? Cand->Specialization->getLocation()
10097 : SourceLocation();
10098}
10099
Richard Smith17c00b42014-11-12 01:24:00 +000010100namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010101struct CompareTemplateSpecCandidatesForDisplay {
10102 Sema &S;
10103 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10104
10105 bool operator()(const TemplateSpecCandidate *L,
10106 const TemplateSpecCandidate *R) {
10107 // Fast-path this check.
10108 if (L == R)
10109 return false;
10110
10111 // Assuming that both candidates are not matches...
10112
10113 // Sort by the ranking of deduction failures.
10114 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10115 return RankDeductionFailure(L->DeductionFailure) <
10116 RankDeductionFailure(R->DeductionFailure);
10117
10118 // Sort everything else by location.
10119 SourceLocation LLoc = GetLocationForCandidate(L);
10120 SourceLocation RLoc = GetLocationForCandidate(R);
10121
10122 // Put candidates without locations (e.g. builtins) at the end.
10123 if (LLoc.isInvalid())
10124 return false;
10125 if (RLoc.isInvalid())
10126 return true;
10127
10128 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10129 }
10130};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010131}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010132
10133/// Diagnose a template argument deduction failure.
10134/// We are treating these failures as overload failures due to bad
10135/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010136void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10137 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010138 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010139 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010140}
10141
10142void TemplateSpecCandidateSet::destroyCandidates() {
10143 for (iterator i = begin(), e = end(); i != e; ++i) {
10144 i->DeductionFailure.Destroy();
10145 }
10146}
10147
10148void TemplateSpecCandidateSet::clear() {
10149 destroyCandidates();
10150 Candidates.clear();
10151}
10152
10153/// NoteCandidates - When no template specialization match is found, prints
10154/// diagnostic messages containing the non-matching specializations that form
10155/// the candidate set.
10156/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10157/// OCD == OCD_AllCandidates and Cand->Viable == false.
10158void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10159 // Sort the candidates by position (assuming no candidate is a match).
10160 // Sorting directly would be prohibitive, so we make a set of pointers
10161 // and sort those.
10162 SmallVector<TemplateSpecCandidate *, 32> Cands;
10163 Cands.reserve(size());
10164 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10165 if (Cand->Specialization)
10166 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010167 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010168 // in general, want to list every possible builtin candidate.
10169 }
10170
10171 std::sort(Cands.begin(), Cands.end(),
10172 CompareTemplateSpecCandidatesForDisplay(S));
10173
10174 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10175 // for generalization purposes (?).
10176 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10177
10178 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10179 unsigned CandsShown = 0;
10180 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10181 TemplateSpecCandidate *Cand = *I;
10182
10183 // Set an arbitrary limit on the number of candidates we'll spam
10184 // the user with. FIXME: This limit should depend on details of the
10185 // candidate list.
10186 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10187 break;
10188 ++CandsShown;
10189
10190 assert(Cand->Specialization &&
10191 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010192 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010193 }
10194
10195 if (I != E)
10196 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10197}
10198
Douglas Gregorb491ed32011-02-19 21:32:49 +000010199// [PossiblyAFunctionType] --> [Return]
10200// NonFunctionType --> NonFunctionType
10201// R (A) --> R(A)
10202// R (*)(A) --> R (A)
10203// R (&)(A) --> R (A)
10204// R (S::*)(A) --> R (A)
10205QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10206 QualType Ret = PossiblyAFunctionType;
10207 if (const PointerType *ToTypePtr =
10208 PossiblyAFunctionType->getAs<PointerType>())
10209 Ret = ToTypePtr->getPointeeType();
10210 else if (const ReferenceType *ToTypeRef =
10211 PossiblyAFunctionType->getAs<ReferenceType>())
10212 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010213 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010214 PossiblyAFunctionType->getAs<MemberPointerType>())
10215 Ret = MemTypePtr->getPointeeType();
10216 Ret =
10217 Context.getCanonicalType(Ret).getUnqualifiedType();
10218 return Ret;
10219}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010220
Richard Smith17c00b42014-11-12 01:24:00 +000010221namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010222// A helper class to help with address of function resolution
10223// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010224class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010225 Sema& S;
10226 Expr* SourceExpr;
10227 const QualType& TargetType;
10228 QualType TargetFunctionType; // Extracted function type from target type
10229
10230 bool Complain;
10231 //DeclAccessPair& ResultFunctionAccessPair;
10232 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010233
Douglas Gregorb491ed32011-02-19 21:32:49 +000010234 bool TargetTypeIsNonStaticMemberFunction;
10235 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010236 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010237 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010238
Douglas Gregorb491ed32011-02-19 21:32:49 +000010239 OverloadExpr::FindResult OvlExprInfo;
10240 OverloadExpr *OvlExpr;
10241 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010242 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010243 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010244
Douglas Gregorb491ed32011-02-19 21:32:49 +000010245public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010246 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10247 const QualType &TargetType, bool Complain)
10248 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10249 Complain(Complain), Context(S.getASTContext()),
10250 TargetTypeIsNonStaticMemberFunction(
10251 !!TargetType->getAs<MemberPointerType>()),
10252 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010253 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010254 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010255 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10256 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010257 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010258 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010259
David Majnemera4f7c7a2013-08-01 06:13:59 +000010260 if (TargetFunctionType->isFunctionType()) {
10261 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10262 if (!UME->isImplicitAccess() &&
10263 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10264 StaticMemberFunctionFromBoundPointer = true;
10265 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10266 DeclAccessPair dap;
10267 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10268 OvlExpr, false, &dap)) {
10269 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10270 if (!Method->isStatic()) {
10271 // If the target type is a non-function type and the function found
10272 // is a non-static member function, pretend as if that was the
10273 // target, it's the only possible type to end up with.
10274 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010275
David Majnemera4f7c7a2013-08-01 06:13:59 +000010276 // And skip adding the function if its not in the proper form.
10277 // We'll diagnose this due to an empty set of functions.
10278 if (!OvlExprInfo.HasFormOfMemberPointer)
10279 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010280 }
10281
David Majnemera4f7c7a2013-08-01 06:13:59 +000010282 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010283 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010284 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010285 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010286
10287 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010288 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010289
Douglas Gregorb491ed32011-02-19 21:32:49 +000010290 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10291 // C++ [over.over]p4:
10292 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010293 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010294 if (FoundNonTemplateFunction)
10295 EliminateAllTemplateMatches();
10296 else
10297 EliminateAllExceptMostSpecializedTemplate();
10298 }
10299 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010300
Justin Lebar25c4a812016-03-29 16:24:16 +000010301 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010302 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010303 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010304
10305 bool hasComplained() const { return HasComplained; }
10306
Douglas Gregorb491ed32011-02-19 21:32:49 +000010307private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010308 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10309 QualType Discard;
10310 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10311 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010312 }
10313
George Burgess IV6da4c202016-03-23 02:33:58 +000010314 /// \return true if A is considered a better overload candidate for the
10315 /// desired type than B.
10316 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10317 // If A doesn't have exactly the correct type, we don't want to classify it
10318 // as "better" than anything else. This way, the user is required to
10319 // disambiguate for us if there are multiple candidates and no exact match.
10320 return candidateHasExactlyCorrectType(A) &&
10321 (!candidateHasExactlyCorrectType(B) ||
10322 hasBetterEnableIfAttrs(S, A, B));
10323 }
10324
10325 /// \return true if we were able to eliminate all but one overload candidate,
10326 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010327 bool eliminiateSuboptimalOverloadCandidates() {
10328 // Same algorithm as overload resolution -- one pass to pick the "best",
10329 // another pass to be sure that nothing is better than the best.
10330 auto Best = Matches.begin();
10331 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10332 if (isBetterCandidate(I->second, Best->second))
10333 Best = I;
10334
10335 const FunctionDecl *BestFn = Best->second;
10336 auto IsBestOrInferiorToBest = [this, BestFn](
10337 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10338 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10339 };
10340
10341 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10342 // option, so we can potentially give the user a better error
10343 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10344 return false;
10345 Matches[0] = *Best;
10346 Matches.resize(1);
10347 return true;
10348 }
10349
Douglas Gregorb491ed32011-02-19 21:32:49 +000010350 bool isTargetTypeAFunction() const {
10351 return TargetFunctionType->isFunctionType();
10352 }
10353
10354 // [ToType] [Return]
10355
10356 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10357 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10358 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10359 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10360 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10361 }
10362
10363 // return true if any matching specializations were found
10364 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10365 const DeclAccessPair& CurAccessFunPair) {
10366 if (CXXMethodDecl *Method
10367 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10368 // Skip non-static function templates when converting to pointer, and
10369 // static when converting to member pointer.
10370 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10371 return false;
10372 }
10373 else if (TargetTypeIsNonStaticMemberFunction)
10374 return false;
10375
10376 // C++ [over.over]p2:
10377 // If the name is a function template, template argument deduction is
10378 // done (14.8.2.2), and if the argument deduction succeeds, the
10379 // resulting template argument list is used to generate a single
10380 // function template specialization, which is added to the set of
10381 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010382 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010383 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010384 if (Sema::TemplateDeductionResult Result
10385 = S.DeduceTemplateArguments(FunctionTemplate,
10386 &OvlExplicitTemplateArgs,
10387 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010388 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010389 // Make a note of the failed deduction for diagnostics.
10390 FailedCandidates.addCandidate()
10391 .set(FunctionTemplate->getTemplatedDecl(),
10392 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010393 return false;
10394 }
10395
Douglas Gregor19a41f12013-04-17 08:45:07 +000010396 // Template argument deduction ensures that we have an exact match or
10397 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010398 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010399 assert(S.isSameOrCompatibleFunctionType(
10400 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010401 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010402
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010403 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010404 return false;
10405
Douglas Gregorb491ed32011-02-19 21:32:49 +000010406 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10407 return true;
10408 }
10409
10410 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10411 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010412 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010413 // Skip non-static functions when converting to pointer, and static
10414 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010415 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10416 return false;
10417 }
10418 else if (TargetTypeIsNonStaticMemberFunction)
10419 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010420
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010421 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010422 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010423 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010424 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010425 return false;
10426
Richard Smith2a7d4812013-05-04 07:00:32 +000010427 // If any candidate has a placeholder return type, trigger its deduction
10428 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010429 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010430 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010431 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10432 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010433 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010434 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010435
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010436 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010437 return false;
10438
George Burgess IV6da4c202016-03-23 02:33:58 +000010439 // If we're in C, we need to support types that aren't exactly identical.
10440 if (!S.getLangOpts().CPlusPlus ||
10441 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010442 Matches.push_back(std::make_pair(
10443 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010444 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010445 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010446 }
Mike Stump11289f42009-09-09 15:08:12 +000010447 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010448
10449 return false;
10450 }
10451
10452 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10453 bool Ret = false;
10454
10455 // If the overload expression doesn't have the form of a pointer to
10456 // member, don't try to convert it to a pointer-to-member type.
10457 if (IsInvalidFormOfPointerToMemberFunction())
10458 return false;
10459
10460 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10461 E = OvlExpr->decls_end();
10462 I != E; ++I) {
10463 // Look through any using declarations to find the underlying function.
10464 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10465
10466 // C++ [over.over]p3:
10467 // Non-member functions and static member functions match
10468 // targets of type "pointer-to-function" or "reference-to-function."
10469 // Nonstatic member functions match targets of
10470 // type "pointer-to-member-function."
10471 // Note that according to DR 247, the containing class does not matter.
10472 if (FunctionTemplateDecl *FunctionTemplate
10473 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10474 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10475 Ret = true;
10476 }
10477 // If we have explicit template arguments supplied, skip non-templates.
10478 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10479 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10480 Ret = true;
10481 }
10482 assert(Ret || Matches.empty());
10483 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010484 }
10485
Douglas Gregorb491ed32011-02-19 21:32:49 +000010486 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010487 // [...] and any given function template specialization F1 is
10488 // eliminated if the set contains a second function template
10489 // specialization whose function template is more specialized
10490 // than the function template of F1 according to the partial
10491 // ordering rules of 14.5.5.2.
10492
10493 // The algorithm specified above is quadratic. We instead use a
10494 // two-pass algorithm (similar to the one used to identify the
10495 // best viable function in an overload set) that identifies the
10496 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010497
10498 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10499 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10500 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010501
Larisse Voufo98b20f12013-07-19 23:00:19 +000010502 // TODO: It looks like FailedCandidates does not serve much purpose
10503 // here, since the no_viable diagnostic has index 0.
10504 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010505 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010506 SourceExpr->getLocStart(), S.PDiag(),
10507 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10508 .second->getDeclName(),
10509 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10510 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010511
Douglas Gregorb491ed32011-02-19 21:32:49 +000010512 if (Result != MatchesCopy.end()) {
10513 // Make it the first and only element
10514 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10515 Matches[0].second = cast<FunctionDecl>(*Result);
10516 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010517 } else
10518 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010520
Douglas Gregorb491ed32011-02-19 21:32:49 +000010521 void EliminateAllTemplateMatches() {
10522 // [...] any function template specializations in the set are
10523 // eliminated if the set also contains a non-template function, [...]
10524 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010525 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010526 ++I;
10527 else {
10528 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010529 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010530 }
10531 }
10532 }
10533
Artem Belevich94a55e82015-09-22 17:22:59 +000010534 void EliminateSuboptimalCudaMatches() {
10535 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10536 }
10537
Douglas Gregorb491ed32011-02-19 21:32:49 +000010538public:
10539 void ComplainNoMatchesFound() const {
10540 assert(Matches.empty());
10541 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10542 << OvlExpr->getName() << TargetFunctionType
10543 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010544 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010545 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10546 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010547 else {
10548 // We have some deduction failure messages. Use them to diagnose
10549 // the function templates, and diagnose the non-template candidates
10550 // normally.
10551 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10552 IEnd = OvlExpr->decls_end();
10553 I != IEnd; ++I)
10554 if (FunctionDecl *Fun =
10555 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010556 if (!functionHasPassObjectSizeParams(Fun))
10557 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10558 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010559 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10560 }
10561 }
10562
Douglas Gregorb491ed32011-02-19 21:32:49 +000010563 bool IsInvalidFormOfPointerToMemberFunction() const {
10564 return TargetTypeIsNonStaticMemberFunction &&
10565 !OvlExprInfo.HasFormOfMemberPointer;
10566 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010567
Douglas Gregorb491ed32011-02-19 21:32:49 +000010568 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10569 // TODO: Should we condition this on whether any functions might
10570 // have matched, or is it more appropriate to do that in callers?
10571 // TODO: a fixit wouldn't hurt.
10572 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10573 << TargetType << OvlExpr->getSourceRange();
10574 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010575
10576 bool IsStaticMemberFunctionFromBoundPointer() const {
10577 return StaticMemberFunctionFromBoundPointer;
10578 }
10579
10580 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10581 S.Diag(OvlExpr->getLocStart(),
10582 diag::err_invalid_form_pointer_member_function)
10583 << OvlExpr->getSourceRange();
10584 }
10585
Douglas Gregorb491ed32011-02-19 21:32:49 +000010586 void ComplainOfInvalidConversion() const {
10587 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10588 << OvlExpr->getName() << TargetType;
10589 }
10590
10591 void ComplainMultipleMatchesFound() const {
10592 assert(Matches.size() > 1);
10593 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10594 << OvlExpr->getName()
10595 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010596 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10597 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010598 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010599
10600 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10601
Douglas Gregorb491ed32011-02-19 21:32:49 +000010602 int getNumMatches() const { return Matches.size(); }
10603
10604 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010605 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010606 return Matches[0].second;
10607 }
10608
10609 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010610 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010611 return &Matches[0].first;
10612 }
10613};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010614}
Richard Smith17c00b42014-11-12 01:24:00 +000010615
Douglas Gregorb491ed32011-02-19 21:32:49 +000010616/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10617/// an overloaded function (C++ [over.over]), where @p From is an
10618/// expression with overloaded function type and @p ToType is the type
10619/// we're trying to resolve to. For example:
10620///
10621/// @code
10622/// int f(double);
10623/// int f(int);
10624///
10625/// int (*pfd)(double) = f; // selects f(double)
10626/// @endcode
10627///
10628/// This routine returns the resulting FunctionDecl if it could be
10629/// resolved, and NULL otherwise. When @p Complain is true, this
10630/// routine will emit diagnostics if there is an error.
10631FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010632Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10633 QualType TargetType,
10634 bool Complain,
10635 DeclAccessPair &FoundResult,
10636 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010637 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010638
10639 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10640 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010641 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010642 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010643 bool ShouldComplain = Complain && !Resolver.hasComplained();
10644 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010645 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10646 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10647 else
10648 Resolver.ComplainNoMatchesFound();
10649 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010650 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010651 Resolver.ComplainMultipleMatchesFound();
10652 else if (NumMatches == 1) {
10653 Fn = Resolver.getMatchingFunctionDecl();
10654 assert(Fn);
10655 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010656 if (Complain) {
10657 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10658 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10659 else
10660 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10661 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010662 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010663
10664 if (pHadMultipleCandidates)
10665 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010666 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010667}
10668
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010669/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010670/// resolve that function to a single function that can have its address taken.
10671/// This will modify `Pair` iff it returns non-null.
10672///
10673/// This routine can only realistically succeed if all but one candidates in the
10674/// overload set for SrcExpr cannot have their addresses taken.
10675FunctionDecl *
10676Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10677 DeclAccessPair &Pair) {
10678 OverloadExpr::FindResult R = OverloadExpr::find(E);
10679 OverloadExpr *Ovl = R.Expression;
10680 FunctionDecl *Result = nullptr;
10681 DeclAccessPair DAP;
10682 // Don't use the AddressOfResolver because we're specifically looking for
10683 // cases where we have one overload candidate that lacks
10684 // enable_if/pass_object_size/...
10685 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10686 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10687 if (!FD)
10688 return nullptr;
10689
10690 if (!checkAddressOfFunctionIsAvailable(FD))
10691 continue;
10692
10693 // We have more than one result; quit.
10694 if (Result)
10695 return nullptr;
10696 DAP = I.getPair();
10697 Result = FD;
10698 }
10699
10700 if (Result)
10701 Pair = DAP;
10702 return Result;
10703}
10704
10705/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010706/// resolve that overloaded function expression down to a single function.
10707///
10708/// This routine can only resolve template-ids that refer to a single function
10709/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010710/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010711/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010712///
10713/// If no template-ids are found, no diagnostics are emitted and NULL is
10714/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010715FunctionDecl *
10716Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10717 bool Complain,
10718 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010719 // C++ [over.over]p1:
10720 // [...] [Note: any redundant set of parentheses surrounding the
10721 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010722 // C++ [over.over]p1:
10723 // [...] The overloaded function name can be preceded by the &
10724 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010725
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010726 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010727 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010728 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010729
10730 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010731 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010732 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010733
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010734 // Look through all of the overloaded functions, searching for one
10735 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010736 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010737 for (UnresolvedSetIterator I = ovl->decls_begin(),
10738 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010739 // C++0x [temp.arg.explicit]p3:
10740 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010741 // where deduction is not done, if a template argument list is
10742 // specified and it, along with any default template arguments,
10743 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010744 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010745 FunctionTemplateDecl *FunctionTemplate
10746 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010747
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010748 // C++ [over.over]p2:
10749 // If the name is a function template, template argument deduction is
10750 // done (14.8.2.2), and if the argument deduction succeeds, the
10751 // resulting template argument list is used to generate a single
10752 // function template specialization, which is added to the set of
10753 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010754 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010755 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010756 if (TemplateDeductionResult Result
10757 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010758 Specialization, Info,
10759 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010760 // Make a note of the failed deduction for diagnostics.
10761 // TODO: Actually use the failed-deduction info?
10762 FailedCandidates.addCandidate()
10763 .set(FunctionTemplate->getTemplatedDecl(),
10764 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010765 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010766 }
10767
John McCall0009fcc2011-04-26 20:42:42 +000010768 assert(Specialization && "no specialization and no error?");
10769
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010770 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010771 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010772 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010773 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10774 << ovl->getName();
10775 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010776 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010777 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010778 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010779
John McCall0009fcc2011-04-26 20:42:42 +000010780 Matched = Specialization;
10781 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010782 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010783
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010784 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010785 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010786 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010787 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010788
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010789 return Matched;
10790}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010791
Douglas Gregor1beec452011-03-12 01:48:56 +000010792
10793
10794
John McCall50a2c2c2011-10-11 23:14:30 +000010795// Resolve and fix an overloaded expression that can be resolved
10796// because it identifies a single function template specialization.
10797//
Douglas Gregor1beec452011-03-12 01:48:56 +000010798// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010799//
10800// Return true if it was logically possible to so resolve the
10801// expression, regardless of whether or not it succeeded. Always
10802// returns true if 'complain' is set.
10803bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10804 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010805 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010806 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010807 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010808 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010809
John McCall50a2c2c2011-10-11 23:14:30 +000010810 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010811
John McCall0009fcc2011-04-26 20:42:42 +000010812 DeclAccessPair found;
10813 ExprResult SingleFunctionExpression;
10814 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10815 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010816 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010817 SrcExpr = ExprError();
10818 return true;
10819 }
John McCall0009fcc2011-04-26 20:42:42 +000010820
10821 // It is only correct to resolve to an instance method if we're
10822 // resolving a form that's permitted to be a pointer to member.
10823 // Otherwise we'll end up making a bound member expression, which
10824 // is illegal in all the contexts we resolve like this.
10825 if (!ovl.HasFormOfMemberPointer &&
10826 isa<CXXMethodDecl>(fn) &&
10827 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010828 if (!complain) return false;
10829
10830 Diag(ovl.Expression->getExprLoc(),
10831 diag::err_bound_member_function)
10832 << 0 << ovl.Expression->getSourceRange();
10833
10834 // TODO: I believe we only end up here if there's a mix of
10835 // static and non-static candidates (otherwise the expression
10836 // would have 'bound member' type, not 'overload' type).
10837 // Ideally we would note which candidate was chosen and why
10838 // the static candidates were rejected.
10839 SrcExpr = ExprError();
10840 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010841 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010842
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010843 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010844 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010845 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010846
10847 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010848 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010849 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010850 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010851 if (SingleFunctionExpression.isInvalid()) {
10852 SrcExpr = ExprError();
10853 return true;
10854 }
10855 }
John McCall0009fcc2011-04-26 20:42:42 +000010856 }
10857
10858 if (!SingleFunctionExpression.isUsable()) {
10859 if (complain) {
10860 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10861 << ovl.Expression->getName()
10862 << DestTypeForComplaining
10863 << OpRangeForComplaining
10864 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010865 NoteAllOverloadCandidates(SrcExpr.get());
10866
10867 SrcExpr = ExprError();
10868 return true;
10869 }
10870
10871 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010872 }
10873
John McCall50a2c2c2011-10-11 23:14:30 +000010874 SrcExpr = SingleFunctionExpression;
10875 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010876}
10877
Douglas Gregorcabea402009-09-22 15:41:20 +000010878/// \brief Add a single candidate to the overload set.
10879static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010880 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010881 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010882 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010883 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010884 bool PartialOverloading,
10885 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010886 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010887 if (isa<UsingShadowDecl>(Callee))
10888 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10889
Douglas Gregorcabea402009-09-22 15:41:20 +000010890 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010891 if (ExplicitTemplateArgs) {
10892 assert(!KnownValid && "Explicit template arguments?");
10893 return;
10894 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010895 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10896 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010897 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010898 return;
John McCalld14a8642009-11-21 08:51:07 +000010899 }
10900
10901 if (FunctionTemplateDecl *FuncTemplate
10902 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010903 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010904 ExplicitTemplateArgs, Args, CandidateSet,
10905 /*SuppressUsedConversions=*/false,
10906 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010907 return;
10908 }
10909
Richard Smith95ce4f62011-06-26 22:19:54 +000010910 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010911}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010912
Douglas Gregorcabea402009-09-22 15:41:20 +000010913/// \brief Add the overload candidates named by callee and/or found by argument
10914/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010915void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010916 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010917 OverloadCandidateSet &CandidateSet,
10918 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010919
10920#ifndef NDEBUG
10921 // Verify that ArgumentDependentLookup is consistent with the rules
10922 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010923 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010924 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10925 // and let Y be the lookup set produced by argument dependent
10926 // lookup (defined as follows). If X contains
10927 //
10928 // -- a declaration of a class member, or
10929 //
10930 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010931 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010932 //
10933 // -- a declaration that is neither a function or a function
10934 // template
10935 //
10936 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010937
John McCall57500772009-12-16 12:17:52 +000010938 if (ULE->requiresADL()) {
10939 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10940 E = ULE->decls_end(); I != E; ++I) {
10941 assert(!(*I)->getDeclContext()->isRecord());
10942 assert(isa<UsingShadowDecl>(*I) ||
10943 !(*I)->getDeclContext()->isFunctionOrMethod());
10944 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010945 }
10946 }
10947#endif
10948
John McCall57500772009-12-16 12:17:52 +000010949 // It would be nice to avoid this copy.
10950 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010951 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010952 if (ULE->hasExplicitTemplateArgs()) {
10953 ULE->copyTemplateArgumentsInto(TABuffer);
10954 ExplicitTemplateArgs = &TABuffer;
10955 }
10956
10957 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10958 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010959 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10960 CandidateSet, PartialOverloading,
10961 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010962
John McCall57500772009-12-16 12:17:52 +000010963 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010964 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010965 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010966 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010967}
John McCalld681c392009-12-16 08:11:27 +000010968
Richard Smith0603bbb2013-06-12 22:56:54 +000010969/// Determine whether a declaration with the specified name could be moved into
10970/// a different namespace.
10971static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10972 switch (Name.getCXXOverloadedOperator()) {
10973 case OO_New: case OO_Array_New:
10974 case OO_Delete: case OO_Array_Delete:
10975 return false;
10976
10977 default:
10978 return true;
10979 }
10980}
10981
Richard Smith998a5912011-06-05 22:42:48 +000010982/// Attempt to recover from an ill-formed use of a non-dependent name in a
10983/// template, where the non-dependent name was declared after the template
10984/// was defined. This is common in code written for a compilers which do not
10985/// correctly implement two-stage name lookup.
10986///
10987/// Returns true if a viable candidate was found and a diagnostic was issued.
10988static bool
10989DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10990 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010991 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010992 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010993 ArrayRef<Expr *> Args,
10994 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010995 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10996 return false;
10997
10998 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010999 if (DC->isTransparentContext())
11000 continue;
11001
Richard Smith998a5912011-06-05 22:42:48 +000011002 SemaRef.LookupQualifiedName(R, DC);
11003
11004 if (!R.empty()) {
11005 R.suppressDiagnostics();
11006
11007 if (isa<CXXRecordDecl>(DC)) {
11008 // Don't diagnose names we find in classes; we get much better
11009 // diagnostics for these from DiagnoseEmptyLookup.
11010 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011011 if (DoDiagnoseEmptyLookup)
11012 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011013 return false;
11014 }
11015
Richard Smith100b24a2014-04-17 01:52:14 +000011016 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011017 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11018 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011019 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011020 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011021
11022 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011023 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011024 // No viable functions. Don't bother the user with notes for functions
11025 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011026 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011027 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011028 }
Richard Smith998a5912011-06-05 22:42:48 +000011029
11030 // Find the namespaces where ADL would have looked, and suggest
11031 // declaring the function there instead.
11032 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11033 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011034 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011035 AssociatedNamespaces,
11036 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011037 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011038 if (canBeDeclaredInNamespace(R.getLookupName())) {
11039 DeclContext *Std = SemaRef.getStdNamespace();
11040 for (Sema::AssociatedNamespaceSet::iterator
11041 it = AssociatedNamespaces.begin(),
11042 end = AssociatedNamespaces.end(); it != end; ++it) {
11043 // Never suggest declaring a function within namespace 'std'.
11044 if (Std && Std->Encloses(*it))
11045 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011046
Richard Smith0603bbb2013-06-12 22:56:54 +000011047 // Never suggest declaring a function within a namespace with a
11048 // reserved name, like __gnu_cxx.
11049 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11050 if (NS &&
11051 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11052 continue;
11053
11054 SuggestedNamespaces.insert(*it);
11055 }
Richard Smith998a5912011-06-05 22:42:48 +000011056 }
11057
11058 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11059 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011060 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011061 SemaRef.Diag(Best->Function->getLocation(),
11062 diag::note_not_found_by_two_phase_lookup)
11063 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011064 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011065 SemaRef.Diag(Best->Function->getLocation(),
11066 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011067 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011068 } else {
11069 // FIXME: It would be useful to list the associated namespaces here,
11070 // but the diagnostics infrastructure doesn't provide a way to produce
11071 // a localized representation of a list of items.
11072 SemaRef.Diag(Best->Function->getLocation(),
11073 diag::note_not_found_by_two_phase_lookup)
11074 << R.getLookupName() << 2;
11075 }
11076
11077 // Try to recover by calling this function.
11078 return true;
11079 }
11080
11081 R.clear();
11082 }
11083
11084 return false;
11085}
11086
11087/// Attempt to recover from ill-formed use of a non-dependent operator in a
11088/// template, where the non-dependent operator was declared after the template
11089/// was defined.
11090///
11091/// Returns true if a viable candidate was found and a diagnostic was issued.
11092static bool
11093DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11094 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011095 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011096 DeclarationName OpName =
11097 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11098 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11099 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011100 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011101 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011102}
11103
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011104namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011105class BuildRecoveryCallExprRAII {
11106 Sema &SemaRef;
11107public:
11108 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11109 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11110 SemaRef.IsBuildingRecoveryCallExpr = true;
11111 }
11112
11113 ~BuildRecoveryCallExprRAII() {
11114 SemaRef.IsBuildingRecoveryCallExpr = false;
11115 }
11116};
11117
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011118}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011119
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011120static std::unique_ptr<CorrectionCandidateCallback>
11121MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11122 bool HasTemplateArgs, bool AllowTypoCorrection) {
11123 if (!AllowTypoCorrection)
11124 return llvm::make_unique<NoTypoCorrectionCCC>();
11125 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11126 HasTemplateArgs, ME);
11127}
11128
John McCalld681c392009-12-16 08:11:27 +000011129/// Attempts to recover from a call where no functions were found.
11130///
11131/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011132static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011133BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011134 UnresolvedLookupExpr *ULE,
11135 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011136 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011137 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011138 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011139 // Do not try to recover if it is already building a recovery call.
11140 // This stops infinite loops for template instantiations like
11141 //
11142 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11143 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11144 //
11145 if (SemaRef.IsBuildingRecoveryCallExpr)
11146 return ExprError();
11147 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011148
11149 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011150 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011151 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011152
John McCall57500772009-12-16 12:17:52 +000011153 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011154 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011155 if (ULE->hasExplicitTemplateArgs()) {
11156 ULE->copyTemplateArgumentsInto(TABuffer);
11157 ExplicitTemplateArgs = &TABuffer;
11158 }
11159
John McCalld681c392009-12-16 08:11:27 +000011160 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11161 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011162 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011163 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011164 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011165 ExplicitTemplateArgs, Args,
11166 &DoDiagnoseEmptyLookup) &&
11167 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11168 S, SS, R,
11169 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11170 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11171 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011172 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011173
John McCall57500772009-12-16 12:17:52 +000011174 assert(!R.empty() && "lookup results empty despite recovery");
11175
11176 // Build an implicit member call if appropriate. Just drop the
11177 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011178 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011179 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011180 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11181 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011182 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011183 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011184 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011185 else
11186 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11187
11188 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011189 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011190
11191 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011192 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011193 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011194 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011195 MultiExprArg(Args.data(), Args.size()),
11196 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011197}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011198
Sam Panzer0f384432012-08-21 00:52:01 +000011199/// \brief Constructs and populates an OverloadedCandidateSet from
11200/// the given function.
11201/// \returns true when an the ExprResult output parameter has been set.
11202bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11203 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011204 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011205 SourceLocation RParenLoc,
11206 OverloadCandidateSet *CandidateSet,
11207 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011208#ifndef NDEBUG
11209 if (ULE->requiresADL()) {
11210 // To do ADL, we must have found an unqualified name.
11211 assert(!ULE->getQualifier() && "qualified name with ADL");
11212
11213 // We don't perform ADL for implicit declarations of builtins.
11214 // Verify that this was correctly set up.
11215 FunctionDecl *F;
11216 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11217 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11218 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011219 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011220
John McCall57500772009-12-16 12:17:52 +000011221 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011222 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011223 }
John McCall57500772009-12-16 12:17:52 +000011224#endif
11225
John McCall4124c492011-10-17 18:40:02 +000011226 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011227 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011228 *Result = ExprError();
11229 return true;
11230 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011231
John McCall57500772009-12-16 12:17:52 +000011232 // Add the functions denoted by the callee to the set of candidate
11233 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011234 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011235
Hans Wennborgb2747382015-06-12 21:23:23 +000011236 if (getLangOpts().MSVCCompat &&
11237 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011238 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11239
11240 OverloadCandidateSet::iterator Best;
11241 if (CandidateSet->empty() ||
11242 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11243 OR_No_Viable_Function) {
11244 // In Microsoft mode, if we are inside a template class member function then
11245 // create a type dependent CallExpr. The goal is to postpone name lookup
11246 // to instantiation time to be able to search into type dependent base
11247 // classes.
11248 CallExpr *CE = new (Context) CallExpr(
11249 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011250 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011251 CE->setValueDependent(true);
11252 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011253 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011254 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011255 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011256 }
John McCalld681c392009-12-16 08:11:27 +000011257
Hans Wennborg64937c62015-06-11 21:21:57 +000011258 if (CandidateSet->empty())
11259 return false;
11260
John McCall4124c492011-10-17 18:40:02 +000011261 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011262 return false;
11263}
John McCall4124c492011-10-17 18:40:02 +000011264
Sam Panzer0f384432012-08-21 00:52:01 +000011265/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11266/// the completed call expression. If overload resolution fails, emits
11267/// diagnostics and returns ExprError()
11268static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11269 UnresolvedLookupExpr *ULE,
11270 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011271 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011272 SourceLocation RParenLoc,
11273 Expr *ExecConfig,
11274 OverloadCandidateSet *CandidateSet,
11275 OverloadCandidateSet::iterator *Best,
11276 OverloadingResult OverloadResult,
11277 bool AllowTypoCorrection) {
11278 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011279 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011280 RParenLoc, /*EmptyLookup=*/true,
11281 AllowTypoCorrection);
11282
11283 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011284 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011285 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011286 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011287 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11288 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011289 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011290 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11291 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011292 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011293
Richard Smith998a5912011-06-05 22:42:48 +000011294 case OR_No_Viable_Function: {
11295 // Try to recover by looking for viable functions which the user might
11296 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011297 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011298 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011299 /*EmptyLookup=*/false,
11300 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011301 if (!Recovery.isInvalid())
11302 return Recovery;
11303
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011304 // If the user passes in a function that we can't take the address of, we
11305 // generally end up emitting really bad error messages. Here, we attempt to
11306 // emit better ones.
11307 for (const Expr *Arg : Args) {
11308 if (!Arg->getType()->isFunctionType())
11309 continue;
11310 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11311 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11312 if (FD &&
11313 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11314 Arg->getExprLoc()))
11315 return ExprError();
11316 }
11317 }
11318
11319 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11320 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011321 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011322 break;
Richard Smith998a5912011-06-05 22:42:48 +000011323 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011324
11325 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011326 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011327 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011328 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011329 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011330
Sam Panzer0f384432012-08-21 00:52:01 +000011331 case OR_Deleted: {
11332 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11333 << (*Best)->Function->isDeleted()
11334 << ULE->getName()
11335 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11336 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011337 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011338
Sam Panzer0f384432012-08-21 00:52:01 +000011339 // We emitted an error for the unvailable/deleted function call but keep
11340 // the call in the AST.
11341 FunctionDecl *FDecl = (*Best)->Function;
11342 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011343 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11344 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011345 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011346 }
11347
Douglas Gregorb412e172010-07-25 18:17:45 +000011348 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011349 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011350}
11351
George Burgess IV7204ed92016-01-07 02:26:57 +000011352static void markUnaddressableCandidatesUnviable(Sema &S,
11353 OverloadCandidateSet &CS) {
11354 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11355 if (I->Viable &&
11356 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11357 I->Viable = false;
11358 I->FailureKind = ovl_fail_addr_not_available;
11359 }
11360 }
11361}
11362
Sam Panzer0f384432012-08-21 00:52:01 +000011363/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11364/// (which eventually refers to the declaration Func) and the call
11365/// arguments Args/NumArgs, attempt to resolve the function call down
11366/// to a specific function. If overload resolution succeeds, returns
11367/// the call expression produced by overload resolution.
11368/// Otherwise, emits diagnostics and returns ExprError.
11369ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11370 UnresolvedLookupExpr *ULE,
11371 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011372 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011373 SourceLocation RParenLoc,
11374 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011375 bool AllowTypoCorrection,
11376 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011377 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11378 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011379 ExprResult result;
11380
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011381 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11382 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011383 return result;
11384
George Burgess IV7204ed92016-01-07 02:26:57 +000011385 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11386 // functions that aren't addressible are considered unviable.
11387 if (CalleesAddressIsTaken)
11388 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11389
Sam Panzer0f384432012-08-21 00:52:01 +000011390 OverloadCandidateSet::iterator Best;
11391 OverloadingResult OverloadResult =
11392 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11393
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011394 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011395 RParenLoc, ExecConfig, &CandidateSet,
11396 &Best, OverloadResult,
11397 AllowTypoCorrection);
11398}
11399
John McCall4c4c1df2010-01-26 03:27:55 +000011400static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011401 return Functions.size() > 1 ||
11402 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11403}
11404
Douglas Gregor084d8552009-03-13 23:49:33 +000011405/// \brief Create a unary operation that may resolve to an overloaded
11406/// operator.
11407///
11408/// \param OpLoc The location of the operator itself (e.g., '*').
11409///
Craig Toppera92ffb02015-12-10 08:51:49 +000011410/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011411///
James Dennett18348b62012-06-22 08:52:37 +000011412/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011413/// considered by overload resolution. The caller needs to build this
11414/// set based on the context using, e.g.,
11415/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11416/// set should not contain any member functions; those will be added
11417/// by CreateOverloadedUnaryOp().
11418///
James Dennett91738ff2012-06-22 10:32:46 +000011419/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011420ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011421Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011422 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011423 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011424 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11425 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11426 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011427 // TODO: provide better source location info.
11428 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011429
John McCall4124c492011-10-17 18:40:02 +000011430 if (checkPlaceholderForOverload(*this, Input))
11431 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011432
Craig Topperc3ec1492014-05-26 06:22:03 +000011433 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011434 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011435
Douglas Gregor084d8552009-03-13 23:49:33 +000011436 // For post-increment and post-decrement, add the implicit '0' as
11437 // the second argument, so that we know this is a post-increment or
11438 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011439 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011440 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011441 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11442 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011443 NumArgs = 2;
11444 }
11445
Richard Smithe54c3072013-05-05 15:51:06 +000011446 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11447
Douglas Gregor084d8552009-03-13 23:49:33 +000011448 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011449 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011450 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11451 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011452
Craig Topperc3ec1492014-05-26 06:22:03 +000011453 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011454 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011455 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011456 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011457 /*ADL*/ true, IsOverloaded(Fns),
11458 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011459 return new (Context)
11460 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11461 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011462 }
11463
11464 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011465 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011466
11467 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011468 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011469
11470 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011471 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011472
John McCall4c4c1df2010-01-26 03:27:55 +000011473 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011474 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011475 /*ExplicitTemplateArgs*/nullptr,
11476 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011477
Douglas Gregor084d8552009-03-13 23:49:33 +000011478 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011479 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011480
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011481 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11482
Douglas Gregor084d8552009-03-13 23:49:33 +000011483 // Perform overload resolution.
11484 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011485 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011486 case OR_Success: {
11487 // We found a built-in operator or an overloaded operator.
11488 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011489
Douglas Gregor084d8552009-03-13 23:49:33 +000011490 if (FnDecl) {
11491 // We matched an overloaded operator. Build a call to that
11492 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011493
Douglas Gregor084d8552009-03-13 23:49:33 +000011494 // Convert the arguments.
11495 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011496 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011497
John Wiegley01296292011-04-08 18:41:53 +000011498 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011499 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011500 Best->FoundDecl, Method);
11501 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011502 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011503 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011504 } else {
11505 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011506 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011507 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011508 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011509 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011510 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011511 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011512 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011513 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011514 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011515 }
11516
Douglas Gregor084d8552009-03-13 23:49:33 +000011517 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011518 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011519 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011520 if (FnExpr.isInvalid())
11521 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011522
Richard Smithc1564702013-11-15 02:58:23 +000011523 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011524 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011525 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11526 ResultTy = ResultTy.getNonLValueExprType(Context);
11527
Eli Friedman030eee42009-11-18 03:58:17 +000011528 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011529 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011530 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011531 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011532
Alp Toker314cc812014-01-25 16:55:45 +000011533 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011534 return ExprError();
11535
John McCallb268a282010-08-23 23:25:46 +000011536 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011537 } else {
11538 // We matched a built-in operator. Convert the arguments, then
11539 // break out so that we will build the appropriate built-in
11540 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011541 ExprResult InputRes =
11542 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11543 Best->Conversions[0], AA_Passing);
11544 if (InputRes.isInvalid())
11545 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011546 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011547 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011548 }
John Wiegley01296292011-04-08 18:41:53 +000011549 }
11550
11551 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011552 // This is an erroneous use of an operator which can be overloaded by
11553 // a non-member function. Check for non-member operators which were
11554 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011555 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011556 // FIXME: Recover by calling the found function.
11557 return ExprError();
11558
John Wiegley01296292011-04-08 18:41:53 +000011559 // No viable function; fall through to handling this as a
11560 // built-in operator, which will produce an error message for us.
11561 break;
11562
11563 case OR_Ambiguous:
11564 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11565 << UnaryOperator::getOpcodeStr(Opc)
11566 << Input->getType()
11567 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011568 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011569 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11570 return ExprError();
11571
11572 case OR_Deleted:
11573 Diag(OpLoc, diag::err_ovl_deleted_oper)
11574 << Best->Function->isDeleted()
11575 << UnaryOperator::getOpcodeStr(Opc)
11576 << getDeletedOrUnavailableSuffix(Best->Function)
11577 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011578 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011579 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011580 return ExprError();
11581 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011582
11583 // Either we found no viable overloaded operator or we matched a
11584 // built-in operator. In either case, fall through to trying to
11585 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011586 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011587}
11588
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011589/// \brief Create a binary operation that may resolve to an overloaded
11590/// operator.
11591///
11592/// \param OpLoc The location of the operator itself (e.g., '+').
11593///
Craig Toppera92ffb02015-12-10 08:51:49 +000011594/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011595///
James Dennett18348b62012-06-22 08:52:37 +000011596/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011597/// considered by overload resolution. The caller needs to build this
11598/// set based on the context using, e.g.,
11599/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11600/// set should not contain any member functions; those will be added
11601/// by CreateOverloadedBinOp().
11602///
11603/// \param LHS Left-hand argument.
11604/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011605ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011606Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011607 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011608 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011609 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011610 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011611 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011612
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011613 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11614 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11615
11616 // If either side is type-dependent, create an appropriate dependent
11617 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011618 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011619 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011620 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011621 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011622 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011623 return new (Context) BinaryOperator(
11624 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11625 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011626
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011627 return new (Context) CompoundAssignOperator(
11628 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11629 Context.DependentTy, Context.DependentTy, OpLoc,
11630 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011631 }
John McCall4c4c1df2010-01-26 03:27:55 +000011632
11633 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011634 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011635 // TODO: provide better source location info in DNLoc component.
11636 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011637 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011638 = UnresolvedLookupExpr::Create(Context, NamingClass,
11639 NestedNameSpecifierLoc(), OpNameInfo,
11640 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011641 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011642 return new (Context)
11643 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11644 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011645 }
11646
John McCall4124c492011-10-17 18:40:02 +000011647 // Always do placeholder-like conversions on the RHS.
11648 if (checkPlaceholderForOverload(*this, Args[1]))
11649 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011650
John McCall526ab472011-10-25 17:37:35 +000011651 // Do placeholder-like conversion on the LHS; note that we should
11652 // not get here with a PseudoObject LHS.
11653 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011654 if (checkPlaceholderForOverload(*this, Args[0]))
11655 return ExprError();
11656
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011657 // If this is the assignment operator, we only perform overload resolution
11658 // if the left-hand side is a class or enumeration type. This is actually
11659 // a hack. The standard requires that we do overload resolution between the
11660 // various built-in candidates, but as DR507 points out, this can lead to
11661 // problems. So we do it this way, which pretty much follows what GCC does.
11662 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011663 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011664 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011665
John McCalle26a8722010-12-04 08:14:53 +000011666 // If this is the .* operator, which is not overloadable, just
11667 // create a built-in binary operator.
11668 if (Opc == BO_PtrMemD)
11669 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11670
Douglas Gregor084d8552009-03-13 23:49:33 +000011671 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011672 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011673
11674 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011675 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011676
11677 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011678 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011679
Richard Smith0daabd72014-09-23 20:31:39 +000011680 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11681 // performed for an assignment operator (nor for operator[] nor operator->,
11682 // which don't get here).
11683 if (Opc != BO_Assign)
11684 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11685 /*ExplicitTemplateArgs*/ nullptr,
11686 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011687
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011688 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011689 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011690
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011691 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11692
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011693 // Perform overload resolution.
11694 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011695 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011696 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011697 // We found a built-in operator or an overloaded operator.
11698 FunctionDecl *FnDecl = Best->Function;
11699
11700 if (FnDecl) {
11701 // We matched an overloaded operator. Build a call to that
11702 // operator.
11703
11704 // Convert the arguments.
11705 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011706 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011707 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011708
Chandler Carruth8e543b32010-12-12 08:17:55 +000011709 ExprResult Arg1 =
11710 PerformCopyInitialization(
11711 InitializedEntity::InitializeParameter(Context,
11712 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011713 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011714 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011715 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011716
John Wiegley01296292011-04-08 18:41:53 +000011717 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011718 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011719 Best->FoundDecl, Method);
11720 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011721 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011722 Args[0] = Arg0.getAs<Expr>();
11723 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011724 } else {
11725 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011726 ExprResult Arg0 = PerformCopyInitialization(
11727 InitializedEntity::InitializeParameter(Context,
11728 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011729 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011730 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011731 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011732
Chandler Carruth8e543b32010-12-12 08:17:55 +000011733 ExprResult Arg1 =
11734 PerformCopyInitialization(
11735 InitializedEntity::InitializeParameter(Context,
11736 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011737 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011738 if (Arg1.isInvalid())
11739 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011740 Args[0] = LHS = Arg0.getAs<Expr>();
11741 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011742 }
11743
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011744 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011745 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011746 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011747 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011748 if (FnExpr.isInvalid())
11749 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011750
Richard Smithc1564702013-11-15 02:58:23 +000011751 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011752 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011753 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11754 ResultTy = ResultTy.getNonLValueExprType(Context);
11755
John McCallb268a282010-08-23 23:25:46 +000011756 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011757 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011758 Args, ResultTy, VK, OpLoc,
11759 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011760
Alp Toker314cc812014-01-25 16:55:45 +000011761 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011762 FnDecl))
11763 return ExprError();
11764
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011765 ArrayRef<const Expr *> ArgsArray(Args, 2);
11766 // Cut off the implicit 'this'.
11767 if (isa<CXXMethodDecl>(FnDecl))
11768 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011769
11770 // Check for a self move.
11771 if (Op == OO_Equal)
11772 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11773
Douglas Gregorb4866e82015-06-19 18:13:19 +000011774 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011775 TheCall->getSourceRange(), VariadicDoesNotApply);
11776
John McCallb268a282010-08-23 23:25:46 +000011777 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011778 } else {
11779 // We matched a built-in operator. Convert the arguments, then
11780 // break out so that we will build the appropriate built-in
11781 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011782 ExprResult ArgsRes0 =
11783 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11784 Best->Conversions[0], AA_Passing);
11785 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011786 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011787 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011788
John Wiegley01296292011-04-08 18:41:53 +000011789 ExprResult ArgsRes1 =
11790 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11791 Best->Conversions[1], AA_Passing);
11792 if (ArgsRes1.isInvalid())
11793 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011794 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011795 break;
11796 }
11797 }
11798
Douglas Gregor66950a32009-09-30 21:46:01 +000011799 case OR_No_Viable_Function: {
11800 // C++ [over.match.oper]p9:
11801 // If the operator is the operator , [...] and there are no
11802 // viable functions, then the operator is assumed to be the
11803 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011804 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011805 break;
11806
Chandler Carruth8e543b32010-12-12 08:17:55 +000011807 // For class as left operand for assignment or compound assigment
11808 // operator do not fall through to handling in built-in, but report that
11809 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011810 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011811 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011812 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011813 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11814 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011815 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011816 if (Args[0]->getType()->isIncompleteType()) {
11817 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11818 << Args[0]->getType()
11819 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11820 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011821 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011822 // This is an erroneous use of an operator which can be overloaded by
11823 // a non-member function. Check for non-member operators which were
11824 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011825 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011826 // FIXME: Recover by calling the found function.
11827 return ExprError();
11828
Douglas Gregor66950a32009-09-30 21:46:01 +000011829 // No viable function; try to create a built-in operation, which will
11830 // produce an error. Then, show the non-viable candidates.
11831 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011833 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011834 "C++ binary operator overloading is missing candidates!");
11835 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011836 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011837 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011838 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011839 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011840
11841 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011842 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011843 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011844 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011845 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011846 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011847 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011848 return ExprError();
11849
11850 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011851 if (isImplicitlyDeleted(Best->Function)) {
11852 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11853 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011854 << Context.getRecordType(Method->getParent())
11855 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011856
Richard Smithde1a4872012-12-28 12:23:24 +000011857 // The user probably meant to call this special member. Just
11858 // explain why it's deleted.
11859 NoteDeletedFunction(Method);
11860 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011861 } else {
11862 Diag(OpLoc, diag::err_ovl_deleted_oper)
11863 << Best->Function->isDeleted()
11864 << BinaryOperator::getOpcodeStr(Opc)
11865 << getDeletedOrUnavailableSuffix(Best->Function)
11866 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11867 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011868 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011869 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011870 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011871 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011872
Douglas Gregor66950a32009-09-30 21:46:01 +000011873 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011874 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011875}
11876
John McCalldadc5752010-08-24 06:29:42 +000011877ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011878Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11879 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011880 Expr *Base, Expr *Idx) {
11881 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011882 DeclarationName OpName =
11883 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11884
11885 // If either side is type-dependent, create an appropriate dependent
11886 // expression.
11887 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11888
Craig Topperc3ec1492014-05-26 06:22:03 +000011889 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011890 // CHECKME: no 'operator' keyword?
11891 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11892 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011893 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011894 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011895 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011896 /*ADL*/ true, /*Overloaded*/ false,
11897 UnresolvedSetIterator(),
11898 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011899 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011900
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011901 return new (Context)
11902 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11903 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011904 }
11905
John McCall4124c492011-10-17 18:40:02 +000011906 // Handle placeholders on both operands.
11907 if (checkPlaceholderForOverload(*this, Args[0]))
11908 return ExprError();
11909 if (checkPlaceholderForOverload(*this, Args[1]))
11910 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011911
Sebastian Redladba46e2009-10-29 20:17:01 +000011912 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011913 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011914
11915 // Subscript can only be overloaded as a member function.
11916
11917 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011918 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011919
11920 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011921 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011922
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011923 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11924
Sebastian Redladba46e2009-10-29 20:17:01 +000011925 // Perform overload resolution.
11926 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011927 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011928 case OR_Success: {
11929 // We found a built-in operator or an overloaded operator.
11930 FunctionDecl *FnDecl = Best->Function;
11931
11932 if (FnDecl) {
11933 // We matched an overloaded operator. Build a call to that
11934 // operator.
11935
John McCalla0296f72010-03-19 07:35:19 +000011936 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011937
Sebastian Redladba46e2009-10-29 20:17:01 +000011938 // Convert the arguments.
11939 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011940 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011941 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011942 Best->FoundDecl, Method);
11943 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011944 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011945 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011946
Anders Carlssona68e51e2010-01-29 18:37:50 +000011947 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011948 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011949 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011950 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011951 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011952 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011953 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011954 if (InputInit.isInvalid())
11955 return ExprError();
11956
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011957 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011958
Sebastian Redladba46e2009-10-29 20:17:01 +000011959 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011960 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11961 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011962 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011963 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011964 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011965 OpLocInfo.getLoc(),
11966 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011967 if (FnExpr.isInvalid())
11968 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011969
Richard Smithc1564702013-11-15 02:58:23 +000011970 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011971 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011972 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11973 ResultTy = ResultTy.getNonLValueExprType(Context);
11974
John McCallb268a282010-08-23 23:25:46 +000011975 CXXOperatorCallExpr *TheCall =
11976 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011977 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011978 ResultTy, VK, RLoc,
11979 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011980
Alp Toker314cc812014-01-25 16:55:45 +000011981 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011982 return ExprError();
11983
John McCallb268a282010-08-23 23:25:46 +000011984 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011985 } else {
11986 // We matched a built-in operator. Convert the arguments, then
11987 // break out so that we will build the appropriate built-in
11988 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011989 ExprResult ArgsRes0 =
11990 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11991 Best->Conversions[0], AA_Passing);
11992 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011993 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011994 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011995
11996 ExprResult ArgsRes1 =
11997 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11998 Best->Conversions[1], AA_Passing);
11999 if (ArgsRes1.isInvalid())
12000 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012001 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012002
12003 break;
12004 }
12005 }
12006
12007 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012008 if (CandidateSet.empty())
12009 Diag(LLoc, diag::err_ovl_no_oper)
12010 << Args[0]->getType() << /*subscript*/ 0
12011 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12012 else
12013 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12014 << Args[0]->getType()
12015 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012016 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012017 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012018 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012019 }
12020
12021 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012022 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012023 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012024 << Args[0]->getType() << Args[1]->getType()
12025 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012026 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012027 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012028 return ExprError();
12029
12030 case OR_Deleted:
12031 Diag(LLoc, diag::err_ovl_deleted_oper)
12032 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012033 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012034 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012035 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012036 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012037 return ExprError();
12038 }
12039
12040 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012041 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012042}
12043
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012044/// BuildCallToMemberFunction - Build a call to a member
12045/// function. MemExpr is the expression that refers to the member
12046/// function (and includes the object parameter), Args/NumArgs are the
12047/// arguments to the function call (not including the object
12048/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012049/// expression refers to a non-static member function or an overloaded
12050/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012051ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012052Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012053 SourceLocation LParenLoc,
12054 MultiExprArg Args,
12055 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012056 assert(MemExprE->getType() == Context.BoundMemberTy ||
12057 MemExprE->getType() == Context.OverloadTy);
12058
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012059 // Dig out the member expression. This holds both the object
12060 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012061 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012062
John McCall0009fcc2011-04-26 20:42:42 +000012063 // Determine whether this is a call to a pointer-to-member function.
12064 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12065 assert(op->getType() == Context.BoundMemberTy);
12066 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12067
12068 QualType fnType =
12069 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12070
12071 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12072 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012073 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012074
12075 // Check that the object type isn't more qualified than the
12076 // member function we're calling.
12077 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12078
12079 QualType objectType = op->getLHS()->getType();
12080 if (op->getOpcode() == BO_PtrMemI)
12081 objectType = objectType->castAs<PointerType>()->getPointeeType();
12082 Qualifiers objectQuals = objectType.getQualifiers();
12083
12084 Qualifiers difference = objectQuals - funcQuals;
12085 difference.removeObjCGCAttr();
12086 difference.removeAddressSpace();
12087 if (difference) {
12088 std::string qualsString = difference.getAsString();
12089 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12090 << fnType.getUnqualifiedType()
12091 << qualsString
12092 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12093 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012094
John McCall0009fcc2011-04-26 20:42:42 +000012095 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012096 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012097 resultType, valueKind, RParenLoc);
12098
Alp Toker314cc812014-01-25 16:55:45 +000012099 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012100 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012101 return ExprError();
12102
Craig Topperc3ec1492014-05-26 06:22:03 +000012103 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012104 return ExprError();
12105
Richard Trieu9be9c682013-06-22 02:30:38 +000012106 if (CheckOtherCall(call, proto))
12107 return ExprError();
12108
John McCall0009fcc2011-04-26 20:42:42 +000012109 return MaybeBindToTemporary(call);
12110 }
12111
David Majnemerced8bdf2015-02-25 17:36:15 +000012112 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12113 return new (Context)
12114 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12115
John McCall4124c492011-10-17 18:40:02 +000012116 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012117 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012118 return ExprError();
12119
John McCall10eae182009-11-30 22:42:35 +000012120 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012121 CXXMethodDecl *Method = nullptr;
12122 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12123 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012124 if (isa<MemberExpr>(NakedMemExpr)) {
12125 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012126 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012127 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012128 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012129 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012130 } else {
12131 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012132 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012133
John McCall6e9f8f62009-12-03 04:06:58 +000012134 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012135 Expr::Classification ObjectClassification
12136 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12137 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012138
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012139 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012140 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12141 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012142
John McCall2d74de92009-12-01 22:10:20 +000012143 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012144 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012145 if (UnresExpr->hasExplicitTemplateArgs()) {
12146 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12147 TemplateArgs = &TemplateArgsBuffer;
12148 }
12149
John McCall10eae182009-11-30 22:42:35 +000012150 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12151 E = UnresExpr->decls_end(); I != E; ++I) {
12152
John McCall6e9f8f62009-12-03 04:06:58 +000012153 NamedDecl *Func = *I;
12154 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12155 if (isa<UsingShadowDecl>(Func))
12156 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12157
Douglas Gregor02824322011-01-26 19:30:28 +000012158
Francois Pichet64225792011-01-18 05:04:39 +000012159 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012160 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012161 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012162 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012163 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012164 // If explicit template arguments were provided, we can't call a
12165 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012166 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012167 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012168
John McCalla0296f72010-03-19 07:35:19 +000012169 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012170 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012171 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012172 } else {
John McCall10eae182009-11-30 22:42:35 +000012173 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012174 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012175 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012176 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012177 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012178 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012179 }
Mike Stump11289f42009-09-09 15:08:12 +000012180
John McCall10eae182009-11-30 22:42:35 +000012181 DeclarationName DeclName = UnresExpr->getMemberName();
12182
John McCall4124c492011-10-17 18:40:02 +000012183 UnbridgedCasts.restore();
12184
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012185 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012186 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012187 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012188 case OR_Success:
12189 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012190 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012191 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012192 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12193 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012194 // If FoundDecl is different from Method (such as if one is a template
12195 // and the other a specialization), make sure DiagnoseUseOfDecl is
12196 // called on both.
12197 // FIXME: This would be more comprehensively addressed by modifying
12198 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12199 // being used.
12200 if (Method != FoundDecl.getDecl() &&
12201 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12202 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012203 break;
12204
12205 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012206 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012207 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012208 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012209 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012210 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012211 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012212
12213 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012214 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012215 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012216 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012217 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012218 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012219
12220 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012221 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012222 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012223 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012224 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012225 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012226 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012227 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012228 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012229 }
12230
John McCall16df1e52010-03-30 21:47:33 +000012231 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012232
John McCall2d74de92009-12-01 22:10:20 +000012233 // If overload resolution picked a static member, build a
12234 // non-member call based on that function.
12235 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012236 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12237 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012238 }
12239
John McCall10eae182009-11-30 22:42:35 +000012240 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012241 }
12242
Alp Toker314cc812014-01-25 16:55:45 +000012243 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012244 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12245 ResultType = ResultType.getNonLValueExprType(Context);
12246
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012247 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012248 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012249 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012250 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012251
Eli Bendersky291a57e2014-09-25 23:59:08 +000012252 // (CUDA B.1): Check for invalid calls between targets.
12253 if (getLangOpts().CUDA) {
12254 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12255 if (CheckCUDATarget(Caller, Method)) {
12256 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12257 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12258 << IdentifyCUDATarget(Caller);
12259 return ExprError();
12260 }
12261 }
12262 }
12263
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012264 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012265 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012266 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012267 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012268
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012269 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012270 // We only need to do this if there was actually an overload; otherwise
12271 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012272 if (!Method->isStatic()) {
12273 ExprResult ObjectArg =
12274 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12275 FoundDecl, Method);
12276 if (ObjectArg.isInvalid())
12277 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012278 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012279 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012280
12281 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012282 const FunctionProtoType *Proto =
12283 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012284 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012285 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012286 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012287
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012288 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012289
Richard Smith55ce3522012-06-25 20:30:08 +000012290 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012291 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012292
George Burgess IVaea6ade2015-09-25 17:53:16 +000012293 // In the case the method to call was not selected by the overloading
12294 // resolution process, we still need to handle the enable_if attribute. Do
12295 // that here, so it will not hide previous -- and more relevant -- errors
12296 if (isa<MemberExpr>(NakedMemExpr)) {
12297 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12298 Diag(MemExprE->getLocStart(),
12299 diag::err_ovl_no_viable_member_function_in_call)
12300 << Method << Method->getSourceRange();
12301 Diag(Method->getLocation(),
12302 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12303 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12304 return ExprError();
12305 }
12306 }
12307
Anders Carlsson47061ee2011-05-06 14:25:31 +000012308 if ((isa<CXXConstructorDecl>(CurContext) ||
12309 isa<CXXDestructorDecl>(CurContext)) &&
12310 TheCall->getMethodDecl()->isPure()) {
12311 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12312
Davide Italianoccb37382015-07-14 23:36:10 +000012313 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12314 MemExpr->performsVirtualDispatch(getLangOpts())) {
12315 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012316 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12317 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12318 << MD->getParent()->getDeclName();
12319
12320 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012321 if (getLangOpts().AppleKext)
12322 Diag(MemExpr->getLocStart(),
12323 diag::note_pure_qualified_call_kext)
12324 << MD->getParent()->getDeclName()
12325 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012326 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012327 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012328
12329 if (CXXDestructorDecl *DD =
12330 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12331 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12332 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() ||
12333 getLangOpts().AppleKext;
12334 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12335 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12336 MemExpr->getMemberLoc());
12337 }
12338
John McCallb268a282010-08-23 23:25:46 +000012339 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012340}
12341
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012342/// BuildCallToObjectOfClassType - Build a call to an object of class
12343/// type (C++ [over.call.object]), which can end up invoking an
12344/// overloaded function call operator (@c operator()) or performing a
12345/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012346ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012347Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012348 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012349 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012350 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012351 if (checkPlaceholderForOverload(*this, Obj))
12352 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012353 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012354
12355 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012356 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012357 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012358
Nico Weberb58e51c2014-11-19 05:21:39 +000012359 assert(Object.get()->getType()->isRecordType() &&
12360 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012361 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012362
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012363 // C++ [over.call.object]p1:
12364 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012365 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012366 // candidate functions includes at least the function call
12367 // operators of T. The function call operators of T are obtained by
12368 // ordinary lookup of the name operator() in the context of
12369 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012370 OverloadCandidateSet CandidateSet(LParenLoc,
12371 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012372 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012373
John Wiegley01296292011-04-08 18:41:53 +000012374 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012375 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012376 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012377
John McCall27b18f82009-11-17 02:14:36 +000012378 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12379 LookupQualifiedName(R, Record->getDecl());
12380 R.suppressDiagnostics();
12381
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012382 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012383 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012384 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012385 Object.get()->Classify(Context),
12386 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012387 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012389
Douglas Gregorab7897a2008-11-19 22:57:39 +000012390 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012391 // In addition, for each (non-explicit in C++0x) conversion function
12392 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012393 //
12394 // operator conversion-type-id () cv-qualifier;
12395 //
12396 // where cv-qualifier is the same cv-qualification as, or a
12397 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012398 // denotes the type "pointer to function of (P1,...,Pn) returning
12399 // R", or the type "reference to pointer to function of
12400 // (P1,...,Pn) returning R", or the type "reference to function
12401 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012402 // is also considered as a candidate function. Similarly,
12403 // surrogate call functions are added to the set of candidate
12404 // functions for each conversion function declared in an
12405 // accessible base class provided the function is not hidden
12406 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012407 const auto &Conversions =
12408 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12409 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012410 NamedDecl *D = *I;
12411 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12412 if (isa<UsingShadowDecl>(D))
12413 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012414
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012415 // Skip over templated conversion functions; they aren't
12416 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012417 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012418 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012419
John McCall6e9f8f62009-12-03 04:06:58 +000012420 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012421 if (!Conv->isExplicit()) {
12422 // Strip the reference type (if any) and then the pointer type (if
12423 // any) to get down to what might be a function type.
12424 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12425 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12426 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012427
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012428 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12429 {
12430 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012431 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012432 }
12433 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012434 }
Mike Stump11289f42009-09-09 15:08:12 +000012435
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012436 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12437
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012438 // Perform overload resolution.
12439 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012440 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012441 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012442 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012443 // Overload resolution succeeded; we'll build the appropriate call
12444 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012445 break;
12446
12447 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012448 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012449 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012450 << Object.get()->getType() << /*call*/ 1
12451 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012452 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012453 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012454 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012455 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012456 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012457 break;
12458
12459 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012460 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012461 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012462 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012463 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012464 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012465
12466 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012467 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012468 diag::err_ovl_deleted_object_call)
12469 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012470 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012471 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012472 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012473 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012474 break;
Mike Stump11289f42009-09-09 15:08:12 +000012475 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012476
Douglas Gregorb412e172010-07-25 18:17:45 +000012477 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012478 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012479
John McCall4124c492011-10-17 18:40:02 +000012480 UnbridgedCasts.restore();
12481
Craig Topperc3ec1492014-05-26 06:22:03 +000012482 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012483 // Since there is no function declaration, this is one of the
12484 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012485 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012486 = cast<CXXConversionDecl>(
12487 Best->Conversions[0].UserDefined.ConversionFunction);
12488
Craig Topperc3ec1492014-05-26 06:22:03 +000012489 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12490 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012491 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12492 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012493 assert(Conv == Best->FoundDecl.getDecl() &&
12494 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012495 // We selected one of the surrogate functions that converts the
12496 // object parameter to a function pointer. Perform the conversion
12497 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012498
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012499 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012500 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012501 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12502 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012503 if (Call.isInvalid())
12504 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012505 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012506 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12507 CK_UserDefinedConversion, Call.get(),
12508 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012509
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012510 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012511 }
12512
Craig Topperc3ec1492014-05-26 06:22:03 +000012513 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012514
Douglas Gregorab7897a2008-11-19 22:57:39 +000012515 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12516 // that calls this method, using Object for the implicit object
12517 // parameter and passing along the remaining arguments.
12518 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012519
12520 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012521 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012522 return ExprError();
12523
Chandler Carruth8e543b32010-12-12 08:17:55 +000012524 const FunctionProtoType *Proto =
12525 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012526
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012527 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012528
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012529 DeclarationNameInfo OpLocInfo(
12530 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12531 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012532 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012533 HadMultipleCandidates,
12534 OpLocInfo.getLoc(),
12535 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012536 if (NewFn.isInvalid())
12537 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012538
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012539 // Build the full argument list for the method call (the implicit object
12540 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012541 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012542 MethodArgs[0] = Object.get();
12543 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12544
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012545 // Once we've built TheCall, all of the expressions are properly
12546 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012547 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012548 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12549 ResultTy = ResultTy.getNonLValueExprType(Context);
12550
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012551 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012552 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012553 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12554 ResultTy, VK, RParenLoc, false);
12555 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012556
Alp Toker314cc812014-01-25 16:55:45 +000012557 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012558 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012559
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012560 // We may have default arguments. If so, we need to allocate more
12561 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012562 if (Args.size() < NumParams)
12563 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012564
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012565 bool IsError = false;
12566
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012567 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012568 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012569 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012570 Best->FoundDecl, Method);
12571 if (ObjRes.isInvalid())
12572 IsError = true;
12573 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012574 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012575 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012576
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012577 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012578 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012579 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012580 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012581 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012582
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012583 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012584
John McCalldadc5752010-08-24 06:29:42 +000012585 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012586 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012587 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012588 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012589 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012590
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012591 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012592 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012593 } else {
John McCalldadc5752010-08-24 06:29:42 +000012594 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012595 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12596 if (DefArg.isInvalid()) {
12597 IsError = true;
12598 break;
12599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012600
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012601 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012602 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012603
12604 TheCall->setArg(i + 1, Arg);
12605 }
12606
12607 // If this is a variadic call, handle args passed through "...".
12608 if (Proto->isVariadic()) {
12609 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012610 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012611 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12612 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012613 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012614 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012615 }
12616 }
12617
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012618 if (IsError) return true;
12619
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012620 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012621
Richard Smith55ce3522012-06-25 20:30:08 +000012622 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012623 return true;
12624
John McCalle172be52010-08-24 06:09:16 +000012625 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012626}
12627
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012628/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012629/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012630/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012631ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012632Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12633 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012634 assert(Base->getType()->isRecordType() &&
12635 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012636
John McCall4124c492011-10-17 18:40:02 +000012637 if (checkPlaceholderForOverload(*this, Base))
12638 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012639
John McCallbc077cf2010-02-08 23:07:23 +000012640 SourceLocation Loc = Base->getExprLoc();
12641
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012642 // C++ [over.ref]p1:
12643 //
12644 // [...] An expression x->m is interpreted as (x.operator->())->m
12645 // for a class object x of type T if T::operator->() exists and if
12646 // the operator is selected as the best match function by the
12647 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012648 DeclarationName OpName =
12649 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012650 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012651 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012652
John McCallbc077cf2010-02-08 23:07:23 +000012653 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012654 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012655 return ExprError();
12656
John McCall27b18f82009-11-17 02:14:36 +000012657 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12658 LookupQualifiedName(R, BaseRecord->getDecl());
12659 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012660
12661 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012662 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012663 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012664 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012665 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012666
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012667 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12668
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012669 // Perform overload resolution.
12670 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012671 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012672 case OR_Success:
12673 // Overload resolution succeeded; we'll build the call below.
12674 break;
12675
12676 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012677 if (CandidateSet.empty()) {
12678 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012679 if (NoArrowOperatorFound) {
12680 // Report this specific error to the caller instead of emitting a
12681 // diagnostic, as requested.
12682 *NoArrowOperatorFound = true;
12683 return ExprError();
12684 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012685 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12686 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012687 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012688 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012689 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012690 }
12691 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012692 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012693 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012694 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012695 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012696
12697 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012698 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12699 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012700 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012701 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012702
12703 case OR_Deleted:
12704 Diag(OpLoc, diag::err_ovl_deleted_oper)
12705 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012706 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012707 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012708 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012709 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012710 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012711 }
12712
Craig Topperc3ec1492014-05-26 06:22:03 +000012713 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012714
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012715 // Convert the object parameter.
12716 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012717 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012718 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012719 Best->FoundDecl, Method);
12720 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012721 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012722 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012723
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012724 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012725 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012726 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012727 if (FnExpr.isInvalid())
12728 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012729
Alp Toker314cc812014-01-25 16:55:45 +000012730 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012731 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12732 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012733 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012734 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012735 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012736
Alp Toker314cc812014-01-25 16:55:45 +000012737 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012738 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012739
12740 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012741}
12742
Richard Smithbcc22fc2012-03-09 08:00:36 +000012743/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12744/// a literal operator described by the provided lookup results.
12745ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12746 DeclarationNameInfo &SuffixInfo,
12747 ArrayRef<Expr*> Args,
12748 SourceLocation LitEndLoc,
12749 TemplateArgumentListInfo *TemplateArgs) {
12750 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012751
Richard Smith100b24a2014-04-17 01:52:14 +000012752 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12753 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012754 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12755 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012756
Richard Smithbcc22fc2012-03-09 08:00:36 +000012757 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12758
Richard Smithbcc22fc2012-03-09 08:00:36 +000012759 // Perform overload resolution. This will usually be trivial, but might need
12760 // to perform substitutions for a literal operator template.
12761 OverloadCandidateSet::iterator Best;
12762 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12763 case OR_Success:
12764 case OR_Deleted:
12765 break;
12766
12767 case OR_No_Viable_Function:
12768 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12769 << R.getLookupName();
12770 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12771 return ExprError();
12772
12773 case OR_Ambiguous:
12774 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12775 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12776 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012777 }
12778
Richard Smithbcc22fc2012-03-09 08:00:36 +000012779 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012780 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12781 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012782 SuffixInfo.getLoc(),
12783 SuffixInfo.getInfo());
12784 if (Fn.isInvalid())
12785 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012786
12787 // Check the argument types. This should almost always be a no-op, except
12788 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012789 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012790 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012791 ExprResult InputInit = PerformCopyInitialization(
12792 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12793 SourceLocation(), Args[ArgIdx]);
12794 if (InputInit.isInvalid())
12795 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012796 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012797 }
12798
Alp Toker314cc812014-01-25 16:55:45 +000012799 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012800 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12801 ResultTy = ResultTy.getNonLValueExprType(Context);
12802
Richard Smithc67fdd42012-03-07 08:35:16 +000012803 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012804 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012805 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012806 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12807
Alp Toker314cc812014-01-25 16:55:45 +000012808 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012809 return ExprError();
12810
Craig Topperc3ec1492014-05-26 06:22:03 +000012811 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012812 return ExprError();
12813
12814 return MaybeBindToTemporary(UDL);
12815}
12816
Sam Panzer0f384432012-08-21 00:52:01 +000012817/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12818/// given LookupResult is non-empty, it is assumed to describe a member which
12819/// will be invoked. Otherwise, the function will be found via argument
12820/// dependent lookup.
12821/// CallExpr is set to a valid expression and FRS_Success returned on success,
12822/// otherwise CallExpr is set to ExprError() and some non-success value
12823/// is returned.
12824Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012825Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12826 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012827 const DeclarationNameInfo &NameInfo,
12828 LookupResult &MemberLookup,
12829 OverloadCandidateSet *CandidateSet,
12830 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012831 Scope *S = nullptr;
12832
Sam Panzer0f384432012-08-21 00:52:01 +000012833 CandidateSet->clear();
12834 if (!MemberLookup.empty()) {
12835 ExprResult MemberRef =
12836 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12837 /*IsPtr=*/false, CXXScopeSpec(),
12838 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012839 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012840 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012841 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012842 if (MemberRef.isInvalid()) {
12843 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012844 return FRS_DiagnosticIssued;
12845 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012846 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012847 if (CallExpr->isInvalid()) {
12848 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012849 return FRS_DiagnosticIssued;
12850 }
12851 } else {
12852 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012853 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012854 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012855 NestedNameSpecifierLoc(), NameInfo,
12856 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012857 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012858
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012859 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012860 CandidateSet, CallExpr);
12861 if (CandidateSet->empty() || CandidateSetError) {
12862 *CallExpr = ExprError();
12863 return FRS_NoViableFunction;
12864 }
12865 OverloadCandidateSet::iterator Best;
12866 OverloadingResult OverloadResult =
12867 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12868
12869 if (OverloadResult == OR_No_Viable_Function) {
12870 *CallExpr = ExprError();
12871 return FRS_NoViableFunction;
12872 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012873 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012874 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012875 OverloadResult,
12876 /*AllowTypoCorrection=*/false);
12877 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12878 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012879 return FRS_DiagnosticIssued;
12880 }
12881 }
12882 return FRS_Success;
12883}
12884
12885
Douglas Gregorcd695e52008-11-10 20:40:00 +000012886/// FixOverloadedFunctionReference - E is an expression that refers to
12887/// a C++ overloaded function (possibly with some parentheses and
12888/// perhaps a '&' around it). We have resolved the overloaded function
12889/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012890/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012891Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012892 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012893 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012894 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12895 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012896 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012897 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012898
Douglas Gregor51c538b2009-11-20 19:42:02 +000012899 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012900 }
12901
Douglas Gregor51c538b2009-11-20 19:42:02 +000012902 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012903 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12904 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012905 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012906 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012907 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012908 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012909 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012910 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012911
12912 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012913 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012914 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012915 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012916 }
12917
Douglas Gregor51c538b2009-11-20 19:42:02 +000012918 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012919 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012920 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012921 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12922 if (Method->isStatic()) {
12923 // Do nothing: static member functions aren't any different
12924 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012925 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012926 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012927 // UnresolvedLookupExpr holding an overloaded member function
12928 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012929 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12930 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012931 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012932 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012933
John McCalld14a8642009-11-21 08:51:07 +000012934 assert(isa<DeclRefExpr>(SubExpr)
12935 && "fixed to something other than a decl ref");
12936 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12937 && "fixed to a member ref with no nested name qualifier");
12938
12939 // We have taken the address of a pointer to member
12940 // function. Perform the computation here so that we get the
12941 // appropriate pointer to member type.
12942 QualType ClassType
12943 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12944 QualType MemPtrType
12945 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12946
John McCall7decc9e2010-11-18 06:31:45 +000012947 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12948 VK_RValue, OK_Ordinary,
12949 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012950 }
12951 }
John McCall16df1e52010-03-30 21:47:33 +000012952 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12953 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012954 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012955 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012956
John McCalle3027922010-08-25 11:45:40 +000012957 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012958 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012959 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012960 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012961 }
John McCalld14a8642009-11-21 08:51:07 +000012962
12963 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012964 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012965 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012966 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012967 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12968 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012969 }
12970
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012971 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12972 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012973 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012974 Fn,
John McCall113bee02012-03-10 09:33:50 +000012975 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012976 ULE->getNameLoc(),
12977 Fn->getType(),
12978 VK_LValue,
12979 Found.getDecl(),
12980 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012981 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012982 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12983 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012984 }
12985
John McCall10eae182009-11-30 22:42:35 +000012986 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012987 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012988 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012989 if (MemExpr->hasExplicitTemplateArgs()) {
12990 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12991 TemplateArgs = &TemplateArgsBuffer;
12992 }
John McCall6b51f282009-11-23 01:53:49 +000012993
John McCall2d74de92009-12-01 22:10:20 +000012994 Expr *Base;
12995
John McCall7decc9e2010-11-18 06:31:45 +000012996 // If we're filling in a static method where we used to have an
12997 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012998 if (MemExpr->isImplicitAccess()) {
12999 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013000 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13001 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013002 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013003 Fn,
John McCall113bee02012-03-10 09:33:50 +000013004 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013005 MemExpr->getMemberLoc(),
13006 Fn->getType(),
13007 VK_LValue,
13008 Found.getDecl(),
13009 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013010 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013011 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13012 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013013 } else {
13014 SourceLocation Loc = MemExpr->getMemberLoc();
13015 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013016 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013017 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013018 Base = new (Context) CXXThisExpr(Loc,
13019 MemExpr->getBaseType(),
13020 /*isImplicit=*/true);
13021 }
John McCall2d74de92009-12-01 22:10:20 +000013022 } else
John McCallc3007a22010-10-26 07:05:15 +000013023 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013024
John McCall4adb38c2011-04-27 00:36:17 +000013025 ExprValueKind valueKind;
13026 QualType type;
13027 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13028 valueKind = VK_LValue;
13029 type = Fn->getType();
13030 } else {
13031 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013032 type = Context.BoundMemberTy;
13033 }
13034
13035 MemberExpr *ME = MemberExpr::Create(
13036 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13037 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13038 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13039 OK_Ordinary);
13040 ME->setHadMultipleCandidates(true);
13041 MarkMemberReferenced(ME);
13042 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013044
John McCallc3007a22010-10-26 07:05:15 +000013045 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013046}
13047
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013048ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013049 DeclAccessPair Found,
13050 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013051 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013052}