blob: ecd5bd2b99b764f8df1a34b82562713c2eee7eb7 [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) {
George Burgess IV21081362016-07-24 23:12:40 +000042 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000045}
46
Nick Lewycky134af912013-02-07 05:08:22 +000047/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000048static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000049CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000051 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000053 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000054 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000062 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000063 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000064 VK_LValue, Loc, LocInfo);
65 if (HadMultipleCandidates)
66 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000067
68 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000069 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
70 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000071}
72
John McCall5c32be02010-08-24 20:38:10 +000073static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
74 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000075 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000076 bool CStyle,
77 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000078
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000079static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
80 QualType &ToType,
81 bool InOverloadResolution,
82 StandardConversionSequence &SCS,
83 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000084static OverloadingResult
85IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
86 UserDefinedConversionSequence& User,
87 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000088 bool AllowExplicit,
89 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000090
91
92static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000093CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000094 const StandardConversionSequence& SCS1,
95 const StandardConversionSequence& SCS2);
96
97static ImplicitConversionSequence::CompareKind
98CompareQualificationConversions(Sema &S,
99 const StandardConversionSequence& SCS1,
100 const StandardConversionSequence& SCS2);
101
102static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000103CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000104 const StandardConversionSequence& SCS1,
105 const StandardConversionSequence& SCS2);
106
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107/// GetConversionRank - Retrieve the implicit conversion rank
108/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000109ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110 static const ImplicitConversionRank
111 Rank[(int)ICK_Num_Conversion_Kinds] = {
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000117 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000118 ICR_Promotion,
119 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000120 ICR_Promotion,
121 ICR_Conversion,
122 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000128 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000129 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000130 ICR_Conversion,
131 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000132 ICR_Complex_Real_Conversion,
133 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000134 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000135 ICR_Writeback_Conversion,
136 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
137 // it was omitted by the patch that added
138 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000139 ICR_C_Conversion,
140 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000141 };
142 return Rank[(int)Kind];
143}
144
145/// GetImplicitConversionName - Return the name of this kind of
146/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000147static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000148 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 "No conversion",
150 "Lvalue-to-rvalue",
151 "Array-to-pointer",
152 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000153 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 "Qualification",
155 "Integral promotion",
156 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000157 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "Integral conversion",
159 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000160 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 "Floating-integral conversion",
162 "Pointer conversion",
163 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000164 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000165 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000166 "Derived-to-base conversion",
167 "Vector conversion",
168 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000169 "Complex-real conversion",
170 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000171 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000172 "Writeback conversion",
173 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000174 "C specific type conversion",
175 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000176 };
177 return Name[Kind];
178}
179
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000180/// StandardConversionSequence - Set the standard conversion
181/// sequence to the identity conversion.
182void StandardConversionSequence::setAsIdentityConversion() {
183 First = ICK_Identity;
184 Second = ICK_Identity;
185 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000186 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000187 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000188 ReferenceBinding = false;
189 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000190 IsLvalueReference = true;
191 BindsToFunctionLvalue = false;
192 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000193 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000194 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000195 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000196}
197
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000198/// getRank - Retrieve the rank of this standard conversion sequence
199/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
200/// implicit conversions.
201ImplicitConversionRank StandardConversionSequence::getRank() const {
202 ImplicitConversionRank Rank = ICR_Exact_Match;
203 if (GetConversionRank(First) > Rank)
204 Rank = GetConversionRank(First);
205 if (GetConversionRank(Second) > Rank)
206 Rank = GetConversionRank(Second);
207 if (GetConversionRank(Third) > Rank)
208 Rank = GetConversionRank(Third);
209 return Rank;
210}
211
212/// isPointerConversionToBool - Determines whether this conversion is
213/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000214/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000215/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000216bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000217 // Note that FromType has not necessarily been transformed by the
218 // array-to-pointer or function-to-pointer implicit conversions, so
219 // check for their presence as well as checking whether FromType is
220 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000221 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000222 (getFromType()->isPointerType() ||
223 getFromType()->isObjCObjectPointerType() ||
224 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000225 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000226 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
227 return true;
228
229 return false;
230}
231
Douglas Gregor5c407d92008-10-23 00:40:37 +0000232/// isPointerConversionToVoidPointer - Determines whether this
233/// conversion is a conversion of a pointer to a void pointer. This is
234/// used as part of the ranking of standard conversion sequences (C++
235/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000236bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000237StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000238isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000239 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000240 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000241
242 // Note that FromType has not necessarily been transformed by the
243 // array-to-pointer implicit conversion, so check for its presence
244 // and redo the conversion to get a pointer.
245 if (First == ICK_Array_To_Pointer)
246 FromType = Context.getArrayDecayedType(FromType);
247
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000248 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000249 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000250 return ToPtrType->getPointeeType()->isVoidType();
251
252 return false;
253}
254
Richard Smith66e05fe2012-01-18 05:21:49 +0000255/// Skip any implicit casts which could be either part of a narrowing conversion
256/// or after one in an implicit conversion.
257static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
258 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
259 switch (ICE->getCastKind()) {
260 case CK_NoOp:
261 case CK_IntegralCast:
262 case CK_IntegralToBoolean:
263 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000264 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000265 case CK_FloatingToIntegral:
266 case CK_FloatingToBoolean:
267 case CK_FloatingCast:
268 Converted = ICE->getSubExpr();
269 continue;
270
271 default:
272 return Converted;
273 }
274 }
275
276 return Converted;
277}
278
279/// Check if this standard conversion sequence represents a narrowing
280/// conversion, according to C++11 [dcl.init.list]p7.
281///
282/// \param Ctx The AST context.
283/// \param Converted The result of applying this standard conversion sequence.
284/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
285/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000286/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
287/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000288NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000289StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
290 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000291 APValue &ConstantValue,
292 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000293 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000294
295 // C++11 [dcl.init.list]p7:
296 // A narrowing conversion is an implicit conversion ...
297 QualType FromType = getToType(0);
298 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000299
300 // A conversion to an enumeration type is narrowing if the conversion to
301 // the underlying type is narrowing. This only arises for expressions of
302 // the form 'Enum{init}'.
303 if (auto *ET = ToType->getAs<EnumType>())
304 ToType = ET->getDecl()->getIntegerType();
305
Richard Smith66e05fe2012-01-18 05:21:49 +0000306 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000307 // 'bool' is an integral type; dispatch to the right place to handle it.
308 case ICK_Boolean_Conversion:
309 if (FromType->isRealFloatingType())
310 goto FloatingIntegralConversion;
311 if (FromType->isIntegralOrUnscopedEnumerationType())
312 goto IntegralConversion;
313 // Boolean conversions can be from pointers and pointers to members
314 // [conv.bool], and those aren't considered narrowing conversions.
315 return NK_Not_Narrowing;
316
Richard Smith66e05fe2012-01-18 05:21:49 +0000317 // -- from a floating-point type to an integer type, or
318 //
319 // -- from an integer type or unscoped enumeration type to a floating-point
320 // type, except where the source is a constant expression and the actual
321 // value after conversion will fit into the target type and will produce
322 // the original value when converted back to the original type, or
323 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000324 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000325 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
326 return NK_Type_Narrowing;
327 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
328 llvm::APSInt IntConstantValue;
329 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
330 if (Initializer &&
331 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
332 // Convert the integer to the floating type.
333 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
334 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
335 llvm::APFloat::rmNearestTiesToEven);
336 // And back.
337 llvm::APSInt ConvertedValue = IntConstantValue;
338 bool ignored;
339 Result.convertToInteger(ConvertedValue,
340 llvm::APFloat::rmTowardZero, &ignored);
341 // If the resulting value is different, this was a narrowing conversion.
342 if (IntConstantValue != ConvertedValue) {
343 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000344 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000345 return NK_Constant_Narrowing;
346 }
347 } else {
348 // Variables are always narrowings.
349 return NK_Variable_Narrowing;
350 }
351 }
352 return NK_Not_Narrowing;
353
354 // -- from long double to double or float, or from double to float, except
355 // where the source is a constant expression and the actual value after
356 // conversion is within the range of values that can be represented (even
357 // if it cannot be represented exactly), or
358 case ICK_Floating_Conversion:
359 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
360 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
361 // FromType is larger than ToType.
362 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
363 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
364 // Constant!
365 assert(ConstantValue.isFloat());
366 llvm::APFloat FloatVal = ConstantValue.getFloat();
367 // Convert the source value into the target type.
368 bool ignored;
369 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
370 Ctx.getFloatTypeSemantics(ToType),
371 llvm::APFloat::rmNearestTiesToEven, &ignored);
372 // If there was no overflow, the source value is within the range of
373 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000374 if (ConvertStatus & llvm::APFloat::opOverflow) {
375 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000376 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000377 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000378 } else {
379 return NK_Variable_Narrowing;
380 }
381 }
382 return NK_Not_Narrowing;
383
384 // -- from an integer type or unscoped enumeration type to an integer type
385 // that cannot represent all the values of the original type, except where
386 // the source is a constant expression and the actual value after
387 // conversion will fit into the target type and will produce the original
388 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000389 case ICK_Integral_Conversion:
390 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 assert(FromType->isIntegralOrUnscopedEnumerationType());
392 assert(ToType->isIntegralOrUnscopedEnumerationType());
393 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
394 const unsigned FromWidth = Ctx.getIntWidth(FromType);
395 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
396 const unsigned ToWidth = Ctx.getIntWidth(ToType);
397
398 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000399 (FromWidth == ToWidth && FromSigned != ToSigned) ||
400 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000401 // Not all values of FromType can be represented in ToType.
402 llvm::APSInt InitializerValue;
403 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000404 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
405 // Such conversions on variables are always narrowing.
406 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000407 }
408 bool Narrowing = false;
409 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000410 // Negative -> unsigned is narrowing. Otherwise, more bits is never
411 // narrowing.
412 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000413 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000414 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000415 // Add a bit to the InitializerValue so we don't have to worry about
416 // signed vs. unsigned comparisons.
417 InitializerValue = InitializerValue.extend(
418 InitializerValue.getBitWidth() + 1);
419 // Convert the initializer to and from the target width and signed-ness.
420 llvm::APSInt ConvertedValue = InitializerValue;
421 ConvertedValue = ConvertedValue.trunc(ToWidth);
422 ConvertedValue.setIsSigned(ToSigned);
423 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
424 ConvertedValue.setIsSigned(InitializerValue.isSigned());
425 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000426 if (ConvertedValue != InitializerValue)
427 Narrowing = true;
428 }
429 if (Narrowing) {
430 ConstantType = Initializer->getType();
431 ConstantValue = APValue(InitializerValue);
432 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000433 }
434 }
435 return NK_Not_Narrowing;
436 }
437
438 default:
439 // Other kinds of conversions are not narrowings.
440 return NK_Not_Narrowing;
441 }
442}
443
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000444/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000445/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000446LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000447 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000448 bool PrintedSomething = false;
449 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 PrintedSomething = true;
452 }
453
454 if (Second != ICK_Identity) {
455 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000458 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000459
460 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000462 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000464 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000466 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467 PrintedSomething = true;
468 }
469
470 if (Third != ICK_Identity) {
471 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 PrintedSomething = true;
476 }
477
478 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
481}
482
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000483/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000488 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000491 if (ConversionFunction)
492 OS << '\'' << *ConversionFunction << '\'';
493 else
494 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000497 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 }
499}
500
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000501/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000505 if (isStdInitializerListElement())
506 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 switch (ConversionKind) {
508 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000510 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511 break;
512 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000513 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000514 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515 break;
516 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000517 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518 break;
John McCall0d1da222010-01-12 00:44:57 +0000519 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000520 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000521 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000522 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000523 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 break;
525 }
526
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000527 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528}
529
John McCall0d1da222010-01-12 00:44:57 +0000530void AmbiguousConversionSequence::construct() {
531 new (&conversions()) ConversionSet();
532}
533
534void AmbiguousConversionSequence::destruct() {
535 conversions().~ConversionSet();
536}
537
538void
539AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
540 FromTypePtr = O.FromTypePtr;
541 ToTypePtr = O.ToTypePtr;
542 new (&conversions()) ConversionSet(O.conversions());
543}
544
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000545namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000546 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000547 // template argument information.
548 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000549 TemplateArgument FirstArg;
550 TemplateArgument SecondArg;
551 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000552 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000553 // template parameter and template argument information.
554 struct DFIParamWithArguments : DFIArguments {
555 TemplateParameter Param;
556 };
Richard Smith9b534542015-12-31 02:02:54 +0000557 // Structure used by DeductionFailureInfo to store template argument
558 // information and the index of the problematic call argument.
559 struct DFIDeducedMismatchArgs : DFIArguments {
560 TemplateArgumentList *TemplateArgs;
561 unsigned CallArgIndex;
562 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000563}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565/// \brief Convert from Sema's representation of template deduction information
566/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000567DeductionFailureInfo
568clang::MakeDeductionFailureInfo(ASTContext &Context,
569 Sema::TemplateDeductionResult TDK,
570 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000571 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000573 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 switch (TDK) {
575 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000576 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000577 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000578 case Sema::TDK_TooManyArguments:
579 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000580 case Sema::TDK_MiscellaneousDeductionFailure:
581 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000582 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000585 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000586 Result.Data = Info.Param.getOpaqueValue();
587 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588
Richard Smith9b534542015-12-31 02:02:54 +0000589 case Sema::TDK_DeducedMismatch: {
590 // FIXME: Should allocate from normal heap so that we can free this later.
591 auto *Saved = new (Context) DFIDeducedMismatchArgs;
592 Saved->FirstArg = Info.FirstArg;
593 Saved->SecondArg = Info.SecondArg;
594 Saved->TemplateArgs = Info.take();
595 Saved->CallArgIndex = Info.CallArgIndex;
596 Result.Data = Saved;
597 break;
598 }
599
Richard Smith44ecdbd2013-01-31 05:19:49 +0000600 case Sema::TDK_NonDeducedMismatch: {
601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIArguments *Saved = new (Context) DFIArguments;
603 Saved->FirstArg = Info.FirstArg;
604 Saved->SecondArg = Info.SecondArg;
605 Result.Data = Saved;
606 break;
607 }
608
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000610 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000611 // FIXME: Should allocate from normal heap so that we can free this later.
612 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613 Saved->Param = Info.Param;
614 Saved->FirstArg = Info.FirstArg;
615 Saved->SecondArg = Info.SecondArg;
616 Result.Data = Saved;
617 break;
618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000621 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000622 if (Info.hasSFINAEDiagnostic()) {
623 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
624 SourceLocation(), PartialDiagnostic::NullDiagnostic());
625 Info.takeSFINAEDiagnostic(*Diag);
626 Result.HasDiagnostic = true;
627 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000628 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000629
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000630 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000631 Result.Data = Info.Expression;
632 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 return Result;
636}
John McCall0d1da222010-01-12 00:44:57 +0000637
Larisse Voufo98b20f12013-07-19 23:00:19 +0000638void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
640 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000641 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000642 case Sema::TDK_InstantiationDepth:
643 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000644 case Sema::TDK_TooManyArguments:
645 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000646 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000647 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000650 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000651 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000652 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000653 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000654 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000655 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000656 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000657
658 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000659 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000660 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000661 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
662 Diag->~PartialDiagnosticAt();
663 HasDiagnostic = false;
664 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Douglas Gregor461761d2010-05-08 18:20:53 +0000667 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000668 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 break;
670 }
671}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Larisse Voufo98b20f12013-07-19 23:00:19 +0000673PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000674 if (HasDiagnostic)
675 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000677}
678
Larisse Voufo98b20f12013-07-19 23:00:19 +0000679TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
681 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000682 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000683 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000684 case Sema::TDK_TooManyArguments:
685 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000686 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000687 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000688 case Sema::TDK_NonDeducedMismatch:
689 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000693 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000695
696 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000697 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000698 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000701 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 break;
703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705 return TemplateParameter();
706}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707
Larisse Voufo98b20f12013-07-19 23:00:19 +0000708TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000709 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000710 case Sema::TDK_Success:
711 case Sema::TDK_Invalid:
712 case Sema::TDK_InstantiationDepth:
713 case Sema::TDK_TooManyArguments:
714 case Sema::TDK_TooFewArguments:
715 case Sema::TDK_Incomplete:
716 case Sema::TDK_InvalidExplicitArguments:
717 case Sema::TDK_Inconsistent:
718 case Sema::TDK_Underqualified:
719 case Sema::TDK_NonDeducedMismatch:
720 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000721 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000722
Richard Smith9b534542015-12-31 02:02:54 +0000723 case Sema::TDK_DeducedMismatch:
724 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
725
Richard Smith44ecdbd2013-01-31 05:19:49 +0000726 case Sema::TDK_SubstitutionFailure:
727 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
Richard Smith44ecdbd2013-01-31 05:19:49 +0000729 // Unhandled
730 case Sema::TDK_MiscellaneousDeductionFailure:
731 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000732 }
733
Craig Topperc3ec1492014-05-26 06:22:03 +0000734 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000735}
736
Larisse Voufo98b20f12013-07-19 23:00:19 +0000737const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
739 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000740 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000741 case Sema::TDK_InstantiationDepth:
742 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 case Sema::TDK_TooManyArguments:
744 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000745 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000746 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000748 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000749
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000750 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000751 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000752 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000753 case Sema::TDK_NonDeducedMismatch:
754 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755
Douglas Gregor461761d2010-05-08 18:20:53 +0000756 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000757 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000758 break;
759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760
Craig Topperc3ec1492014-05-26 06:22:03 +0000761 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000763
Larisse Voufo98b20f12013-07-19 23:00:19 +0000764const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000765 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
766 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000767 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000768 case Sema::TDK_InstantiationDepth:
769 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000770 case Sema::TDK_TooManyArguments:
771 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000772 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000773 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000774 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000775 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000777 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000778 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000779 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000782
Douglas Gregor461761d2010-05-08 18:20:53 +0000783 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000784 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000785 break;
786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Craig Topperc3ec1492014-05-26 06:22:03 +0000788 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000789}
790
Larisse Voufo98b20f12013-07-19 23:00:19 +0000791Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000792 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
793 Sema::TDK_FailedOverloadResolution)
794 return static_cast<Expr*>(Data);
795
Craig Topperc3ec1492014-05-26 06:22:03 +0000796 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000797}
798
Richard Smith9b534542015-12-31 02:02:54 +0000799llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
800 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
801 Sema::TDK_DeducedMismatch)
802 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
803
804 return llvm::None;
805}
806
Benjamin Kramer97e59492012-10-09 15:52:25 +0000807void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000808 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000809 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
810 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000811 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
812 i->DeductionFailure.Destroy();
813 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000814}
815
816void OverloadCandidateSet::clear() {
817 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000818 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000819 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000820 Functions.clear();
821}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822
John McCall4124c492011-10-17 18:40:02 +0000823namespace {
824 class UnbridgedCastsSet {
825 struct Entry {
826 Expr **Addr;
827 Expr *Saved;
828 };
829 SmallVector<Entry, 2> Entries;
830
831 public:
832 void save(Sema &S, Expr *&E) {
833 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
834 Entry entry = { &E, E };
835 Entries.push_back(entry);
836 E = S.stripARCUnbridgedCast(E);
837 }
838
839 void restore() {
840 for (SmallVectorImpl<Entry>::iterator
841 i = Entries.begin(), e = Entries.end(); i != e; ++i)
842 *i->Addr = i->Saved;
843 }
844 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000845}
John McCall4124c492011-10-17 18:40:02 +0000846
847/// checkPlaceholderForOverload - Do any interesting placeholder-like
848/// preprocessing on the given expression.
849///
850/// \param unbridgedCasts a collection to which to add unbridged casts;
851/// without this, they will be immediately diagnosed as errors
852///
853/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000854static bool
855checkPlaceholderForOverload(Sema &S, Expr *&E,
856 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000857 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
858 // We can't handle overloaded expressions here because overload
859 // resolution might reasonably tweak them.
860 if (placeholder->getKind() == BuiltinType::Overload) return false;
861
862 // If the context potentially accepts unbridged ARC casts, strip
863 // the unbridged cast and add it to the collection for later restoration.
864 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
865 unbridgedCasts) {
866 unbridgedCasts->save(S, E);
867 return false;
868 }
869
870 // Go ahead and check everything else.
871 ExprResult result = S.CheckPlaceholderExpr(E);
872 if (result.isInvalid())
873 return true;
874
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000875 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000876 return false;
877 }
878
879 // Nothing to do.
880 return false;
881}
882
883/// checkArgPlaceholdersForOverload - Check a set of call operands for
884/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000885static bool checkArgPlaceholdersForOverload(Sema &S,
886 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000887 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000888 for (unsigned i = 0, e = Args.size(); i != e; ++i)
889 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000890 return true;
891
892 return false;
893}
894
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000896// overload of the declarations in Old. This routine returns false if
897// New and Old cannot be overloaded, e.g., if New has the same
898// signature as some function in Old (C++ 1.3.10) or if the Old
899// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000900// it does return false, MatchedDecl will point to the decl that New
901// cannot be overloaded with. This decl may be a UsingShadowDecl on
902// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000903//
904// Example: Given the following input:
905//
906// void f(int, float); // #1
907// void f(int, int); // #2
908// int f(int, int); // #3
909//
910// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000911// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912//
John McCall3d988d92009-12-02 08:47:38 +0000913// When we process #2, Old contains only the FunctionDecl for #1. By
914// comparing the parameter types, we see that #1 and #2 are overloaded
915// (since they have different signatures), so this routine returns
916// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000917//
John McCall3d988d92009-12-02 08:47:38 +0000918// When we process #3, Old is an overload set containing #1 and #2. We
919// compare the signatures of #3 to #1 (they're overloaded, so we do
920// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
921// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000922// signature), IsOverload returns false and MatchedDecl will be set to
923// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000924//
925// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
926// into a class by a using declaration. The rules for whether to hide
927// shadow declarations ignore some properties which otherwise figure
928// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000929Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000930Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
931 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000932 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000933 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000934 NamedDecl *OldD = *I;
935
936 bool OldIsUsingDecl = false;
937 if (isa<UsingShadowDecl>(OldD)) {
938 OldIsUsingDecl = true;
939
940 // We can always introduce two using declarations into the same
941 // context, even if they have identical signatures.
942 if (NewIsUsingDecl) continue;
943
944 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
945 }
946
Richard Smithf091e122015-09-15 01:28:55 +0000947 // A using-declaration does not conflict with another declaration
948 // if one of them is hidden.
949 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
950 continue;
951
John McCalle9cccd82010-06-16 08:42:20 +0000952 // If either declaration was introduced by a using declaration,
953 // we'll need to use slightly different rules for matching.
954 // Essentially, these rules are the normal rules, except that
955 // function templates hide function templates with different
956 // return types or template parameter lists.
957 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000958 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
959 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000960
Alp Tokera2794f92014-01-22 07:29:52 +0000961 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000962 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
963 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
964 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
965 continue;
966 }
967
Alp Tokera2794f92014-01-22 07:29:52 +0000968 if (!isa<FunctionTemplateDecl>(OldD) &&
969 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000970 continue;
971
John McCalldaa3d6b2009-12-09 03:35:25 +0000972 Match = *I;
973 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000974 }
John McCalla8987a2942010-11-10 03:01:53 +0000975 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000976 // We can overload with these, which can show up when doing
977 // redeclaration checks for UsingDecls.
978 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000979 } else if (isa<TagDecl>(OldD)) {
980 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000981 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
982 // Optimistically assume that an unresolved using decl will
983 // overload; if it doesn't, we'll have to diagnose during
984 // template instantiation.
985 } else {
John McCall1f82f242009-11-18 22:49:29 +0000986 // (C++ 13p1):
987 // Only function declarations can be overloaded; object and type
988 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000989 Match = *I;
990 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000991 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000992 }
John McCall1f82f242009-11-18 22:49:29 +0000993
John McCalldaa3d6b2009-12-09 03:35:25 +0000994 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000995}
996
Richard Smithac974a32013-06-30 09:48:50 +0000997bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +0000998 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +0000999 // C++ [basic.start.main]p2: This function shall not be overloaded.
1000 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001001 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001002
David Majnemerc729b0b2013-09-16 22:44:20 +00001003 // MSVCRT user defined entry points cannot be overloaded.
1004 if (New->isMSVCRTEntryPoint())
1005 return false;
1006
John McCall1f82f242009-11-18 22:49:29 +00001007 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1008 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1009
1010 // C++ [temp.fct]p2:
1011 // A function template can be overloaded with other function templates
1012 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001013 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001014 return true;
1015
1016 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001017 QualType OldQType = Context.getCanonicalType(Old->getType());
1018 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001019
1020 // Compare the signatures (C++ 1.3.10) of the two functions to
1021 // determine whether they are overloads. If we find any mismatch
1022 // in the signature, they are overloads.
1023
1024 // If either of these functions is a K&R-style function (no
1025 // prototype), then we consider them to have matching signatures.
1026 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1027 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1028 return false;
1029
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001030 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1031 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001032
1033 // The signature of a function includes the types of its
1034 // parameters (C++ 1.3.10), which includes the presence or absence
1035 // of the ellipsis; see C++ DR 357).
1036 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001037 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001038 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001039 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001040 return true;
1041
1042 // C++ [temp.over.link]p4:
1043 // The signature of a function template consists of its function
1044 // signature, its return type and its template parameter list. The names
1045 // of the template parameters are significant only for establishing the
1046 // relationship between the template parameters and the rest of the
1047 // signature.
1048 //
1049 // We check the return type and template parameter lists for function
1050 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001051 //
1052 // However, we don't consider either of these when deciding whether
1053 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001054 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001055 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1056 OldTemplate->getTemplateParameters(),
1057 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001058 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001059 return true;
1060
1061 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001062 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001063 //
1064 // As part of this, also check whether one of the member functions
1065 // is static, in which case they are not overloads (C++
1066 // 13.1p2). While not part of the definition of the signature,
1067 // this check is important to determine whether these functions
1068 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001069 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1070 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001071 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001072 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1073 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001074 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001075 (OldMethod->getRefQualifier() == RQ_None ||
1076 NewMethod->getRefQualifier() == RQ_None)) {
1077 // C++0x [over.load]p2:
1078 // - Member function declarations with the same name and the same
1079 // parameter-type-list as well as member function template
1080 // declarations with the same name, the same parameter-type-list, and
1081 // the same template parameter lists cannot be overloaded if any of
1082 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001083 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001084 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001085 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001086 }
1087 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001089
Richard Smith574f4f62013-01-14 05:37:29 +00001090 // We may not have applied the implicit const for a constexpr member
1091 // function yet (because we haven't yet resolved whether this is a static
1092 // or non-static member function). Add it now, on the assumption that this
1093 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001094 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001095 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001096 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001097 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001098 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001099
1100 // We do not allow overloading based off of '__restrict'.
1101 OldQuals &= ~Qualifiers::Restrict;
1102 NewQuals &= ~Qualifiers::Restrict;
1103 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001104 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001106
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001107 // Though pass_object_size is placed on parameters and takes an argument, we
1108 // consider it to be a function-level modifier for the sake of function
1109 // identity. Either the function has one or more parameters with
1110 // pass_object_size or it doesn't.
1111 if (functionHasPassObjectSizeParams(New) !=
1112 functionHasPassObjectSizeParams(Old))
1113 return true;
1114
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001115 // enable_if attributes are an order-sensitive part of the signature.
1116 for (specific_attr_iterator<EnableIfAttr>
1117 NewI = New->specific_attr_begin<EnableIfAttr>(),
1118 NewE = New->specific_attr_end<EnableIfAttr>(),
1119 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1120 OldE = Old->specific_attr_end<EnableIfAttr>();
1121 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1122 if (NewI == NewE || OldI == OldE)
1123 return true;
1124 llvm::FoldingSetNodeID NewID, OldID;
1125 NewI->getCond()->Profile(NewID, Context, true);
1126 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001127 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001128 return true;
1129 }
1130
Justin Lebarba122ab2016-03-30 23:30:21 +00001131 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001132 // Don't allow overloading of destructors. (In theory we could, but it
1133 // would be a giant change to clang.)
1134 if (isa<CXXDestructorDecl>(New))
1135 return false;
1136
Artem Belevich94a55e82015-09-22 17:22:59 +00001137 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1138 OldTarget = IdentifyCUDATarget(Old);
1139 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1140 return false;
1141
1142 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1143
1144 // Don't allow mixing of HD with other kinds. This guarantees that
1145 // we have only one viable function with this signature on any
1146 // side of CUDA compilation .
Artem Belevich1ef9b592016-02-24 21:54:45 +00001147 // __global__ functions can't be overloaded based on attribute
1148 // difference because, like HD, they also exist on both sides.
1149 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1150 (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
Artem Belevich94a55e82015-09-22 17:22:59 +00001151 return false;
1152
1153 // Allow overloading of functions with same signature, but
1154 // different CUDA target attributes.
1155 return NewTarget != OldTarget;
1156 }
1157
John McCall1f82f242009-11-18 22:49:29 +00001158 // The signatures match; this is not an overload.
1159 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001160}
1161
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001162/// \brief Checks availability of the function depending on the current
1163/// function context. Inside an unavailable function, unavailability is ignored.
1164///
1165/// \returns true if \arg FD is unavailable and current context is inside
1166/// an available function, false otherwise.
1167bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001168 if (!FD->isUnavailable())
1169 return false;
1170
1171 // Walk up the context of the caller.
1172 Decl *C = cast<Decl>(CurContext);
1173 do {
1174 if (C->isUnavailable())
1175 return false;
1176 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1177 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001178}
1179
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001180/// \brief Tries a user-defined conversion from From to ToType.
1181///
1182/// Produces an implicit conversion sequence for when a standard conversion
1183/// is not an option. See TryImplicitConversion for more information.
1184static ImplicitConversionSequence
1185TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1186 bool SuppressUserConversions,
1187 bool AllowExplicit,
1188 bool InOverloadResolution,
1189 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001190 bool AllowObjCWritebackConversion,
1191 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001192 ImplicitConversionSequence ICS;
1193
1194 if (SuppressUserConversions) {
1195 // We're not in the case above, so there is no conversion that
1196 // we can perform.
1197 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1198 return ICS;
1199 }
1200
1201 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001202 OverloadCandidateSet Conversions(From->getExprLoc(),
1203 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001204 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1205 Conversions, AllowExplicit,
1206 AllowObjCConversionOnExplicit)) {
1207 case OR_Success:
1208 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001209 ICS.setUserDefined();
1210 // C++ [over.ics.user]p4:
1211 // A conversion of an expression of class type to the same class
1212 // type is given Exact Match rank, and a conversion of an
1213 // expression of class type to a base class of that type is
1214 // given Conversion rank, in spite of the fact that a copy
1215 // constructor (i.e., a user-defined conversion function) is
1216 // called for those cases.
1217 if (CXXConstructorDecl *Constructor
1218 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1219 QualType FromCanon
1220 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1221 QualType ToCanon
1222 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1223 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001224 (FromCanon == ToCanon ||
1225 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001226 // Turn this into a "standard" conversion sequence, so that it
1227 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001228 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001229 ICS.setStandard();
1230 ICS.Standard.setAsIdentityConversion();
1231 ICS.Standard.setFromType(From->getType());
1232 ICS.Standard.setAllToTypes(ToType);
1233 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001234 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001235 if (ToCanon != FromCanon)
1236 ICS.Standard.Second = ICK_Derived_To_Base;
1237 }
1238 }
Richard Smith48372b62015-01-27 03:30:40 +00001239 break;
1240
1241 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001242 ICS.setAmbiguous();
1243 ICS.Ambiguous.setFromType(From->getType());
1244 ICS.Ambiguous.setToType(ToType);
1245 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1246 Cand != Conversions.end(); ++Cand)
1247 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001248 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001249 break;
Richard Smith48372b62015-01-27 03:30:40 +00001250
1251 // Fall through.
1252 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001253 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001254 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001255 }
1256
1257 return ICS;
1258}
1259
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001260/// TryImplicitConversion - Attempt to perform an implicit conversion
1261/// from the given expression (Expr) to the given type (ToType). This
1262/// function returns an implicit conversion sequence that can be used
1263/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001264///
1265/// void f(float f);
1266/// void g(int i) { f(i); }
1267///
1268/// this routine would produce an implicit conversion sequence to
1269/// describe the initialization of f from i, which will be a standard
1270/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1271/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1272//
1273/// Note that this routine only determines how the conversion can be
1274/// performed; it does not actually perform the conversion. As such,
1275/// it will not produce any diagnostics if no conversion is available,
1276/// but will instead return an implicit conversion sequence of kind
1277/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001278///
1279/// If @p SuppressUserConversions, then user-defined conversions are
1280/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001281/// If @p AllowExplicit, then explicit user-defined conversions are
1282/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001283///
1284/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1285/// writeback conversion, which allows __autoreleasing id* parameters to
1286/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001287static ImplicitConversionSequence
1288TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1289 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001290 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001291 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001292 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001293 bool AllowObjCWritebackConversion,
1294 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001295 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001296 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001297 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001298 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001299 return ICS;
1300 }
1301
David Blaikiebbafb8a2012-03-11 07:00:24 +00001302 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001303 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001304 return ICS;
1305 }
1306
Douglas Gregor836a7e82010-08-11 02:15:33 +00001307 // C++ [over.ics.user]p4:
1308 // A conversion of an expression of class type to the same class
1309 // type is given Exact Match rank, and a conversion of an
1310 // expression of class type to a base class of that type is
1311 // given Conversion rank, in spite of the fact that a copy/move
1312 // constructor (i.e., a user-defined conversion function) is
1313 // called for those cases.
1314 QualType FromType = From->getType();
1315 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001316 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001317 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001318 ICS.setStandard();
1319 ICS.Standard.setAsIdentityConversion();
1320 ICS.Standard.setFromType(FromType);
1321 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001322
Douglas Gregor5ab11652010-04-17 22:01:05 +00001323 // We don't actually check at this point whether there is a valid
1324 // copy/move constructor, since overloading just assumes that it
1325 // exists. When we actually perform initialization, we'll find the
1326 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001327 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
Douglas Gregor5ab11652010-04-17 22:01:05 +00001329 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001330 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001331 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332
Douglas Gregor836a7e82010-08-11 02:15:33 +00001333 return ICS;
1334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001336 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1337 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001338 AllowObjCWritebackConversion,
1339 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001340}
1341
John McCall31168b02011-06-15 23:02:42 +00001342ImplicitConversionSequence
1343Sema::TryImplicitConversion(Expr *From, QualType ToType,
1344 bool SuppressUserConversions,
1345 bool AllowExplicit,
1346 bool InOverloadResolution,
1347 bool CStyle,
1348 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001349 return ::TryImplicitConversion(*this, From, ToType,
1350 SuppressUserConversions, AllowExplicit,
1351 InOverloadResolution, CStyle,
1352 AllowObjCWritebackConversion,
1353 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001354}
1355
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001356/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001357/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001358/// converted expression. Flavor is the kind of conversion we're
1359/// performing, used in the error message. If @p AllowExplicit,
1360/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001361ExprResult
1362Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001363 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001364 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001365 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001366}
1367
John Wiegley01296292011-04-08 18:41:53 +00001368ExprResult
1369Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001370 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001371 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001372 if (checkPlaceholderForOverload(*this, From))
1373 return ExprError();
1374
John McCall31168b02011-06-15 23:02:42 +00001375 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1376 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001377 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001378 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001379 if (getLangOpts().ObjC1)
1380 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1381 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001382 ICS = ::TryImplicitConversion(*this, From, ToType,
1383 /*SuppressUserConversions=*/false,
1384 AllowExplicit,
1385 /*InOverloadResolution=*/false,
1386 /*CStyle=*/false,
1387 AllowObjCWritebackConversion,
1388 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001389 return PerformImplicitConversion(From, ToType, ICS, Action);
1390}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391
1392/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001393/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001394bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1395 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001396 if (Context.hasSameUnqualifiedType(FromType, ToType))
1397 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001398
John McCall991eb4b2010-12-21 00:44:39 +00001399 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1400 // where F adds one of the following at most once:
1401 // - a pointer
1402 // - a member pointer
1403 // - a block pointer
1404 CanQualType CanTo = Context.getCanonicalType(ToType);
1405 CanQualType CanFrom = Context.getCanonicalType(FromType);
1406 Type::TypeClass TyClass = CanTo->getTypeClass();
1407 if (TyClass != CanFrom->getTypeClass()) return false;
1408 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1409 if (TyClass == Type::Pointer) {
1410 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1411 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1412 } else if (TyClass == Type::BlockPointer) {
1413 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1414 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1415 } else if (TyClass == Type::MemberPointer) {
1416 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1417 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1418 } else {
1419 return false;
1420 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001421
John McCall991eb4b2010-12-21 00:44:39 +00001422 TyClass = CanTo->getTypeClass();
1423 if (TyClass != CanFrom->getTypeClass()) return false;
1424 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1425 return false;
1426 }
1427
1428 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1429 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1430 if (!EInfo.getNoReturn()) return false;
1431
1432 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1433 assert(QualType(FromFn, 0).isCanonical());
1434 if (QualType(FromFn, 0) != CanTo) return false;
1435
1436 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001437 return true;
1438}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001439
Douglas Gregor46188682010-05-18 22:42:18 +00001440/// \brief Determine whether the conversion from FromType to ToType is a valid
1441/// vector conversion.
1442///
1443/// \param ICK Will be set to the vector conversion kind, if this is a vector
1444/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001445static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001447 // We need at least one of these types to be a vector type to have a vector
1448 // conversion.
1449 if (!ToType->isVectorType() && !FromType->isVectorType())
1450 return false;
1451
1452 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001453 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001454 return false;
1455
1456 // There are no conversions between extended vector types, only identity.
1457 if (ToType->isExtVectorType()) {
1458 // There are no conversions between extended vector types other than the
1459 // identity conversion.
1460 if (FromType->isExtVectorType())
1461 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462
Douglas Gregor46188682010-05-18 22:42:18 +00001463 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001464 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001465 ICK = ICK_Vector_Splat;
1466 return true;
1467 }
1468 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001469
1470 // We can perform the conversion between vector types in the following cases:
1471 // 1)vector types are equivalent AltiVec and GCC vector types
1472 // 2)lax vector conversions are permitted and the vector types are of the
1473 // same size
1474 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001475 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1476 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001477 ICK = ICK_Vector_Conversion;
1478 return true;
1479 }
Douglas Gregor46188682010-05-18 22:42:18 +00001480 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001481
Douglas Gregor46188682010-05-18 22:42:18 +00001482 return false;
1483}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001485static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1486 bool InOverloadResolution,
1487 StandardConversionSequence &SCS,
1488 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001489
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001490/// IsStandardConversion - Determines whether there is a standard
1491/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1492/// expression From to the type ToType. Standard conversion sequences
1493/// only consider non-class types; for conversions that involve class
1494/// types, use TryImplicitConversion. If a conversion exists, SCS will
1495/// contain the standard conversion sequence required to perform this
1496/// conversion and this routine will return true. Otherwise, this
1497/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001498static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1499 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001500 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001501 bool CStyle,
1502 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001503 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001504
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001505 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001506 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001507 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001508 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001509 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001510
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001511 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001512 // abort early. When overloading in C, however, we do permit them.
1513 if (S.getLangOpts().CPlusPlus &&
1514 (FromType->isRecordType() || ToType->isRecordType()))
1515 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001516
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001517 // The first conversion can be an lvalue-to-rvalue conversion,
1518 // array-to-pointer conversion, or function-to-pointer conversion
1519 // (C++ 4p1).
1520
John McCall5c32be02010-08-24 20:38:10 +00001521 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001522 DeclAccessPair AccessPair;
1523 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001525 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001526 // We were able to resolve the address of the overloaded function,
1527 // so we can convert to the type of that function.
1528 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001529 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001530
1531 // we can sometimes resolve &foo<int> regardless of ToType, so check
1532 // if the type matches (identity) or we are converting to bool
1533 if (!S.Context.hasSameUnqualifiedType(
1534 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1535 QualType resultTy;
1536 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001537 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001538 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1539 // otherwise, only a boolean conversion is standard
1540 if (!ToType->isBooleanType())
1541 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543
Chandler Carruthffce2452011-03-29 08:08:18 +00001544 // Check if the "from" expression is taking the address of an overloaded
1545 // function and recompute the FromType accordingly. Take advantage of the
1546 // fact that non-static member functions *must* have such an address-of
1547 // expression.
1548 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1549 if (Method && !Method->isStatic()) {
1550 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1551 "Non-unary operator on non-static member address");
1552 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1553 == UO_AddrOf &&
1554 "Non-address-of operator on non-static member address");
1555 const Type *ClassType
1556 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1557 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001558 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1559 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1560 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001561 "Non-address-of operator for overloaded function expression");
1562 FromType = S.Context.getPointerType(FromType);
1563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
Douglas Gregor980fb162010-04-29 18:24:40 +00001565 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001566 assert(S.Context.hasSameType(
1567 FromType,
1568 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001569 } else {
1570 return false;
1571 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001572 }
John McCall154a2fd2011-08-30 00:57:29 +00001573 // Lvalue-to-rvalue conversion (C++11 4.1):
1574 // A glvalue (3.10) of a non-function, non-array type T can
1575 // be converted to a prvalue.
1576 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001577 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001578 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001579 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001580 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581
Douglas Gregorc79862f2012-04-12 17:51:55 +00001582 // C11 6.3.2.1p2:
1583 // ... if the lvalue has atomic type, the value has the non-atomic version
1584 // of the type of the lvalue ...
1585 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1586 FromType = Atomic->getValueType();
1587
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001588 // If T is a non-class type, the type of the rvalue is the
1589 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001590 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1591 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001592 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001593 } else if (FromType->isArrayType()) {
1594 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001595 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001596
1597 // An lvalue or rvalue of type "array of N T" or "array of unknown
1598 // bound of T" can be converted to an rvalue of type "pointer to
1599 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001600 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001601
John McCall5c32be02010-08-24 20:38:10 +00001602 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001603 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001604 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001605
1606 // For the purpose of ranking in overload resolution
1607 // (13.3.3.1.1), this conversion is considered an
1608 // array-to-pointer conversion followed by a qualification
1609 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001610 SCS.Second = ICK_Identity;
1611 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001612 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001613 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001614 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615 }
John McCall086a4642010-11-24 05:12:34 +00001616 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001617 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001618 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001620 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1621 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1622 if (!S.checkAddressOfFunctionIsAvailable(FD))
1623 return false;
1624
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001625 // An lvalue of function type T can be converted to an rvalue of
1626 // type "pointer to T." The result is a pointer to the
1627 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001628 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001629 } else {
1630 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001631 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001632 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001633 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001634
1635 // The second conversion can be an integral promotion, floating
1636 // point promotion, integral conversion, floating point conversion,
1637 // floating-integral conversion, pointer conversion,
1638 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001639 // For overloading in C, this can also be a "compatible-type"
1640 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001641 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001642 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001643 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001644 // The unqualified versions of the types are the same: there's no
1645 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001646 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001647 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001648 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001649 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001650 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001651 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001652 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001653 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001654 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001655 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001656 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001657 SCS.Second = ICK_Complex_Promotion;
1658 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001659 } else if (ToType->isBooleanType() &&
1660 (FromType->isArithmeticType() ||
1661 FromType->isAnyPointerType() ||
1662 FromType->isBlockPointerType() ||
1663 FromType->isMemberPointerType() ||
1664 FromType->isNullPtrType())) {
1665 // Boolean conversions (C++ 4.12).
1666 SCS.Second = ICK_Boolean_Conversion;
1667 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001668 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001669 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001670 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001671 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001673 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001674 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001675 SCS.Second = ICK_Complex_Conversion;
1676 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001677 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1678 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001679 // Complex-real conversions (C99 6.3.1.7)
1680 SCS.Second = ICK_Complex_Real;
1681 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001682 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001683 // FIXME: disable conversions between long double and __float128 if
1684 // their representation is different until there is back end support
1685 // We of course allow this conversion if long double is really double.
1686 if (&S.Context.getFloatTypeSemantics(FromType) !=
1687 &S.Context.getFloatTypeSemantics(ToType)) {
1688 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1689 ToType == S.Context.LongDoubleTy) ||
1690 (FromType == S.Context.LongDoubleTy &&
1691 ToType == S.Context.Float128Ty));
1692 if (Float128AndLongDouble &&
1693 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1694 &llvm::APFloat::IEEEdouble))
1695 return false;
1696 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001697 // Floating point conversions (C++ 4.8).
1698 SCS.Second = ICK_Floating_Conversion;
1699 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001700 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001701 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001702 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001703 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001704 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001705 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001707 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001708 SCS.Second = ICK_Block_Pointer_Conversion;
1709 } else if (AllowObjCWritebackConversion &&
1710 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1711 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001712 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1713 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001714 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001715 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001716 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001717 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001718 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001719 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001720 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001721 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001722 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001723 SCS.Second = SecondICK;
1724 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001725 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001726 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001727 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001728 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001729 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001730 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001731 // Treat a conversion that strips "noreturn" as an identity conversion.
1732 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001733 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1734 InOverloadResolution,
1735 SCS, CStyle)) {
1736 SCS.Second = ICK_TransparentUnionConversion;
1737 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001738 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1739 CStyle)) {
1740 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001741 // appropriately.
1742 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001743 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001744 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001745 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001746 SCS.Second = ICK_Zero_Event_Conversion;
1747 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 } else {
1749 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001750 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001751 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001752 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001753
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001754 QualType CanonFrom;
1755 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001756 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001757 bool ObjCLifetimeConversion;
1758 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1759 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001760 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001761 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001762 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001763 CanonFrom = S.Context.getCanonicalType(FromType);
1764 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001765 } else {
1766 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001767 SCS.Third = ICK_Identity;
1768
Mike Stump11289f42009-09-09 15:08:12 +00001769 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001770 // [...] Any difference in top-level cv-qualification is
1771 // subsumed by the initialization itself and does not constitute
1772 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001773 CanonFrom = S.Context.getCanonicalType(FromType);
1774 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001775 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001776 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001777 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001778 FromType = ToType;
1779 CanonFrom = CanonTo;
1780 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001782 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001783
George Burgess IV45461812015-10-11 20:13:20 +00001784 if (CanonFrom == CanonTo)
1785 return true;
1786
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001788 // this is a bad conversion sequence, unless we're resolving an overload in C.
1789 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001790 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001791
George Burgess IV45461812015-10-11 20:13:20 +00001792 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001793 Sema::AssignConvertType Conv =
1794 S.CheckSingleAssignmentConstraints(ToType, ER,
1795 /*Diagnose=*/false,
1796 /*DiagnoseCFAudited=*/false,
1797 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001798 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001799 switch (Conv) {
1800 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001801 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001802 break;
1803 // For our purposes, discarding qualifiers is just as bad as using an
1804 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1805 // qualifiers, as well.
1806 case Sema::CompatiblePointerDiscardsQualifiers:
1807 case Sema::IncompatiblePointer:
1808 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001809 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001810 break;
1811 default:
George Burgess IV45461812015-10-11 20:13:20 +00001812 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001813 }
George Burgess IV45461812015-10-11 20:13:20 +00001814
George Burgess IV6098fd12016-09-03 00:28:25 +00001815 // First can only be an lvalue conversion, so we pretend that this was the
1816 // second conversion. First should already be valid from earlier in the
1817 // function.
1818 SCS.Second = SecondConv;
1819 SCS.setToType(1, ToType);
1820
1821 // Third is Identity, because Second should rank us worse than any other
1822 // conversion. This could also be ICK_Qualification, but it's simpler to just
1823 // lump everything in with the second conversion, and we don't gain anything
1824 // from making this ICK_Qualification.
1825 SCS.Third = ICK_Identity;
1826 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001827 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001828}
George Burgess IV2099b542016-09-02 22:59:57 +00001829
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001830static bool
1831IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1832 QualType &ToType,
1833 bool InOverloadResolution,
1834 StandardConversionSequence &SCS,
1835 bool CStyle) {
1836
1837 const RecordType *UT = ToType->getAsUnionType();
1838 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1839 return false;
1840 // The field to initialize within the transparent union.
1841 RecordDecl *UD = UT->getDecl();
1842 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001843 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001844 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1845 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001846 ToType = it->getType();
1847 return true;
1848 }
1849 }
1850 return false;
1851}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001852
1853/// IsIntegralPromotion - Determines whether the conversion from the
1854/// expression From (whose potentially-adjusted type is FromType) to
1855/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1856/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001857bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001858 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001859 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001860 if (!To) {
1861 return false;
1862 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001863
1864 // An rvalue of type char, signed char, unsigned char, short int, or
1865 // unsigned short int can be converted to an rvalue of type int if
1866 // int can represent all the values of the source type; otherwise,
1867 // the source rvalue can be converted to an rvalue of type unsigned
1868 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001869 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1870 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001871 if (// We can promote any signed, promotable integer type to an int
1872 (FromType->isSignedIntegerType() ||
1873 // We can promote any unsigned integer type whose size is
1874 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001875 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001876 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001877 }
1878
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001879 return To->getKind() == BuiltinType::UInt;
1880 }
1881
Richard Smithb9c5a602012-09-13 21:18:54 +00001882 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001883 // A prvalue of an unscoped enumeration type whose underlying type is not
1884 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1885 // following types that can represent all the values of the enumeration
1886 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1887 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001888 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001889 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001890 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891 // with lowest integer conversion rank (4.13) greater than the rank of long
1892 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001893 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001894 // C++11 [conv.prom]p4:
1895 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1896 // can be converted to a prvalue of its underlying type. Moreover, if
1897 // integral promotion can be applied to its underlying type, a prvalue of an
1898 // unscoped enumeration type whose underlying type is fixed can also be
1899 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001900 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1901 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1902 // provided for a scoped enumeration.
1903 if (FromEnumType->getDecl()->isScoped())
1904 return false;
1905
Richard Smithb9c5a602012-09-13 21:18:54 +00001906 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001907 // even if that's not the promoted type. Note that the check for promoting
1908 // the underlying type is based on the type alone, and does not consider
1909 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001910 if (FromEnumType->getDecl()->isFixed()) {
1911 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1912 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001913 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001914 }
1915
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001916 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001918 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001919 return Context.hasSameUnqualifiedType(
1920 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001921 }
John McCall56774992009-12-09 09:09:27 +00001922
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001923 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1925 // to an rvalue a prvalue of the first of the following types that can
1926 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001927 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001929 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001931 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001933 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934 // Determine whether the type we're converting from is signed or
1935 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001936 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001937 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001939 // The types we'll try to promote to, in the appropriate
1940 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001941 QualType PromoteTypes[6] = {
1942 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001943 Context.LongTy, Context.UnsignedLongTy ,
1944 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001945 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001946 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001947 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1948 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001949 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1951 // We found the type that we can promote to. If this is the
1952 // type we wanted, we have a promotion. Otherwise, no
1953 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001954 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001955 }
1956 }
1957 }
1958
1959 // An rvalue for an integral bit-field (9.6) can be converted to an
1960 // rvalue of type int if int can represent all the values of the
1961 // bit-field; otherwise, it can be converted to unsigned int if
1962 // unsigned int can represent all the values of the bit-field. If
1963 // the bit-field is larger yet, no integral promotion applies to
1964 // it. If the bit-field has an enumerated type, it is treated as any
1965 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001966 // FIXME: We should delay checking of bit-fields until we actually perform the
1967 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001968 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001969 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001970 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001971 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001972 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001973 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001974 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001975
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001976 // Are we promoting to an int from a bitfield that fits in an int?
1977 if (BitWidth < ToSize ||
1978 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1979 return To->getKind() == BuiltinType::Int;
1980 }
Mike Stump11289f42009-09-09 15:08:12 +00001981
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001982 // Are we promoting to an unsigned int from an unsigned bitfield
1983 // that fits into an unsigned int?
1984 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1985 return To->getKind() == BuiltinType::UInt;
1986 }
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001988 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001989 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001990 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001991 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001993 // An rvalue of type bool can be converted to an rvalue of type int,
1994 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001995 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001996 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001997 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001998
1999 return false;
2000}
2001
2002/// IsFloatingPointPromotion - Determines whether the conversion from
2003/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2004/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002005bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002006 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2007 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002008 /// An rvalue of type float can be converted to an rvalue of type
2009 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002010 if (FromBuiltin->getKind() == BuiltinType::Float &&
2011 ToBuiltin->getKind() == BuiltinType::Double)
2012 return true;
2013
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002014 // C99 6.3.1.5p1:
2015 // When a float is promoted to double or long double, or a
2016 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002017 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002018 (FromBuiltin->getKind() == BuiltinType::Float ||
2019 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002020 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2021 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002022 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002023
2024 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002025 if (!getLangOpts().NativeHalfType &&
2026 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002027 ToBuiltin->getKind() == BuiltinType::Float)
2028 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002029 }
2030
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002031 return false;
2032}
2033
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002034/// \brief Determine if a conversion is a complex promotion.
2035///
2036/// A complex promotion is defined as a complex -> complex conversion
2037/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002038/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002039bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002040 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002041 if (!FromComplex)
2042 return false;
2043
John McCall9dd450b2009-09-21 23:43:11 +00002044 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002045 if (!ToComplex)
2046 return false;
2047
2048 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002049 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002050 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002051 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002052}
2053
Douglas Gregor237f96c2008-11-26 23:31:11 +00002054/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2055/// the pointer type FromPtr to a pointer to type ToPointee, with the
2056/// same type qualifiers as FromPtr has on its pointee type. ToType,
2057/// if non-empty, will be a pointer to ToType that may or may not have
2058/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002059///
Mike Stump11289f42009-09-09 15:08:12 +00002060static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002061BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002062 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002063 ASTContext &Context,
2064 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002065 assert((FromPtr->getTypeClass() == Type::Pointer ||
2066 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2067 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068
John McCall31168b02011-06-15 23:02:42 +00002069 /// Conversions to 'id' subsume cv-qualifier conversions.
2070 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002071 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072
2073 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002074 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002075 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002076 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002077
John McCall31168b02011-06-15 23:02:42 +00002078 if (StripObjCLifetime)
2079 Quals.removeObjCLifetime();
2080
Mike Stump11289f42009-09-09 15:08:12 +00002081 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002082 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002083 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002084 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002085 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002086
2087 // Build a pointer to ToPointee. It has the right qualifiers
2088 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002089 if (isa<ObjCObjectPointerType>(ToType))
2090 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002091 return Context.getPointerType(ToPointee);
2092 }
2093
2094 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002095 QualType QualifiedCanonToPointee
2096 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002098 if (isa<ObjCObjectPointerType>(ToType))
2099 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2100 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002101}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002102
Mike Stump11289f42009-09-09 15:08:12 +00002103static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002104 bool InOverloadResolution,
2105 ASTContext &Context) {
2106 // Handle value-dependent integral null pointer constants correctly.
2107 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2108 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002109 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002110 return !InOverloadResolution;
2111
Douglas Gregor56751b52009-09-25 04:25:58 +00002112 return Expr->isNullPointerConstant(Context,
2113 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2114 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002115}
Mike Stump11289f42009-09-09 15:08:12 +00002116
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002117/// IsPointerConversion - Determines whether the conversion of the
2118/// expression From, which has the (possibly adjusted) type FromType,
2119/// can be converted to the type ToType via a pointer conversion (C++
2120/// 4.10). If so, returns true and places the converted type (that
2121/// might differ from ToType in its cv-qualifiers at some level) into
2122/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002123///
Douglas Gregora29dc052008-11-27 01:19:21 +00002124/// This routine also supports conversions to and from block pointers
2125/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2126/// pointers to interfaces. FIXME: Once we've determined the
2127/// appropriate overloading rules for Objective-C, we may want to
2128/// split the Objective-C checks into a different routine; however,
2129/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002130/// conversions, so for now they live here. IncompatibleObjC will be
2131/// set if the conversion is an allowed Objective-C conversion that
2132/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002133bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002134 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002135 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002136 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002137 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002138 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2139 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002140 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002141
Mike Stump11289f42009-09-09 15:08:12 +00002142 // Conversion from a null pointer constant to any Objective-C pointer type.
2143 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002144 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002145 ConvertedType = ToType;
2146 return true;
2147 }
2148
Douglas Gregor231d1c62008-11-27 00:15:41 +00002149 // Blocks: Block pointers can be converted to void*.
2150 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002151 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002152 ConvertedType = ToType;
2153 return true;
2154 }
2155 // Blocks: A null pointer constant can be converted to a block
2156 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002157 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002158 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002159 ConvertedType = ToType;
2160 return true;
2161 }
2162
Sebastian Redl576fd422009-05-10 18:38:11 +00002163 // If the left-hand-side is nullptr_t, the right side can be a null
2164 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002165 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002166 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002167 ConvertedType = ToType;
2168 return true;
2169 }
2170
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002171 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002172 if (!ToTypePtr)
2173 return false;
2174
2175 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002176 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002177 ConvertedType = ToType;
2178 return true;
2179 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002180
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002181 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002182 // , including objective-c pointers.
2183 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002184 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002185 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002186 ConvertedType = BuildSimilarlyQualifiedPointerType(
2187 FromType->getAs<ObjCObjectPointerType>(),
2188 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002189 ToType, Context);
2190 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002191 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002192 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002193 if (!FromTypePtr)
2194 return false;
2195
2196 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002197
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002199 // pointer conversion, so don't do all of the work below.
2200 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2201 return false;
2202
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002203 // An rvalue of type "pointer to cv T," where T is an object type,
2204 // can be converted to an rvalue of type "pointer to cv void" (C++
2205 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002206 if (FromPointeeType->isIncompleteOrObjectType() &&
2207 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002208 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002209 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002210 ToType, Context,
2211 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002212 return true;
2213 }
2214
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002215 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002216 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002217 ToPointeeType->isVoidType()) {
2218 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2219 ToPointeeType,
2220 ToType, Context);
2221 return true;
2222 }
2223
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002224 // When we're overloading in C, we allow a special kind of pointer
2225 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002226 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002227 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002228 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002229 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002230 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002231 return true;
2232 }
2233
Douglas Gregor5c407d92008-10-23 00:40:37 +00002234 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002235 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002236 // An rvalue of type "pointer to cv D," where D is a class type,
2237 // can be converted to an rvalue of type "pointer to cv B," where
2238 // B is a base class (clause 10) of D. If B is an inaccessible
2239 // (clause 11) or ambiguous (10.2) base class of D, a program that
2240 // necessitates this conversion is ill-formed. The result of the
2241 // conversion is a pointer to the base class sub-object of the
2242 // derived class object. The null pointer value is converted to
2243 // the null pointer value of the destination type.
2244 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002245 // Note that we do not check for ambiguity or inaccessibility
2246 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002247 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002248 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002249 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002250 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002251 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002252 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002253 ToType, Context);
2254 return true;
2255 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002256
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002257 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2258 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2259 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2260 ToPointeeType,
2261 ToType, Context);
2262 return true;
2263 }
2264
Douglas Gregora119f102008-12-19 19:13:09 +00002265 return false;
2266}
Douglas Gregoraec25842011-04-26 23:16:46 +00002267
2268/// \brief Adopt the given qualifiers for the given type.
2269static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2270 Qualifiers TQs = T.getQualifiers();
2271
2272 // Check whether qualifiers already match.
2273 if (TQs == Qs)
2274 return T;
2275
2276 if (Qs.compatiblyIncludes(TQs))
2277 return Context.getQualifiedType(T, Qs);
2278
2279 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2280}
Douglas Gregora119f102008-12-19 19:13:09 +00002281
2282/// isObjCPointerConversion - Determines whether this is an
2283/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2284/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002285bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002286 QualType& ConvertedType,
2287 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002288 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002289 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290
Douglas Gregoraec25842011-04-26 23:16:46 +00002291 // The set of qualifiers on the type we're converting from.
2292 Qualifiers FromQualifiers = FromType.getQualifiers();
2293
Steve Naroff7cae42b2009-07-10 23:34:53 +00002294 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002295 const ObjCObjectPointerType* ToObjCPtr =
2296 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002297 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002298 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002299
Steve Naroff7cae42b2009-07-10 23:34:53 +00002300 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002301 // If the pointee types are the same (ignoring qualifications),
2302 // then this is not a pointer conversion.
2303 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2304 FromObjCPtr->getPointeeType()))
2305 return false;
2306
Douglas Gregorab209d82015-07-07 03:58:42 +00002307 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002308 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002309 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2310 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002311 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002312 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2313 FromObjCPtr->getPointeeType()))
2314 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002315 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002316 ToObjCPtr->getPointeeType(),
2317 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002318 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002319 return true;
2320 }
2321
2322 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2323 // Okay: this is some kind of implicit downcast of Objective-C
2324 // interfaces, which is permitted. However, we're going to
2325 // complain about it.
2326 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002327 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002328 ToObjCPtr->getPointeeType(),
2329 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002330 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002331 return true;
2332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002334 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002335 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002336 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002337 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002338 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002339 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002340 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002341 // to a block pointer type.
2342 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002343 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002344 return true;
2345 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002346 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002347 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002348 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002349 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002350 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002351 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002352 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002353 return true;
2354 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002355 else
Douglas Gregora119f102008-12-19 19:13:09 +00002356 return false;
2357
Douglas Gregor033f56d2008-12-23 00:53:59 +00002358 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002359 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002360 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002361 else if (const BlockPointerType *FromBlockPtr =
2362 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002363 FromPointeeType = FromBlockPtr->getPointeeType();
2364 else
Douglas Gregora119f102008-12-19 19:13:09 +00002365 return false;
2366
Douglas Gregora119f102008-12-19 19:13:09 +00002367 // If we have pointers to pointers, recursively check whether this
2368 // is an Objective-C conversion.
2369 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2370 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2371 IncompatibleObjC)) {
2372 // We always complain about this conversion.
2373 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002374 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002375 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002376 return true;
2377 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002378 // Allow conversion of pointee being objective-c pointer to another one;
2379 // as in I* to id.
2380 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2381 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2382 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2383 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002384
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002385 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002386 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002387 return true;
2388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002389
Douglas Gregor033f56d2008-12-23 00:53:59 +00002390 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002391 // differences in the argument and result types are in Objective-C
2392 // pointer conversions. If so, we permit the conversion (but
2393 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002394 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002395 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002396 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002397 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002398 if (FromFunctionType && ToFunctionType) {
2399 // If the function types are exactly the same, this isn't an
2400 // Objective-C pointer conversion.
2401 if (Context.getCanonicalType(FromPointeeType)
2402 == Context.getCanonicalType(ToPointeeType))
2403 return false;
2404
2405 // Perform the quick checks that will tell us whether these
2406 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002407 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002408 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2409 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2410 return false;
2411
2412 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002413 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2414 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002415 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002416 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2417 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002418 ConvertedType, IncompatibleObjC)) {
2419 // Okay, we have an Objective-C pointer conversion.
2420 HasObjCConversion = true;
2421 } else {
2422 // Function types are too different. Abort.
2423 return false;
2424 }
Mike Stump11289f42009-09-09 15:08:12 +00002425
Douglas Gregora119f102008-12-19 19:13:09 +00002426 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002427 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002428 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002429 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2430 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002431 if (Context.getCanonicalType(FromArgType)
2432 == Context.getCanonicalType(ToArgType)) {
2433 // Okay, the types match exactly. Nothing to do.
2434 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2435 ConvertedType, IncompatibleObjC)) {
2436 // Okay, we have an Objective-C pointer conversion.
2437 HasObjCConversion = true;
2438 } else {
2439 // Argument types are too different. Abort.
2440 return false;
2441 }
2442 }
2443
2444 if (HasObjCConversion) {
2445 // We had an Objective-C conversion. Allow this pointer
2446 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002447 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002448 IncompatibleObjC = true;
2449 return true;
2450 }
2451 }
2452
Sebastian Redl72b597d2009-01-25 19:43:20 +00002453 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002454}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455
John McCall31168b02011-06-15 23:02:42 +00002456/// \brief Determine whether this is an Objective-C writeback conversion,
2457/// used for parameter passing when performing automatic reference counting.
2458///
2459/// \param FromType The type we're converting form.
2460///
2461/// \param ToType The type we're converting to.
2462///
2463/// \param ConvertedType The type that will be produced after applying
2464/// this conversion.
2465bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2466 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002467 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002468 Context.hasSameUnqualifiedType(FromType, ToType))
2469 return false;
2470
2471 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2472 QualType ToPointee;
2473 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2474 ToPointee = ToPointer->getPointeeType();
2475 else
2476 return false;
2477
2478 Qualifiers ToQuals = ToPointee.getQualifiers();
2479 if (!ToPointee->isObjCLifetimeType() ||
2480 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002481 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002482 return false;
2483
2484 // Argument must be a pointer to __strong to __weak.
2485 QualType FromPointee;
2486 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2487 FromPointee = FromPointer->getPointeeType();
2488 else
2489 return false;
2490
2491 Qualifiers FromQuals = FromPointee.getQualifiers();
2492 if (!FromPointee->isObjCLifetimeType() ||
2493 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2494 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2495 return false;
2496
2497 // Make sure that we have compatible qualifiers.
2498 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2499 if (!ToQuals.compatiblyIncludes(FromQuals))
2500 return false;
2501
2502 // Remove qualifiers from the pointee type we're converting from; they
2503 // aren't used in the compatibility check belong, and we'll be adding back
2504 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2505 FromPointee = FromPointee.getUnqualifiedType();
2506
2507 // The unqualified form of the pointee types must be compatible.
2508 ToPointee = ToPointee.getUnqualifiedType();
2509 bool IncompatibleObjC;
2510 if (Context.typesAreCompatible(FromPointee, ToPointee))
2511 FromPointee = ToPointee;
2512 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2513 IncompatibleObjC))
2514 return false;
2515
2516 /// \brief Construct the type we're converting to, which is a pointer to
2517 /// __autoreleasing pointee.
2518 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2519 ConvertedType = Context.getPointerType(FromPointee);
2520 return true;
2521}
2522
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002523bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2524 QualType& ConvertedType) {
2525 QualType ToPointeeType;
2526 if (const BlockPointerType *ToBlockPtr =
2527 ToType->getAs<BlockPointerType>())
2528 ToPointeeType = ToBlockPtr->getPointeeType();
2529 else
2530 return false;
2531
2532 QualType FromPointeeType;
2533 if (const BlockPointerType *FromBlockPtr =
2534 FromType->getAs<BlockPointerType>())
2535 FromPointeeType = FromBlockPtr->getPointeeType();
2536 else
2537 return false;
2538 // We have pointer to blocks, check whether the only
2539 // differences in the argument and result types are in Objective-C
2540 // pointer conversions. If so, we permit the conversion.
2541
2542 const FunctionProtoType *FromFunctionType
2543 = FromPointeeType->getAs<FunctionProtoType>();
2544 const FunctionProtoType *ToFunctionType
2545 = ToPointeeType->getAs<FunctionProtoType>();
2546
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002547 if (!FromFunctionType || !ToFunctionType)
2548 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002549
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002550 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002551 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002552
2553 // Perform the quick checks that will tell us whether these
2554 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002555 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002556 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2557 return false;
2558
2559 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2560 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2561 if (FromEInfo != ToEInfo)
2562 return false;
2563
2564 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002565 if (Context.hasSameType(FromFunctionType->getReturnType(),
2566 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002567 // Okay, the types match exactly. Nothing to do.
2568 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002569 QualType RHS = FromFunctionType->getReturnType();
2570 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002571 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002572 !RHS.hasQualifiers() && LHS.hasQualifiers())
2573 LHS = LHS.getUnqualifiedType();
2574
2575 if (Context.hasSameType(RHS,LHS)) {
2576 // OK exact match.
2577 } else if (isObjCPointerConversion(RHS, LHS,
2578 ConvertedType, IncompatibleObjC)) {
2579 if (IncompatibleObjC)
2580 return false;
2581 // Okay, we have an Objective-C pointer conversion.
2582 }
2583 else
2584 return false;
2585 }
2586
2587 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002588 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002589 ArgIdx != NumArgs; ++ArgIdx) {
2590 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002591 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2592 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002593 if (Context.hasSameType(FromArgType, ToArgType)) {
2594 // Okay, the types match exactly. Nothing to do.
2595 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2596 ConvertedType, IncompatibleObjC)) {
2597 if (IncompatibleObjC)
2598 return false;
2599 // Okay, we have an Objective-C pointer conversion.
2600 } else
2601 // Argument types are too different. Abort.
2602 return false;
2603 }
John McCall18afab72016-03-01 00:49:02 +00002604 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2605 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002606 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002607
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002608 ConvertedType = ToType;
2609 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002610}
2611
Richard Trieucaff2472011-11-23 22:32:32 +00002612enum {
2613 ft_default,
2614 ft_different_class,
2615 ft_parameter_arity,
2616 ft_parameter_mismatch,
2617 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002618 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002619};
2620
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002621/// Attempts to get the FunctionProtoType from a Type. Handles
2622/// MemberFunctionPointers properly.
2623static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2624 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2625 return FPT;
2626
2627 if (auto *MPT = FromType->getAs<MemberPointerType>())
2628 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2629
2630 return nullptr;
2631}
2632
Richard Trieucaff2472011-11-23 22:32:32 +00002633/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2634/// function types. Catches different number of parameter, mismatch in
2635/// parameter types, and different return types.
2636void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2637 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002638 // If either type is not valid, include no extra info.
2639 if (FromType.isNull() || ToType.isNull()) {
2640 PDiag << ft_default;
2641 return;
2642 }
2643
Richard Trieucaff2472011-11-23 22:32:32 +00002644 // Get the function type from the pointers.
2645 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2646 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2647 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002648 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002649 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2650 << QualType(FromMember->getClass(), 0);
2651 return;
2652 }
2653 FromType = FromMember->getPointeeType();
2654 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002655 }
2656
Richard Trieu96ed5b62011-12-13 23:19:45 +00002657 if (FromType->isPointerType())
2658 FromType = FromType->getPointeeType();
2659 if (ToType->isPointerType())
2660 ToType = ToType->getPointeeType();
2661
2662 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002663 FromType = FromType.getNonReferenceType();
2664 ToType = ToType.getNonReferenceType();
2665
Richard Trieucaff2472011-11-23 22:32:32 +00002666 // Don't print extra info for non-specialized template functions.
2667 if (FromType->isInstantiationDependentType() &&
2668 !FromType->getAs<TemplateSpecializationType>()) {
2669 PDiag << ft_default;
2670 return;
2671 }
2672
Richard Trieu96ed5b62011-12-13 23:19:45 +00002673 // No extra info for same types.
2674 if (Context.hasSameType(FromType, ToType)) {
2675 PDiag << ft_default;
2676 return;
2677 }
2678
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002679 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2680 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002681
2682 // Both types need to be function types.
2683 if (!FromFunction || !ToFunction) {
2684 PDiag << ft_default;
2685 return;
2686 }
2687
Alp Toker9cacbab2014-01-20 20:26:09 +00002688 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2689 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2690 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002691 return;
2692 }
2693
2694 // Handle different parameter types.
2695 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002696 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002697 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002698 << ToFunction->getParamType(ArgPos)
2699 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002700 return;
2701 }
2702
2703 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002704 if (!Context.hasSameType(FromFunction->getReturnType(),
2705 ToFunction->getReturnType())) {
2706 PDiag << ft_return_type << ToFunction->getReturnType()
2707 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002708 return;
2709 }
2710
2711 unsigned FromQuals = FromFunction->getTypeQuals(),
2712 ToQuals = ToFunction->getTypeQuals();
2713 if (FromQuals != ToQuals) {
2714 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2715 return;
2716 }
2717
2718 // Unable to find a difference, so add no extra info.
2719 PDiag << ft_default;
2720}
2721
Alp Toker9cacbab2014-01-20 20:26:09 +00002722/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002723/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002724/// they have same number of arguments. If the parameters are different,
2725/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002726bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2727 const FunctionProtoType *NewType,
2728 unsigned *ArgPos) {
2729 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2730 N = NewType->param_type_begin(),
2731 E = OldType->param_type_end();
2732 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002733 if (!Context.hasSameType(O->getUnqualifiedType(),
2734 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002735 if (ArgPos)
2736 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002737 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002738 }
2739 }
2740 return true;
2741}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002742
Douglas Gregor39c16d42008-10-24 04:54:22 +00002743/// CheckPointerConversion - Check the pointer conversion from the
2744/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002745/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002746/// conversions for which IsPointerConversion has already returned
2747/// true. It returns true and produces a diagnostic if there was an
2748/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002749bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002750 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002751 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002752 bool IgnoreBaseAccess,
2753 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002754 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002755 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002756
John McCall8cb679e2010-11-15 09:13:47 +00002757 Kind = CK_BitCast;
2758
George Burgess IV60bc9722016-01-13 23:36:34 +00002759 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002760 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002761 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002762 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2763 DiagRuntimeBehavior(From->getExprLoc(), From,
2764 PDiag(diag::warn_impcast_bool_to_null_pointer)
2765 << ToType << From->getSourceRange());
2766 else if (!isUnevaluatedContext())
2767 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2768 << ToType << From->getSourceRange();
2769 }
John McCall9320b872011-09-09 05:25:32 +00002770 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2771 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002772 QualType FromPointeeType = FromPtrType->getPointeeType(),
2773 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002774
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002775 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2776 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002777 // We must have a derived-to-base conversion. Check an
2778 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002779 unsigned InaccessibleID = 0;
2780 unsigned AmbigiousID = 0;
2781 if (Diagnose) {
2782 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2783 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2784 }
2785 if (CheckDerivedToBaseConversion(
2786 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2787 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2788 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002789 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002790
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002791 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002792 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002793 }
David Majnemer6bf02822015-10-31 08:42:14 +00002794
George Burgess IV60bc9722016-01-13 23:36:34 +00002795 if (Diagnose && !IsCStyleOrFunctionalCast &&
2796 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002797 assert(getLangOpts().MSVCCompat &&
2798 "this should only be possible with MSVCCompat!");
2799 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2800 << From->getSourceRange();
2801 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002802 }
John McCall9320b872011-09-09 05:25:32 +00002803 } else if (const ObjCObjectPointerType *ToPtrType =
2804 ToType->getAs<ObjCObjectPointerType>()) {
2805 if (const ObjCObjectPointerType *FromPtrType =
2806 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002807 // Objective-C++ conversions are always okay.
2808 // FIXME: We should have a different class of conversions for the
2809 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002810 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002811 return false;
John McCall9320b872011-09-09 05:25:32 +00002812 } else if (FromType->isBlockPointerType()) {
2813 Kind = CK_BlockPointerToObjCPointerCast;
2814 } else {
2815 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002816 }
John McCall9320b872011-09-09 05:25:32 +00002817 } else if (ToType->isBlockPointerType()) {
2818 if (!FromType->isBlockPointerType())
2819 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002820 }
John McCall8cb679e2010-11-15 09:13:47 +00002821
2822 // We shouldn't fall into this case unless it's valid for other
2823 // reasons.
2824 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2825 Kind = CK_NullToPointer;
2826
Douglas Gregor39c16d42008-10-24 04:54:22 +00002827 return false;
2828}
2829
Sebastian Redl72b597d2009-01-25 19:43:20 +00002830/// IsMemberPointerConversion - Determines whether the conversion of the
2831/// expression From, which has the (possibly adjusted) type FromType, can be
2832/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2833/// If so, returns true and places the converted type (that might differ from
2834/// ToType in its cv-qualifiers at some level) into ConvertedType.
2835bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002836 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002837 bool InOverloadResolution,
2838 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002839 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002840 if (!ToTypePtr)
2841 return false;
2842
2843 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002844 if (From->isNullPointerConstant(Context,
2845 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2846 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002847 ConvertedType = ToType;
2848 return true;
2849 }
2850
2851 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002852 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002853 if (!FromTypePtr)
2854 return false;
2855
2856 // A pointer to member of B can be converted to a pointer to member of D,
2857 // where D is derived from B (C++ 4.11p2).
2858 QualType FromClass(FromTypePtr->getClass(), 0);
2859 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002860
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002861 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002862 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002863 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2864 ToClass.getTypePtr());
2865 return true;
2866 }
2867
2868 return false;
2869}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002870
Sebastian Redl72b597d2009-01-25 19:43:20 +00002871/// CheckMemberPointerConversion - Check the member pointer conversion from the
2872/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002873/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002874/// for which IsMemberPointerConversion has already returned true. It returns
2875/// true and produces a diagnostic if there was an error, or returns false
2876/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002877bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002878 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002879 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002880 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002881 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002882 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002883 if (!FromPtrType) {
2884 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002886 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002887 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002888 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002889 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002890 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002891
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002892 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002893 assert(ToPtrType && "No member pointer cast has a target type "
2894 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002895
Sebastian Redled8f2002009-01-28 18:33:18 +00002896 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2897 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002898
Sebastian Redled8f2002009-01-28 18:33:18 +00002899 // FIXME: What about dependent types?
2900 assert(FromClass->isRecordType() && "Pointer into non-class.");
2901 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002902
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002903 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002904 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002905 bool DerivationOkay =
2906 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002907 assert(DerivationOkay &&
2908 "Should not have been called if derivation isn't OK.");
2909 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002910
Sebastian Redled8f2002009-01-28 18:33:18 +00002911 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2912 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002913 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2914 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2915 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2916 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002917 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002918
Douglas Gregor89ee6822009-02-28 01:32:25 +00002919 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002920 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2921 << FromClass << ToClass << QualType(VBase, 0)
2922 << From->getSourceRange();
2923 return true;
2924 }
2925
John McCall5b0829a2010-02-10 09:31:12 +00002926 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002927 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2928 Paths.front(),
2929 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002930
Anders Carlssond7923c62009-08-22 23:33:40 +00002931 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002932 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002933 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002934 return false;
2935}
2936
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002937/// Determine whether the lifetime conversion between the two given
2938/// qualifiers sets is nontrivial.
2939static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2940 Qualifiers ToQuals) {
2941 // Converting anything to const __unsafe_unretained is trivial.
2942 if (ToQuals.hasConst() &&
2943 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2944 return false;
2945
2946 return true;
2947}
2948
Douglas Gregor9a657932008-10-21 23:43:52 +00002949/// IsQualificationConversion - Determines whether the conversion from
2950/// an rvalue of type FromType to ToType is a qualification conversion
2951/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002952///
2953/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2954/// when the qualification conversion involves a change in the Objective-C
2955/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002956bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002958 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002959 FromType = Context.getCanonicalType(FromType);
2960 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002961 ObjCLifetimeConversion = false;
2962
Douglas Gregor9a657932008-10-21 23:43:52 +00002963 // If FromType and ToType are the same type, this is not a
2964 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002965 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002966 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002967
Douglas Gregor9a657932008-10-21 23:43:52 +00002968 // (C++ 4.4p4):
2969 // A conversion can add cv-qualifiers at levels other than the first
2970 // in multi-level pointers, subject to the following rules: [...]
2971 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002972 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002973 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002974 // Within each iteration of the loop, we check the qualifiers to
2975 // determine if this still looks like a qualification
2976 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002977 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002978 // until there are no more pointers or pointers-to-members left to
2979 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002980 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002981
Douglas Gregor90609aa2011-04-25 18:40:17 +00002982 Qualifiers FromQuals = FromType.getQualifiers();
2983 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00002984
2985 // Ignore __unaligned qualifier if this type is void.
2986 if (ToType.getUnqualifiedType()->isVoidType())
2987 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00002988
John McCall31168b02011-06-15 23:02:42 +00002989 // Objective-C ARC:
2990 // Check Objective-C lifetime conversions.
2991 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2992 UnwrappedAnyPointer) {
2993 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002994 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2995 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002996 FromQuals.removeObjCLifetime();
2997 ToQuals.removeObjCLifetime();
2998 } else {
2999 // Qualification conversions cannot cast between different
3000 // Objective-C lifetime qualifiers.
3001 return false;
3002 }
3003 }
3004
Douglas Gregorf30053d2011-05-08 06:09:53 +00003005 // Allow addition/removal of GC attributes but not changing GC attributes.
3006 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3007 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3008 FromQuals.removeObjCGCAttr();
3009 ToQuals.removeObjCGCAttr();
3010 }
3011
Douglas Gregor9a657932008-10-21 23:43:52 +00003012 // -- for every j > 0, if const is in cv 1,j then const is in cv
3013 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003014 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003015 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003016
Douglas Gregor9a657932008-10-21 23:43:52 +00003017 // -- if the cv 1,j and cv 2,j are different, then const is in
3018 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003019 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003020 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003021 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003022
Douglas Gregor9a657932008-10-21 23:43:52 +00003023 // Keep track of whether all prior cv-qualifiers in the "to" type
3024 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003025 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003026 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003027 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003028
3029 // We are left with FromType and ToType being the pointee types
3030 // after unwrapping the original FromType and ToType the same number
3031 // of types. If we unwrapped any pointers, and if FromType and
3032 // ToType have the same unqualified type (since we checked
3033 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003034 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003035}
3036
Douglas Gregorc79862f2012-04-12 17:51:55 +00003037/// \brief - Determine whether this is a conversion from a scalar type to an
3038/// atomic type.
3039///
3040/// If successful, updates \c SCS's second and third steps in the conversion
3041/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003042static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3043 bool InOverloadResolution,
3044 StandardConversionSequence &SCS,
3045 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003046 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3047 if (!ToAtomic)
3048 return false;
3049
3050 StandardConversionSequence InnerSCS;
3051 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3052 InOverloadResolution, InnerSCS,
3053 CStyle, /*AllowObjCWritebackConversion=*/false))
3054 return false;
3055
3056 SCS.Second = InnerSCS.Second;
3057 SCS.setToType(1, InnerSCS.getToType(1));
3058 SCS.Third = InnerSCS.Third;
3059 SCS.QualificationIncludesObjCLifetime
3060 = InnerSCS.QualificationIncludesObjCLifetime;
3061 SCS.setToType(2, InnerSCS.getToType(2));
3062 return true;
3063}
3064
Sebastian Redle5417162012-03-27 18:33:03 +00003065static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3066 CXXConstructorDecl *Constructor,
3067 QualType Type) {
3068 const FunctionProtoType *CtorType =
3069 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003070 if (CtorType->getNumParams() > 0) {
3071 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003072 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3073 return true;
3074 }
3075 return false;
3076}
3077
Sebastian Redl82ace982012-02-11 23:51:08 +00003078static OverloadingResult
3079IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3080 CXXRecordDecl *To,
3081 UserDefinedConversionSequence &User,
3082 OverloadCandidateSet &CandidateSet,
3083 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003084 for (auto *D : S.LookupConstructors(To)) {
3085 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003086 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003087 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003088
Richard Smithc2bebe92016-05-11 20:37:46 +00003089 bool Usable = !Info.Constructor->isInvalidDecl() &&
3090 S.isInitListConstructor(Info.Constructor) &&
3091 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003092 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003093 // If the first argument is (a reference to) the target type,
3094 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003095 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3096 S.Context, Info.Constructor, ToType);
3097 if (Info.ConstructorTmpl)
3098 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3099 /*ExplicitArgs*/ nullptr, From,
3100 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003101 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003102 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3103 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003104 }
3105 }
3106
3107 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3108
3109 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003110 switch (auto Result =
3111 CandidateSet.BestViableFunction(S, From->getLocStart(),
3112 Best, true)) {
3113 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003114 case OR_Success: {
3115 // Record the standard conversion we used and the conversion function.
3116 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003117 QualType ThisType = Constructor->getThisType(S.Context);
3118 // Initializer lists don't have conversions as such.
3119 User.Before.setAsIdentityConversion();
3120 User.HadMultipleCandidates = HadMultipleCandidates;
3121 User.ConversionFunction = Constructor;
3122 User.FoundConversionFunction = Best->FoundDecl;
3123 User.After.setAsIdentityConversion();
3124 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3125 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003126 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003127 }
3128
3129 case OR_No_Viable_Function:
3130 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003131 case OR_Ambiguous:
3132 return OR_Ambiguous;
3133 }
3134
3135 llvm_unreachable("Invalid OverloadResult!");
3136}
3137
Douglas Gregor576e98c2009-01-30 23:27:23 +00003138/// Determines whether there is a user-defined conversion sequence
3139/// (C++ [over.ics.user]) that converts expression From to the type
3140/// ToType. If such a conversion exists, User will contain the
3141/// user-defined conversion sequence that performs such a conversion
3142/// and this routine will return true. Otherwise, this routine returns
3143/// false and User is unspecified.
3144///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003145/// \param AllowExplicit true if the conversion should consider C++0x
3146/// "explicit" conversion functions as well as non-explicit conversion
3147/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003148///
3149/// \param AllowObjCConversionOnExplicit true if the conversion should
3150/// allow an extra Objective-C pointer conversion on uses of explicit
3151/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003152static OverloadingResult
3153IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003154 UserDefinedConversionSequence &User,
3155 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003156 bool AllowExplicit,
3157 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003158 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003159
Douglas Gregor5ab11652010-04-17 22:01:05 +00003160 // Whether we will only visit constructors.
3161 bool ConstructorsOnly = false;
3162
3163 // If the type we are conversion to is a class type, enumerate its
3164 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003165 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003166 // C++ [over.match.ctor]p1:
3167 // When objects of class type are direct-initialized (8.5), or
3168 // copy-initialized from an expression of the same or a
3169 // derived class type (8.5), overload resolution selects the
3170 // constructor. [...] For copy-initialization, the candidate
3171 // functions are all the converting constructors (12.3.1) of
3172 // that class. The argument list is the expression-list within
3173 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003174 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003175 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003176 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003177 ConstructorsOnly = true;
3178
Richard Smithdb0ac552015-12-18 22:40:25 +00003179 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003180 // We're not going to find any constructors.
3181 } else if (CXXRecordDecl *ToRecordDecl
3182 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003183
3184 Expr **Args = &From;
3185 unsigned NumArgs = 1;
3186 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003187 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003188 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003189 OverloadingResult Result = IsInitializerListConstructorConversion(
3190 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3191 if (Result != OR_No_Viable_Function)
3192 return Result;
3193 // Never mind.
3194 CandidateSet.clear();
3195
3196 // If we're list-initializing, we pass the individual elements as
3197 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003198 Args = InitList->getInits();
3199 NumArgs = InitList->getNumInits();
3200 ListInitializing = true;
3201 }
3202
Richard Smithc2bebe92016-05-11 20:37:46 +00003203 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3204 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003205 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003206 continue;
John McCalla0296f72010-03-19 07:35:19 +00003207
Richard Smithc2bebe92016-05-11 20:37:46 +00003208 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003209 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003210 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003211 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003212 Usable = Usable &&
3213 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003214 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003215 bool SuppressUserConversions = !ConstructorsOnly;
3216 if (SuppressUserConversions && ListInitializing) {
3217 SuppressUserConversions = false;
3218 if (NumArgs == 1) {
3219 // If the first argument is (a reference to) the target type,
3220 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003221 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003222 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003223 }
3224 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003225 if (Info.ConstructorTmpl)
3226 S.AddTemplateOverloadCandidate(
3227 Info.ConstructorTmpl, Info.FoundDecl,
3228 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3229 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003230 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003231 // Allow one user-defined conversion when user specifies a
3232 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003233 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003234 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003235 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003236 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003237 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003238 }
3239 }
3240
Douglas Gregor5ab11652010-04-17 22:01:05 +00003241 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003242 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003243 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003244 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003245 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003246 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003247 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003248 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3249 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003250 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3251 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003252 DeclAccessPair FoundDecl = I.getPair();
3253 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003254 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3255 if (isa<UsingShadowDecl>(D))
3256 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3257
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003258 CXXConversionDecl *Conv;
3259 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003260 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3261 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003262 else
John McCallda4458e2010-03-31 01:36:47 +00003263 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003264
3265 if (AllowExplicit || !Conv->isExplicit()) {
3266 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003267 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3268 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003269 CandidateSet,
3270 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003271 else
John McCall5c32be02010-08-24 20:38:10 +00003272 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003273 From, ToType, CandidateSet,
3274 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003275 }
3276 }
3277 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003278 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003279
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003280 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3281
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003282 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003283 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3284 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003285 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003286 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003287 // Record the standard conversion we used and the conversion function.
3288 if (CXXConstructorDecl *Constructor
3289 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3290 // C++ [over.ics.user]p1:
3291 // If the user-defined conversion is specified by a
3292 // constructor (12.3.1), the initial standard conversion
3293 // sequence converts the source type to the type required by
3294 // the argument of the constructor.
3295 //
3296 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003297 if (isa<InitListExpr>(From)) {
3298 // Initializer lists don't have conversions as such.
3299 User.Before.setAsIdentityConversion();
3300 } else {
3301 if (Best->Conversions[0].isEllipsis())
3302 User.EllipsisConversion = true;
3303 else {
3304 User.Before = Best->Conversions[0].Standard;
3305 User.EllipsisConversion = false;
3306 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003307 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003308 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003309 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003310 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003311 User.After.setAsIdentityConversion();
3312 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3313 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003314 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003315 }
3316 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003317 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3318 // C++ [over.ics.user]p1:
3319 //
3320 // [...] If the user-defined conversion is specified by a
3321 // conversion function (12.3.2), the initial standard
3322 // conversion sequence converts the source type to the
3323 // implicit object parameter of the conversion function.
3324 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003325 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003326 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003327 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003328 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003329
John McCall5c32be02010-08-24 20:38:10 +00003330 // C++ [over.ics.user]p2:
3331 // The second standard conversion sequence converts the
3332 // result of the user-defined conversion to the target type
3333 // for the sequence. Since an implicit conversion sequence
3334 // is an initialization, the special rules for
3335 // initialization by user-defined conversion apply when
3336 // selecting the best user-defined conversion for a
3337 // user-defined conversion sequence (see 13.3.3 and
3338 // 13.3.3.1).
3339 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003340 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003341 }
David Blaikie8a40f702012-01-17 06:56:22 +00003342 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003343
John McCall5c32be02010-08-24 20:38:10 +00003344 case OR_No_Viable_Function:
3345 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346
John McCall5c32be02010-08-24 20:38:10 +00003347 case OR_Ambiguous:
3348 return OR_Ambiguous;
3349 }
3350
David Blaikie8a40f702012-01-17 06:56:22 +00003351 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003352}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003354bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003355Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003356 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003357 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3358 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003360 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003361 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003362 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003363 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3364 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003365 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003366 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003367 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003368 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003369 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003370 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003371 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003372 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003373 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003375}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003376
Douglas Gregor2837aa22012-02-22 17:32:19 +00003377/// \brief Compare the user-defined conversion functions or constructors
3378/// of two user-defined conversion sequences to determine whether any ordering
3379/// is possible.
3380static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003381compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003382 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003383 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003384 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003385
Douglas Gregor2837aa22012-02-22 17:32:19 +00003386 // Objective-C++:
3387 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003388 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003389 // respectively, always prefer the conversion to a function pointer,
3390 // because the function pointer is more lightweight and is more likely
3391 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003392 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003393 if (!Conv1)
3394 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003395
Douglas Gregor2837aa22012-02-22 17:32:19 +00003396 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3397 if (!Conv2)
3398 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003399
Douglas Gregor2837aa22012-02-22 17:32:19 +00003400 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3401 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3402 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3403 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003404 return Block1 ? ImplicitConversionSequence::Worse
3405 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003406 }
3407
3408 return ImplicitConversionSequence::Indistinguishable;
3409}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003410
3411static bool hasDeprecatedStringLiteralToCharPtrConversion(
3412 const ImplicitConversionSequence &ICS) {
3413 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3414 (ICS.isUserDefined() &&
3415 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3416}
3417
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003418/// CompareImplicitConversionSequences - Compare two implicit
3419/// conversion sequences to determine whether one is better than the
3420/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003421static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003422CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003423 const ImplicitConversionSequence& ICS1,
3424 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003425{
3426 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3427 // conversion sequences (as defined in 13.3.3.1)
3428 // -- a standard conversion sequence (13.3.3.1.1) is a better
3429 // conversion sequence than a user-defined conversion sequence or
3430 // an ellipsis conversion sequence, and
3431 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3432 // conversion sequence than an ellipsis conversion sequence
3433 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003434 //
John McCall0d1da222010-01-12 00:44:57 +00003435 // C++0x [over.best.ics]p10:
3436 // For the purpose of ranking implicit conversion sequences as
3437 // described in 13.3.3.2, the ambiguous conversion sequence is
3438 // treated as a user-defined sequence that is indistinguishable
3439 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003440
3441 // String literal to 'char *' conversion has been deprecated in C++03. It has
3442 // been removed from C++11. We still accept this conversion, if it happens at
3443 // the best viable function. Otherwise, this conversion is considered worse
3444 // than ellipsis conversion. Consider this as an extension; this is not in the
3445 // standard. For example:
3446 //
3447 // int &f(...); // #1
3448 // void f(char*); // #2
3449 // void g() { int &r = f("foo"); }
3450 //
3451 // In C++03, we pick #2 as the best viable function.
3452 // In C++11, we pick #1 as the best viable function, because ellipsis
3453 // conversion is better than string-literal to char* conversion (since there
3454 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3455 // convert arguments, #2 would be the best viable function in C++11.
3456 // If the best viable function has this conversion, a warning will be issued
3457 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3458
3459 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3460 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3461 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3462 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3463 ? ImplicitConversionSequence::Worse
3464 : ImplicitConversionSequence::Better;
3465
Douglas Gregor5ab11652010-04-17 22:01:05 +00003466 if (ICS1.getKindRank() < ICS2.getKindRank())
3467 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003468 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003469 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003470
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003471 // The following checks require both conversion sequences to be of
3472 // the same kind.
3473 if (ICS1.getKind() != ICS2.getKind())
3474 return ImplicitConversionSequence::Indistinguishable;
3475
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003476 ImplicitConversionSequence::CompareKind Result =
3477 ImplicitConversionSequence::Indistinguishable;
3478
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003479 // Two implicit conversion sequences of the same form are
3480 // indistinguishable conversion sequences unless one of the
3481 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003482
3483 // List-initialization sequence L1 is a better conversion sequence than
3484 // list-initialization sequence L2 if:
3485 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3486 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003487 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003488 // and N1 is smaller than N2.,
3489 // even if one of the other rules in this paragraph would otherwise apply.
3490 if (!ICS1.isBad()) {
3491 if (ICS1.isStdInitializerListElement() &&
3492 !ICS2.isStdInitializerListElement())
3493 return ImplicitConversionSequence::Better;
3494 if (!ICS1.isStdInitializerListElement() &&
3495 ICS2.isStdInitializerListElement())
3496 return ImplicitConversionSequence::Worse;
3497 }
3498
John McCall0d1da222010-01-12 00:44:57 +00003499 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003500 // Standard conversion sequence S1 is a better conversion sequence than
3501 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003502 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003503 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003504 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003505 // User-defined conversion sequence U1 is a better conversion
3506 // sequence than another user-defined conversion sequence U2 if
3507 // they contain the same user-defined conversion function or
3508 // constructor and if the second standard conversion sequence of
3509 // U1 is better than the second standard conversion sequence of
3510 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003511 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003512 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003513 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003514 ICS1.UserDefined.After,
3515 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003516 else
3517 Result = compareConversionFunctions(S,
3518 ICS1.UserDefined.ConversionFunction,
3519 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003520 }
3521
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003522 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003523}
3524
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003525static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3526 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3527 Qualifiers Quals;
3528 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003532 return Context.hasSameUnqualifiedType(T1, T2);
3533}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003535// Per 13.3.3.2p3, compare the given standard conversion sequences to
3536// determine if one is a proper subset of the other.
3537static ImplicitConversionSequence::CompareKind
3538compareStandardConversionSubsets(ASTContext &Context,
3539 const StandardConversionSequence& SCS1,
3540 const StandardConversionSequence& SCS2) {
3541 ImplicitConversionSequence::CompareKind Result
3542 = ImplicitConversionSequence::Indistinguishable;
3543
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003545 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003546 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3547 return ImplicitConversionSequence::Better;
3548 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3549 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003551 if (SCS1.Second != SCS2.Second) {
3552 if (SCS1.Second == ICK_Identity)
3553 Result = ImplicitConversionSequence::Better;
3554 else if (SCS2.Second == ICK_Identity)
3555 Result = ImplicitConversionSequence::Worse;
3556 else
3557 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003558 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003559 return ImplicitConversionSequence::Indistinguishable;
3560
3561 if (SCS1.Third == SCS2.Third) {
3562 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3563 : ImplicitConversionSequence::Indistinguishable;
3564 }
3565
3566 if (SCS1.Third == ICK_Identity)
3567 return Result == ImplicitConversionSequence::Worse
3568 ? ImplicitConversionSequence::Indistinguishable
3569 : ImplicitConversionSequence::Better;
3570
3571 if (SCS2.Third == ICK_Identity)
3572 return Result == ImplicitConversionSequence::Better
3573 ? ImplicitConversionSequence::Indistinguishable
3574 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003576 return ImplicitConversionSequence::Indistinguishable;
3577}
3578
Douglas Gregore696ebb2011-01-26 14:52:12 +00003579/// \brief Determine whether one of the given reference bindings is better
3580/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003581static bool
3582isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3583 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003584 // C++0x [over.ics.rank]p3b4:
3585 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3586 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003587 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003588 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003590 // reference*.
3591 //
3592 // FIXME: Rvalue references. We're going rogue with the above edits,
3593 // because the semantics in the current C++0x working paper (N3225 at the
3594 // time of this writing) break the standard definition of std::forward
3595 // and std::reference_wrapper when dealing with references to functions.
3596 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003597 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3598 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3599 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregore696ebb2011-01-26 14:52:12 +00003601 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3602 SCS2.IsLvalueReference) ||
3603 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003604 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003605}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003607/// CompareStandardConversionSequences - Compare two standard
3608/// conversion sequences to determine whether one is better than the
3609/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003610static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003611CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003612 const StandardConversionSequence& SCS1,
3613 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003614{
3615 // Standard conversion sequence S1 is a better conversion sequence
3616 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3617
3618 // -- S1 is a proper subsequence of S2 (comparing the conversion
3619 // sequences in the canonical form defined by 13.3.3.1.1,
3620 // excluding any Lvalue Transformation; the identity conversion
3621 // sequence is considered to be a subsequence of any
3622 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003623 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003624 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003625 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003626
3627 // -- the rank of S1 is better than the rank of S2 (by the rules
3628 // defined below), or, if not that,
3629 ImplicitConversionRank Rank1 = SCS1.getRank();
3630 ImplicitConversionRank Rank2 = SCS2.getRank();
3631 if (Rank1 < Rank2)
3632 return ImplicitConversionSequence::Better;
3633 else if (Rank2 < Rank1)
3634 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003635
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003636 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3637 // are indistinguishable unless one of the following rules
3638 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003639
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003640 // A conversion that is not a conversion of a pointer, or
3641 // pointer to member, to bool is better than another conversion
3642 // that is such a conversion.
3643 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3644 return SCS2.isPointerConversionToBool()
3645 ? ImplicitConversionSequence::Better
3646 : ImplicitConversionSequence::Worse;
3647
Douglas Gregor5c407d92008-10-23 00:40:37 +00003648 // C++ [over.ics.rank]p4b2:
3649 //
3650 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003651 // conversion of B* to A* is better than conversion of B* to
3652 // void*, and conversion of A* to void* is better than conversion
3653 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003654 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003655 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003656 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003657 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003658 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3659 // Exactly one of the conversion sequences is a conversion to
3660 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003661 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3662 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003663 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3664 // Neither conversion sequence converts to a void pointer; compare
3665 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003666 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003667 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003668 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003669 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3670 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003671 // Both conversion sequences are conversions to void
3672 // pointers. Compare the source types to determine if there's an
3673 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003674 QualType FromType1 = SCS1.getFromType();
3675 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003676
3677 // Adjust the types we're converting from via the array-to-pointer
3678 // conversion, if we need to.
3679 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003680 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003681 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003682 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003683
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003684 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3685 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003686
Richard Smith0f59cb32015-12-18 21:45:41 +00003687 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003688 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003689 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003690 return ImplicitConversionSequence::Worse;
3691
3692 // Objective-C++: If one interface is more specific than the
3693 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003694 const ObjCObjectPointerType* FromObjCPtr1
3695 = FromType1->getAs<ObjCObjectPointerType>();
3696 const ObjCObjectPointerType* FromObjCPtr2
3697 = FromType2->getAs<ObjCObjectPointerType>();
3698 if (FromObjCPtr1 && FromObjCPtr2) {
3699 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3700 FromObjCPtr2);
3701 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3702 FromObjCPtr1);
3703 if (AssignLeft != AssignRight) {
3704 return AssignLeft? ImplicitConversionSequence::Better
3705 : ImplicitConversionSequence::Worse;
3706 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003707 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003708 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003709
3710 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3711 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003712 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003713 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003714 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003715
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003716 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003717 // Check for a better reference binding based on the kind of bindings.
3718 if (isBetterReferenceBindingKind(SCS1, SCS2))
3719 return ImplicitConversionSequence::Better;
3720 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3721 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722
Sebastian Redlb28b4072009-03-22 23:49:27 +00003723 // C++ [over.ics.rank]p3b4:
3724 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3725 // which the references refer are the same type except for
3726 // top-level cv-qualifiers, and the type to which the reference
3727 // initialized by S2 refers is more cv-qualified than the type
3728 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003729 QualType T1 = SCS1.getToType(2);
3730 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003731 T1 = S.Context.getCanonicalType(T1);
3732 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003733 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003734 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3735 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003736 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003737 // Objective-C++ ARC: If the references refer to objects with different
3738 // lifetimes, prefer bindings that don't change lifetime.
3739 if (SCS1.ObjCLifetimeConversionBinding !=
3740 SCS2.ObjCLifetimeConversionBinding) {
3741 return SCS1.ObjCLifetimeConversionBinding
3742 ? ImplicitConversionSequence::Worse
3743 : ImplicitConversionSequence::Better;
3744 }
3745
Chandler Carruth8e543b32010-12-12 08:17:55 +00003746 // If the type is an array type, promote the element qualifiers to the
3747 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003748 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003749 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003750 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003751 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003752 if (T2.isMoreQualifiedThan(T1))
3753 return ImplicitConversionSequence::Better;
3754 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003755 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003756 }
3757 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003758
Francois Pichet08d2fa02011-09-18 21:37:37 +00003759 // In Microsoft mode, prefer an integral conversion to a
3760 // floating-to-integral conversion if the integral conversion
3761 // is between types of the same size.
3762 // For example:
3763 // void f(float);
3764 // void f(int);
3765 // int main {
3766 // long a;
3767 // f(a);
3768 // }
3769 // Here, MSVC will call f(int) instead of generating a compile error
3770 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003771 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3772 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003773 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003774 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003775 return ImplicitConversionSequence::Better;
3776
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003777 return ImplicitConversionSequence::Indistinguishable;
3778}
3779
3780/// CompareQualificationConversions - Compares two standard conversion
3781/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003782/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003783static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003784CompareQualificationConversions(Sema &S,
3785 const StandardConversionSequence& SCS1,
3786 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003787 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003788 // -- S1 and S2 differ only in their qualification conversion and
3789 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3790 // cv-qualification signature of type T1 is a proper subset of
3791 // the cv-qualification signature of type T2, and S1 is not the
3792 // deprecated string literal array-to-pointer conversion (4.2).
3793 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3794 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3795 return ImplicitConversionSequence::Indistinguishable;
3796
3797 // FIXME: the example in the standard doesn't use a qualification
3798 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003799 QualType T1 = SCS1.getToType(2);
3800 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003801 T1 = S.Context.getCanonicalType(T1);
3802 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003803 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003804 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3805 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003806
3807 // If the types are the same, we won't learn anything by unwrapped
3808 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003809 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003810 return ImplicitConversionSequence::Indistinguishable;
3811
Chandler Carruth607f38e2009-12-29 07:16:59 +00003812 // If the type is an array type, promote the element qualifiers to the type
3813 // for comparison.
3814 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003815 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003816 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003817 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003818
Mike Stump11289f42009-09-09 15:08:12 +00003819 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003820 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003821
3822 // Objective-C++ ARC:
3823 // Prefer qualification conversions not involving a change in lifetime
3824 // to qualification conversions that do not change lifetime.
3825 if (SCS1.QualificationIncludesObjCLifetime !=
3826 SCS2.QualificationIncludesObjCLifetime) {
3827 Result = SCS1.QualificationIncludesObjCLifetime
3828 ? ImplicitConversionSequence::Worse
3829 : ImplicitConversionSequence::Better;
3830 }
3831
John McCall5c32be02010-08-24 20:38:10 +00003832 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003833 // Within each iteration of the loop, we check the qualifiers to
3834 // determine if this still looks like a qualification
3835 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003836 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003837 // until there are no more pointers or pointers-to-members left
3838 // to unwrap. This essentially mimics what
3839 // IsQualificationConversion does, but here we're checking for a
3840 // strict subset of qualifiers.
3841 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3842 // The qualifiers are the same, so this doesn't tell us anything
3843 // about how the sequences rank.
3844 ;
3845 else if (T2.isMoreQualifiedThan(T1)) {
3846 // T1 has fewer qualifiers, so it could be the better sequence.
3847 if (Result == ImplicitConversionSequence::Worse)
3848 // Neither has qualifiers that are a subset of the other's
3849 // qualifiers.
3850 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003851
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003852 Result = ImplicitConversionSequence::Better;
3853 } else if (T1.isMoreQualifiedThan(T2)) {
3854 // T2 has fewer qualifiers, so it could be the better sequence.
3855 if (Result == ImplicitConversionSequence::Better)
3856 // Neither has qualifiers that are a subset of the other's
3857 // qualifiers.
3858 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003859
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003860 Result = ImplicitConversionSequence::Worse;
3861 } else {
3862 // Qualifiers are disjoint.
3863 return ImplicitConversionSequence::Indistinguishable;
3864 }
3865
3866 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003867 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003868 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003869 }
3870
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003871 // Check that the winning standard conversion sequence isn't using
3872 // the deprecated string literal array to pointer conversion.
3873 switch (Result) {
3874 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003875 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003876 Result = ImplicitConversionSequence::Indistinguishable;
3877 break;
3878
3879 case ImplicitConversionSequence::Indistinguishable:
3880 break;
3881
3882 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003883 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003884 Result = ImplicitConversionSequence::Indistinguishable;
3885 break;
3886 }
3887
3888 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003889}
3890
Douglas Gregor5c407d92008-10-23 00:40:37 +00003891/// CompareDerivedToBaseConversions - Compares two standard conversion
3892/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003893/// various kinds of derived-to-base conversions (C++
3894/// [over.ics.rank]p4b3). As part of these checks, we also look at
3895/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003896static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003897CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003898 const StandardConversionSequence& SCS1,
3899 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003900 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003901 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003902 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003903 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003904
3905 // Adjust the types we're converting from via the array-to-pointer
3906 // conversion, if we need to.
3907 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003908 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003909 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003910 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003911
3912 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003913 FromType1 = S.Context.getCanonicalType(FromType1);
3914 ToType1 = S.Context.getCanonicalType(ToType1);
3915 FromType2 = S.Context.getCanonicalType(FromType2);
3916 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003917
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003918 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003919 //
3920 // If class B is derived directly or indirectly from class A and
3921 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003922 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003923 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003924 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003925 SCS2.Second == ICK_Pointer_Conversion &&
3926 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3927 FromType1->isPointerType() && FromType2->isPointerType() &&
3928 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003929 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003930 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003931 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003932 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003933 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003934 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003935 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003936 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003937
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003938 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003939 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003940 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003941 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003942 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003943 return ImplicitConversionSequence::Worse;
3944 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003945
3946 // -- conversion of B* to A* is better than conversion of C* to A*,
3947 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003948 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003949 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003950 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003951 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003952 }
3953 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3954 SCS2.Second == ICK_Pointer_Conversion) {
3955 const ObjCObjectPointerType *FromPtr1
3956 = FromType1->getAs<ObjCObjectPointerType>();
3957 const ObjCObjectPointerType *FromPtr2
3958 = FromType2->getAs<ObjCObjectPointerType>();
3959 const ObjCObjectPointerType *ToPtr1
3960 = ToType1->getAs<ObjCObjectPointerType>();
3961 const ObjCObjectPointerType *ToPtr2
3962 = ToType2->getAs<ObjCObjectPointerType>();
3963
3964 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3965 // Apply the same conversion ranking rules for Objective-C pointer types
3966 // that we do for C++ pointers to class types. However, we employ the
3967 // Objective-C pseudo-subtyping relationship used for assignment of
3968 // Objective-C pointer types.
3969 bool FromAssignLeft
3970 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3971 bool FromAssignRight
3972 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3973 bool ToAssignLeft
3974 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3975 bool ToAssignRight
3976 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3977
3978 // A conversion to an a non-id object pointer type or qualified 'id'
3979 // type is better than a conversion to 'id'.
3980 if (ToPtr1->isObjCIdType() &&
3981 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3982 return ImplicitConversionSequence::Worse;
3983 if (ToPtr2->isObjCIdType() &&
3984 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3985 return ImplicitConversionSequence::Better;
3986
3987 // A conversion to a non-id object pointer type is better than a
3988 // conversion to a qualified 'id' type
3989 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3990 return ImplicitConversionSequence::Worse;
3991 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3992 return ImplicitConversionSequence::Better;
3993
3994 // A conversion to an a non-Class object pointer type or qualified 'Class'
3995 // type is better than a conversion to 'Class'.
3996 if (ToPtr1->isObjCClassType() &&
3997 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3998 return ImplicitConversionSequence::Worse;
3999 if (ToPtr2->isObjCClassType() &&
4000 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4001 return ImplicitConversionSequence::Better;
4002
4003 // A conversion to a non-Class object pointer type is better than a
4004 // conversion to a qualified 'Class' type.
4005 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4006 return ImplicitConversionSequence::Worse;
4007 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4008 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004009
Douglas Gregor058d3de2011-01-31 18:51:41 +00004010 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4011 if (S.Context.hasSameType(FromType1, FromType2) &&
4012 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4013 (ToAssignLeft != ToAssignRight))
4014 return ToAssignLeft? ImplicitConversionSequence::Worse
4015 : ImplicitConversionSequence::Better;
4016
4017 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4018 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4019 (FromAssignLeft != FromAssignRight))
4020 return FromAssignLeft? ImplicitConversionSequence::Better
4021 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004022 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004023 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004024
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004025 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004026 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4027 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4028 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004029 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004030 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004032 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004034 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004036 ToType2->getAs<MemberPointerType>();
4037 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4038 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4039 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4040 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4041 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4042 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4043 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4044 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004045 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004046 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004047 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004048 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004049 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004050 return ImplicitConversionSequence::Better;
4051 }
4052 // conversion of B::* to C::* is better than conversion of A::* to C::*
4053 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004054 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004055 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004056 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004057 return ImplicitConversionSequence::Worse;
4058 }
4059 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060
Douglas Gregor5ab11652010-04-17 22:01:05 +00004061 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004062 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004063 // -- binding of an expression of type C to a reference of type
4064 // B& is better than binding an expression of type C to a
4065 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004066 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4067 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004068 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004069 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004070 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004071 return ImplicitConversionSequence::Worse;
4072 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004073
Douglas Gregor2fe98832008-11-03 19:09:14 +00004074 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004075 // -- binding of an expression of type B to a reference of type
4076 // A& is better than binding an expression of type C to a
4077 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004078 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4079 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004080 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004081 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004082 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004083 return ImplicitConversionSequence::Worse;
4084 }
4085 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004086
Douglas Gregor5c407d92008-10-23 00:40:37 +00004087 return ImplicitConversionSequence::Indistinguishable;
4088}
4089
Douglas Gregor45bb4832013-03-26 23:36:30 +00004090/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4091/// C++ class.
4092static bool isTypeValid(QualType T) {
4093 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4094 return !Record->isInvalidDecl();
4095
4096 return true;
4097}
4098
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004099/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4100/// determine whether they are reference-related,
4101/// reference-compatible, reference-compatible with added
4102/// qualification, or incompatible, for use in C++ initialization by
4103/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4104/// type, and the first type (T1) is the pointee type of the reference
4105/// type being initialized.
4106Sema::ReferenceCompareResult
4107Sema::CompareReferenceRelationship(SourceLocation Loc,
4108 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004109 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004110 bool &ObjCConversion,
4111 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004112 assert(!OrigT1->isReferenceType() &&
4113 "T1 must be the pointee type of the reference type");
4114 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4115
4116 QualType T1 = Context.getCanonicalType(OrigT1);
4117 QualType T2 = Context.getCanonicalType(OrigT2);
4118 Qualifiers T1Quals, T2Quals;
4119 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4120 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4121
4122 // C++ [dcl.init.ref]p4:
4123 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4124 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4125 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004126 DerivedToBase = false;
4127 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004128 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004129 if (UnqualT1 == UnqualT2) {
4130 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004131 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004132 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004133 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004134 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004135 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4136 UnqualT2->isObjCObjectOrInterfaceType() &&
4137 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4138 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004139 else
4140 return Ref_Incompatible;
4141
4142 // At this point, we know that T1 and T2 are reference-related (at
4143 // least).
4144
4145 // If the type is an array type, promote the element qualifiers to the type
4146 // for comparison.
4147 if (isa<ArrayType>(T1) && T1Quals)
4148 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4149 if (isa<ArrayType>(T2) && T2Quals)
4150 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4151
4152 // C++ [dcl.init.ref]p4:
4153 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4154 // reference-related to T2 and cv1 is the same cv-qualification
4155 // as, or greater cv-qualification than, cv2. For purposes of
4156 // overload resolution, cases for which cv1 is greater
4157 // cv-qualification than cv2 are identified as
4158 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004159 //
4160 // Note that we also require equivalence of Objective-C GC and address-space
4161 // qualifiers when performing these computations, so that e.g., an int in
4162 // address space 1 is not reference-compatible with an int in address
4163 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004164 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4165 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004166 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4167 ObjCLifetimeConversion = true;
4168
John McCall31168b02011-06-15 23:02:42 +00004169 T1Quals.removeObjCLifetime();
4170 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004171 }
4172
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004173 // MS compiler ignores __unaligned qualifier for references; do the same.
4174 T1Quals.removeUnaligned();
4175 T2Quals.removeUnaligned();
4176
Douglas Gregord517d552011-04-28 17:56:11 +00004177 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004178 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004179 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004180 return Ref_Compatible_With_Added_Qualification;
4181 else
4182 return Ref_Related;
4183}
4184
Douglas Gregor836a7e82010-08-11 02:15:33 +00004185/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004186/// with DeclType. Return true if something definite is found.
4187static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004188FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4189 QualType DeclType, SourceLocation DeclLoc,
4190 Expr *Init, QualType T2, bool AllowRvalues,
4191 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004192 assert(T2->isRecordType() && "Can only find conversions of record types.");
4193 CXXRecordDecl *T2RecordDecl
4194 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4195
Richard Smith100b24a2014-04-17 01:52:14 +00004196 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004197 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4198 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004199 NamedDecl *D = *I;
4200 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4201 if (isa<UsingShadowDecl>(D))
4202 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4203
4204 FunctionTemplateDecl *ConvTemplate
4205 = dyn_cast<FunctionTemplateDecl>(D);
4206 CXXConversionDecl *Conv;
4207 if (ConvTemplate)
4208 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4209 else
4210 Conv = cast<CXXConversionDecl>(D);
4211
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004213 // explicit conversions, skip it.
4214 if (!AllowExplicit && Conv->isExplicit())
4215 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004216
Douglas Gregor836a7e82010-08-11 02:15:33 +00004217 if (AllowRvalues) {
4218 bool DerivedToBase = false;
4219 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004220 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004221
4222 // If we are initializing an rvalue reference, don't permit conversion
4223 // functions that return lvalues.
4224 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4225 const ReferenceType *RefType
4226 = Conv->getConversionType()->getAs<LValueReferenceType>();
4227 if (RefType && !RefType->getPointeeType()->isFunctionType())
4228 continue;
4229 }
4230
Douglas Gregor836a7e82010-08-11 02:15:33 +00004231 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004232 S.CompareReferenceRelationship(
4233 DeclLoc,
4234 Conv->getConversionType().getNonReferenceType()
4235 .getUnqualifiedType(),
4236 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004237 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004238 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004239 continue;
4240 } else {
4241 // If the conversion function doesn't return a reference type,
4242 // it can't be considered for this conversion. An rvalue reference
4243 // is only acceptable if its referencee is a function type.
4244
4245 const ReferenceType *RefType =
4246 Conv->getConversionType()->getAs<ReferenceType>();
4247 if (!RefType ||
4248 (!RefType->isLValueReferenceType() &&
4249 !RefType->getPointeeType()->isFunctionType()))
4250 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004251 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252
Douglas Gregor836a7e82010-08-11 02:15:33 +00004253 if (ConvTemplate)
4254 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004255 Init, DeclType, CandidateSet,
4256 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004257 else
4258 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004259 DeclType, CandidateSet,
4260 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004261 }
4262
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004263 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4264
Sebastian Redld92badf2010-06-30 18:13:39 +00004265 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004266 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004267 case OR_Success:
4268 // C++ [over.ics.ref]p1:
4269 //
4270 // [...] If the parameter binds directly to the result of
4271 // applying a conversion function to the argument
4272 // expression, the implicit conversion sequence is a
4273 // user-defined conversion sequence (13.3.3.1.2), with the
4274 // second standard conversion sequence either an identity
4275 // conversion or, if the conversion function returns an
4276 // entity of a type that is a derived class of the parameter
4277 // type, a derived-to-base Conversion.
4278 if (!Best->FinalConversion.DirectBinding)
4279 return false;
4280
4281 ICS.setUserDefined();
4282 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4283 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004284 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004285 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004286 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004287 ICS.UserDefined.EllipsisConversion = false;
4288 assert(ICS.UserDefined.After.ReferenceBinding &&
4289 ICS.UserDefined.After.DirectBinding &&
4290 "Expected a direct reference binding!");
4291 return true;
4292
4293 case OR_Ambiguous:
4294 ICS.setAmbiguous();
4295 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4296 Cand != CandidateSet.end(); ++Cand)
4297 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004298 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004299 return true;
4300
4301 case OR_No_Viable_Function:
4302 case OR_Deleted:
4303 // There was no suitable conversion, or we found a deleted
4304 // conversion; continue with other checks.
4305 return false;
4306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
David Blaikie8a40f702012-01-17 06:56:22 +00004308 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004309}
4310
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004311/// \brief Compute an implicit conversion sequence for reference
4312/// initialization.
4313static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004314TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004315 SourceLocation DeclLoc,
4316 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004317 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004318 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4319
4320 // Most paths end in a failed conversion.
4321 ImplicitConversionSequence ICS;
4322 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4323
4324 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4325 QualType T2 = Init->getType();
4326
4327 // If the initializer is the address of an overloaded function, try
4328 // to resolve the overloaded function. If all goes well, T2 is the
4329 // type of the resulting function.
4330 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4331 DeclAccessPair Found;
4332 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4333 false, Found))
4334 T2 = Fn->getType();
4335 }
4336
4337 // Compute some basic properties of the types and the initializer.
4338 bool isRValRef = DeclType->isRValueReferenceType();
4339 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004340 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004341 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004342 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004343 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004344 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004345 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004346
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004347
Sebastian Redld92badf2010-06-30 18:13:39 +00004348 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004349 // A reference to type "cv1 T1" is initialized by an expression
4350 // of type "cv2 T2" as follows:
4351
Sebastian Redld92badf2010-06-30 18:13:39 +00004352 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004353 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004354 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4355 // reference-compatible with "cv2 T2," or
4356 //
4357 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4358 if (InitCategory.isLValue() &&
4359 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004360 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004361 // When a parameter of reference type binds directly (8.5.3)
4362 // to an argument expression, the implicit conversion sequence
4363 // is the identity conversion, unless the argument expression
4364 // has a type that is a derived class of the parameter type,
4365 // in which case the implicit conversion sequence is a
4366 // derived-to-base Conversion (13.3.3.1).
4367 ICS.setStandard();
4368 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004369 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4370 : ObjCConversion? ICK_Compatible_Conversion
4371 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004372 ICS.Standard.Third = ICK_Identity;
4373 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4374 ICS.Standard.setToType(0, T2);
4375 ICS.Standard.setToType(1, T1);
4376 ICS.Standard.setToType(2, T1);
4377 ICS.Standard.ReferenceBinding = true;
4378 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004379 ICS.Standard.IsLvalueReference = !isRValRef;
4380 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4381 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004382 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004383 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004384 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004385 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004386
Sebastian Redld92badf2010-06-30 18:13:39 +00004387 // Nothing more to do: the inaccessibility/ambiguity check for
4388 // derived-to-base conversions is suppressed when we're
4389 // computing the implicit conversion sequence (C++
4390 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004391 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004392 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004393
Sebastian Redld92badf2010-06-30 18:13:39 +00004394 // -- has a class type (i.e., T2 is a class type), where T1 is
4395 // not reference-related to T2, and can be implicitly
4396 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4397 // is reference-compatible with "cv3 T3" 92) (this
4398 // conversion is selected by enumerating the applicable
4399 // conversion functions (13.3.1.6) and choosing the best
4400 // one through overload resolution (13.3)),
4401 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004402 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004403 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004404 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4405 Init, T2, /*AllowRvalues=*/false,
4406 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004407 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004408 }
4409 }
4410
Sebastian Redld92badf2010-06-30 18:13:39 +00004411 // -- Otherwise, the reference shall be an lvalue reference to a
4412 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004413 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004414 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004415 return ICS;
4416
Douglas Gregorf143cd52011-01-24 16:14:37 +00004417 // -- If the initializer expression
4418 //
4419 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004420 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004421 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4422 (InitCategory.isXValue() ||
4423 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4424 (InitCategory.isLValue() && T2->isFunctionType()))) {
4425 ICS.setStandard();
4426 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004428 : ObjCConversion? ICK_Compatible_Conversion
4429 : ICK_Identity;
4430 ICS.Standard.Third = ICK_Identity;
4431 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4432 ICS.Standard.setToType(0, T2);
4433 ICS.Standard.setToType(1, T1);
4434 ICS.Standard.setToType(2, T1);
4435 ICS.Standard.ReferenceBinding = true;
4436 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4437 // binding unless we're binding to a class prvalue.
4438 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4439 // allow the use of rvalue references in C++98/03 for the benefit of
4440 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004442 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004443 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004444 ICS.Standard.IsLvalueReference = !isRValRef;
4445 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004447 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004448 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004449 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004450 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453
Douglas Gregorf143cd52011-01-24 16:14:37 +00004454 // -- has a class type (i.e., T2 is a class type), where T1 is not
4455 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456 // an xvalue, class prvalue, or function lvalue of type
4457 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004458 // "cv3 T3",
4459 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004461 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004462 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004463 // class subobject).
4464 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004465 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004466 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4467 Init, T2, /*AllowRvalues=*/true,
4468 AllowExplicit)) {
4469 // In the second case, if the reference is an rvalue reference
4470 // and the second standard conversion sequence of the
4471 // user-defined conversion sequence includes an lvalue-to-rvalue
4472 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004474 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4475 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4476
Douglas Gregor95273c32011-01-21 16:36:05 +00004477 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479
Richard Smith19172c42014-07-14 02:28:44 +00004480 // A temporary of function type cannot be created; don't even try.
4481 if (T1->isFunctionType())
4482 return ICS;
4483
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004484 // -- Otherwise, a temporary of type "cv1 T1" is created and
4485 // initialized from the initializer expression using the
4486 // rules for a non-reference copy initialization (8.5). The
4487 // reference is then bound to the temporary. If T1 is
4488 // reference-related to T2, cv1 must be the same
4489 // cv-qualification as, or greater cv-qualification than,
4490 // cv2; otherwise, the program is ill-formed.
4491 if (RefRelationship == Sema::Ref_Related) {
4492 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4493 // we would be reference-compatible or reference-compatible with
4494 // added qualification. But that wasn't the case, so the reference
4495 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004496 //
4497 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004498 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004499 Qualifiers T1Quals = T1.getQualifiers();
4500 Qualifiers T2Quals = T2.getQualifiers();
4501 T1Quals.removeObjCGCAttr();
4502 T1Quals.removeObjCLifetime();
4503 T2Quals.removeObjCGCAttr();
4504 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004505 // MS compiler ignores __unaligned qualifier for references; do the same.
4506 T1Quals.removeUnaligned();
4507 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004508 if (!T1Quals.compatiblyIncludes(T2Quals))
4509 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004510 }
4511
4512 // If at least one of the types is a class type, the types are not
4513 // related, and we aren't allowed any user conversions, the
4514 // reference binding fails. This case is important for breaking
4515 // recursion, since TryImplicitConversion below will attempt to
4516 // create a temporary through the use of a copy constructor.
4517 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4518 (T1->isRecordType() || T2->isRecordType()))
4519 return ICS;
4520
Douglas Gregorcba72b12011-01-21 05:18:22 +00004521 // If T1 is reference-related to T2 and the reference is an rvalue
4522 // reference, the initializer expression shall not be an lvalue.
4523 if (RefRelationship >= Sema::Ref_Related &&
4524 isRValRef && Init->Classify(S.Context).isLValue())
4525 return ICS;
4526
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004527 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004528 // When a parameter of reference type is not bound directly to
4529 // an argument expression, the conversion sequence is the one
4530 // required to convert the argument expression to the
4531 // underlying type of the reference according to
4532 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4533 // to copy-initializing a temporary of the underlying type with
4534 // the argument expression. Any difference in top-level
4535 // cv-qualification is subsumed by the initialization itself
4536 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004537 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4538 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004539 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004540 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004541 /*AllowObjCWritebackConversion=*/false,
4542 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004543
4544 // Of course, that's still a reference binding.
4545 if (ICS.isStandard()) {
4546 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004547 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004548 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004549 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004550 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004551 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004552 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004553 const ReferenceType *LValRefType =
4554 ICS.UserDefined.ConversionFunction->getReturnType()
4555 ->getAs<LValueReferenceType>();
4556
4557 // C++ [over.ics.ref]p3:
4558 // Except for an implicit object parameter, for which see 13.3.1, a
4559 // standard conversion sequence cannot be formed if it requires [...]
4560 // binding an rvalue reference to an lvalue other than a function
4561 // lvalue.
4562 // Note that the function case is not possible here.
4563 if (DeclType->isRValueReferenceType() && LValRefType) {
4564 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4565 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4566 // reference to an rvalue!
4567 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4568 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004569 }
Richard Smith19172c42014-07-14 02:28:44 +00004570
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004571 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004572 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004573 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4574 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004575 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4576 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004577 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004578
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004579 return ICS;
4580}
4581
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004582static ImplicitConversionSequence
4583TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4584 bool SuppressUserConversions,
4585 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004586 bool AllowObjCWritebackConversion,
4587 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004588
4589/// TryListConversion - Try to copy-initialize a value of type ToType from the
4590/// initializer list From.
4591static ImplicitConversionSequence
4592TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4593 bool SuppressUserConversions,
4594 bool InOverloadResolution,
4595 bool AllowObjCWritebackConversion) {
4596 // C++11 [over.ics.list]p1:
4597 // When an argument is an initializer list, it is not an expression and
4598 // special rules apply for converting it to a parameter type.
4599
4600 ImplicitConversionSequence Result;
4601 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4602
Sebastian Redl09edce02012-01-23 22:09:39 +00004603 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004604 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004605 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004606 return Result;
4607
Larisse Voufo19d08672015-01-27 18:47:05 +00004608 // Per DR1467:
4609 // If the parameter type is a class X and the initializer list has a single
4610 // element of type cv U, where U is X or a class derived from X, the
4611 // implicit conversion sequence is the one required to convert the element
4612 // to the parameter type.
4613 //
4614 // Otherwise, if the parameter type is a character array [... ]
4615 // and the initializer list has a single element that is an
4616 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4617 // implicit conversion sequence is the identity conversion.
4618 if (From->getNumInits() == 1) {
4619 if (ToType->isRecordType()) {
4620 QualType InitType = From->getInit(0)->getType();
4621 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004622 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004623 return TryCopyInitialization(S, From->getInit(0), ToType,
4624 SuppressUserConversions,
4625 InOverloadResolution,
4626 AllowObjCWritebackConversion);
4627 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004628 // FIXME: Check the other conditions here: array of character type,
4629 // initializer is a string literal.
4630 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004631 InitializedEntity Entity =
4632 InitializedEntity::InitializeParameter(S.Context, ToType,
4633 /*Consumed=*/false);
4634 if (S.CanPerformCopyInitialization(Entity, From)) {
4635 Result.setStandard();
4636 Result.Standard.setAsIdentityConversion();
4637 Result.Standard.setFromType(ToType);
4638 Result.Standard.setAllToTypes(ToType);
4639 return Result;
4640 }
4641 }
4642 }
4643
4644 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004645 // C++11 [over.ics.list]p2:
4646 // If the parameter type is std::initializer_list<X> or "array of X" and
4647 // all the elements can be implicitly converted to X, the implicit
4648 // conversion sequence is the worst conversion necessary to convert an
4649 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004650 //
4651 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004652 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004653 // list has exactly N elements or if it has fewer than N elements and X is
4654 // default-constructible, and if all the elements of the initializer list
4655 // can be implicitly converted to X, the implicit conversion sequence is
4656 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004657 //
4658 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004659 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004660 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004661 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004662 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004663 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004664 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004665 if (!X.isNull()) {
4666 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4667 Expr *Init = From->getInit(i);
4668 ImplicitConversionSequence ICS =
4669 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4670 InOverloadResolution,
4671 AllowObjCWritebackConversion);
4672 // If a single element isn't convertible, fail.
4673 if (ICS.isBad()) {
4674 Result = ICS;
4675 break;
4676 }
4677 // Otherwise, look for the worst conversion.
4678 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004679 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4680 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004681 ImplicitConversionSequence::Worse)
4682 Result = ICS;
4683 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004684
4685 // For an empty list, we won't have computed any conversion sequence.
4686 // Introduce the identity conversion sequence.
4687 if (From->getNumInits() == 0) {
4688 Result.setStandard();
4689 Result.Standard.setAsIdentityConversion();
4690 Result.Standard.setFromType(ToType);
4691 Result.Standard.setAllToTypes(ToType);
4692 }
4693
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004694 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004695 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004696 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004697
Larisse Voufo19d08672015-01-27 18:47:05 +00004698 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004699 // C++11 [over.ics.list]p3:
4700 // Otherwise, if the parameter is a non-aggregate class X and overload
4701 // resolution chooses a single best constructor [...] the implicit
4702 // conversion sequence is a user-defined conversion sequence. If multiple
4703 // constructors are viable but none is better than the others, the
4704 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004705 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4706 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004707 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4708 /*AllowExplicit=*/false,
4709 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004710 AllowObjCWritebackConversion,
4711 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004712 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004713
Larisse Voufo19d08672015-01-27 18:47:05 +00004714 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004715 // C++11 [over.ics.list]p4:
4716 // Otherwise, if the parameter has an aggregate type which can be
4717 // initialized from the initializer list [...] the implicit conversion
4718 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004719 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004720 // Type is an aggregate, argument is an init list. At this point it comes
4721 // down to checking whether the initialization works.
4722 // FIXME: Find out whether this parameter is consumed or not.
4723 InitializedEntity Entity =
4724 InitializedEntity::InitializeParameter(S.Context, ToType,
4725 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004726 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004727 Result.setUserDefined();
4728 Result.UserDefined.Before.setAsIdentityConversion();
4729 // Initializer lists don't have a type.
4730 Result.UserDefined.Before.setFromType(QualType());
4731 Result.UserDefined.Before.setAllToTypes(QualType());
4732
4733 Result.UserDefined.After.setAsIdentityConversion();
4734 Result.UserDefined.After.setFromType(ToType);
4735 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004736 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004737 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004738 return Result;
4739 }
4740
Larisse Voufo19d08672015-01-27 18:47:05 +00004741 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004742 // C++11 [over.ics.list]p5:
4743 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004744 if (ToType->isReferenceType()) {
4745 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4746 // mention initializer lists in any way. So we go by what list-
4747 // initialization would do and try to extrapolate from that.
4748
4749 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4750
4751 // If the initializer list has a single element that is reference-related
4752 // to the parameter type, we initialize the reference from that.
4753 if (From->getNumInits() == 1) {
4754 Expr *Init = From->getInit(0);
4755
4756 QualType T2 = Init->getType();
4757
4758 // If the initializer is the address of an overloaded function, try
4759 // to resolve the overloaded function. If all goes well, T2 is the
4760 // type of the resulting function.
4761 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4762 DeclAccessPair Found;
4763 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4764 Init, ToType, false, Found))
4765 T2 = Fn->getType();
4766 }
4767
4768 // Compute some basic properties of the types and the initializer.
4769 bool dummy1 = false;
4770 bool dummy2 = false;
4771 bool dummy3 = false;
4772 Sema::ReferenceCompareResult RefRelationship
4773 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4774 dummy2, dummy3);
4775
Richard Smith4d2bbd72013-09-06 01:22:42 +00004776 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004777 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4778 SuppressUserConversions,
4779 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004780 }
Sebastian Redldf888642011-12-03 14:54:30 +00004781 }
4782
4783 // Otherwise, we bind the reference to a temporary created from the
4784 // initializer list.
4785 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4786 InOverloadResolution,
4787 AllowObjCWritebackConversion);
4788 if (Result.isFailure())
4789 return Result;
4790 assert(!Result.isEllipsis() &&
4791 "Sub-initialization cannot result in ellipsis conversion.");
4792
4793 // Can we even bind to a temporary?
4794 if (ToType->isRValueReferenceType() ||
4795 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4796 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4797 Result.UserDefined.After;
4798 SCS.ReferenceBinding = true;
4799 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4800 SCS.BindsToRvalue = true;
4801 SCS.BindsToFunctionLvalue = false;
4802 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4803 SCS.ObjCLifetimeConversionBinding = false;
4804 } else
4805 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4806 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004807 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004808 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004809
Larisse Voufo19d08672015-01-27 18:47:05 +00004810 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004811 // C++11 [over.ics.list]p6:
4812 // Otherwise, if the parameter type is not a class:
4813 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004814 // - if the initializer list has one element that is not itself an
4815 // initializer list, the implicit conversion sequence is the one
4816 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004817 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004818 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004819 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4820 SuppressUserConversions,
4821 InOverloadResolution,
4822 AllowObjCWritebackConversion);
4823 // - if the initializer list has no elements, the implicit conversion
4824 // sequence is the identity conversion.
4825 else if (NumInits == 0) {
4826 Result.setStandard();
4827 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004828 Result.Standard.setFromType(ToType);
4829 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004830 }
4831 return Result;
4832 }
4833
Larisse Voufo19d08672015-01-27 18:47:05 +00004834 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004835 // C++11 [over.ics.list]p7:
4836 // In all cases other than those enumerated above, no conversion is possible
4837 return Result;
4838}
4839
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004840/// TryCopyInitialization - Try to copy-initialize a value of type
4841/// ToType from the expression From. Return the implicit conversion
4842/// sequence required to pass this argument, which may be a bad
4843/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004844/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004845/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004846static ImplicitConversionSequence
4847TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004849 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004850 bool AllowObjCWritebackConversion,
4851 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004852 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4853 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4854 InOverloadResolution,AllowObjCWritebackConversion);
4855
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004856 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004857 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004858 /*FIXME:*/From->getLocStart(),
4859 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004860 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004861
John McCall5c32be02010-08-24 20:38:10 +00004862 return TryImplicitConversion(S, From, ToType,
4863 SuppressUserConversions,
4864 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004865 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004866 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004867 AllowObjCWritebackConversion,
4868 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004869}
4870
Anna Zaks1b068122011-07-28 19:46:48 +00004871static bool TryCopyInitialization(const CanQualType FromQTy,
4872 const CanQualType ToQTy,
4873 Sema &S,
4874 SourceLocation Loc,
4875 ExprValueKind FromVK) {
4876 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4877 ImplicitConversionSequence ICS =
4878 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4879
4880 return !ICS.isBad();
4881}
4882
Douglas Gregor436424c2008-11-18 23:14:02 +00004883/// TryObjectArgumentInitialization - Try to initialize the object
4884/// parameter of the given member function (@c Method) from the
4885/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004886static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004887TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004888 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004889 CXXMethodDecl *Method,
4890 CXXRecordDecl *ActingContext) {
4891 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004892 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4893 // const volatile object.
4894 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4895 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004896 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004897
4898 // Set up the conversion sequence as a "bad" conversion, to allow us
4899 // to exit early.
4900 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004901
4902 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004903 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004904 FromType = PT->getPointeeType();
4905
Douglas Gregor02824322011-01-26 19:30:28 +00004906 // When we had a pointer, it's implicitly dereferenced, so we
4907 // better have an lvalue.
4908 assert(FromClassification.isLValue());
4909 }
4910
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004911 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004912
Douglas Gregor02824322011-01-26 19:30:28 +00004913 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004915 // parameter is
4916 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004917 // - "lvalue reference to cv X" for functions declared without a
4918 // ref-qualifier or with the & ref-qualifier
4919 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004920 // ref-qualifier
4921 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004923 // cv-qualification on the member function declaration.
4924 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004926 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004927 // (C++ [over.match.funcs]p5). We perform a simplified version of
4928 // reference binding here, that allows class rvalues to bind to
4929 // non-constant references.
4930
Douglas Gregor02824322011-01-26 19:30:28 +00004931 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004932 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004934 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004935 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004936 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004937 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004938 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004939 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004940
4941 // Check that we have either the same type or a derived type. It
4942 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004943 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004944 ImplicitConversionKind SecondKind;
4945 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4946 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004947 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004948 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004949 else {
John McCall65eb8792010-02-25 01:37:24 +00004950 ICS.setBad(BadConversionSequence::unrelated_class,
4951 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004952 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004953 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004954
Douglas Gregor02824322011-01-26 19:30:28 +00004955 // Check the ref-qualifier.
4956 switch (Method->getRefQualifier()) {
4957 case RQ_None:
4958 // Do nothing; we don't care about lvalueness or rvalueness.
4959 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960
Douglas Gregor02824322011-01-26 19:30:28 +00004961 case RQ_LValue:
4962 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4963 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004964 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004965 ImplicitParamType);
4966 return ICS;
4967 }
4968 break;
4969
4970 case RQ_RValue:
4971 if (!FromClassification.isRValue()) {
4972 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004974 ImplicitParamType);
4975 return ICS;
4976 }
4977 break;
4978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979
Douglas Gregor436424c2008-11-18 23:14:02 +00004980 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004981 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004982 ICS.Standard.setAsIdentityConversion();
4983 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004984 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004985 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004986 ICS.Standard.ReferenceBinding = true;
4987 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004989 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004990 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4991 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4992 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004993 return ICS;
4994}
4995
4996/// PerformObjectArgumentInitialization - Perform initialization of
4997/// the implicit object parameter for the given Method with the given
4998/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004999ExprResult
5000Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005002 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005003 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005004 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005005 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005006 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005007
Douglas Gregor02824322011-01-26 19:30:28 +00005008 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005009 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005010 FromRecordType = PT->getPointeeType();
5011 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005012 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005013 } else {
5014 FromRecordType = From->getType();
5015 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005016 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005017 }
5018
John McCall6e9f8f62009-12-03 04:06:58 +00005019 // Note that we always use the true parent context when performing
5020 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005021 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005022 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5023 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005024 if (ICS.isBad()) {
5025 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5026 Qualifiers FromQs = FromRecordType.getQualifiers();
5027 Qualifiers ToQs = DestType.getQualifiers();
5028 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5029 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005030 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005031 diag::err_member_function_call_bad_cvr)
5032 << Method->getDeclName() << FromRecordType << (CVR - 1)
5033 << From->getSourceRange();
5034 Diag(Method->getLocation(), diag::note_previous_decl)
5035 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005036 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005037 }
5038 }
5039
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005040 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005041 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005042 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005043 }
Mike Stump11289f42009-09-09 15:08:12 +00005044
John Wiegley01296292011-04-08 18:41:53 +00005045 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5046 ExprResult FromRes =
5047 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5048 if (FromRes.isInvalid())
5049 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005050 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005051 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005052
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005053 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005054 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005055 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005056 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005057}
5058
Douglas Gregor5fb53972009-01-14 15:45:31 +00005059/// TryContextuallyConvertToBool - Attempt to contextually convert the
5060/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005061static ImplicitConversionSequence
5062TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005063 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005064 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005065 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005066 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005067 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005068 /*AllowObjCWritebackConversion=*/false,
5069 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005070}
5071
5072/// PerformContextuallyConvertToBool - Perform a contextual conversion
5073/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005074ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005075 if (checkPlaceholderForOverload(*this, From))
5076 return ExprError();
5077
John McCall5c32be02010-08-24 20:38:10 +00005078 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005079 if (!ICS.isBad())
5080 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081
Fariborz Jahanian76197412009-11-18 18:26:29 +00005082 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005083 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005084 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005085 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005086 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005087}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088
Richard Smithf8379a02012-01-18 23:55:52 +00005089/// Check that the specified conversion is permitted in a converted constant
5090/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5091/// is acceptable.
5092static bool CheckConvertedConstantConversions(Sema &S,
5093 StandardConversionSequence &SCS) {
5094 // Since we know that the target type is an integral or unscoped enumeration
5095 // type, most conversion kinds are impossible. All possible First and Third
5096 // conversions are fine.
5097 switch (SCS.Second) {
5098 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005099 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005100 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005101 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005102 return true;
5103
5104 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005105 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005106 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5107 // conversion, so we allow it in a converted constant expression.
5108 //
5109 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5110 // a lot of popular code. We should at least add a warning for this
5111 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005112 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5113 SCS.getToType(2)->isBooleanType();
5114
Richard Smith410cc892014-11-26 03:26:53 +00005115 case ICK_Pointer_Conversion:
5116 case ICK_Pointer_Member:
5117 // C++1z: null pointer conversions and null member pointer conversions are
5118 // only permitted if the source type is std::nullptr_t.
5119 return SCS.getFromType()->isNullPtrType();
5120
5121 case ICK_Floating_Promotion:
5122 case ICK_Complex_Promotion:
5123 case ICK_Floating_Conversion:
5124 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005125 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005126 case ICK_Compatible_Conversion:
5127 case ICK_Derived_To_Base:
5128 case ICK_Vector_Conversion:
5129 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005130 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005131 case ICK_Block_Pointer_Conversion:
5132 case ICK_TransparentUnionConversion:
5133 case ICK_Writeback_Conversion:
5134 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005135 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005136 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005137 return false;
5138
5139 case ICK_Lvalue_To_Rvalue:
5140 case ICK_Array_To_Pointer:
5141 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005142 llvm_unreachable("found a first conversion kind in Second");
5143
Richard Smithf8379a02012-01-18 23:55:52 +00005144 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005145 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005146
5147 case ICK_Num_Conversion_Kinds:
5148 break;
5149 }
5150
5151 llvm_unreachable("unknown conversion kind");
5152}
5153
5154/// CheckConvertedConstantExpression - Check that the expression From is a
5155/// converted constant expression of type T, perform the conversion and produce
5156/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005157static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5158 QualType T, APValue &Value,
5159 Sema::CCEKind CCE,
5160 bool RequireInt) {
5161 assert(S.getLangOpts().CPlusPlus11 &&
5162 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005163
Richard Smith410cc892014-11-26 03:26:53 +00005164 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005165 return ExprError();
5166
Richard Smith410cc892014-11-26 03:26:53 +00005167 // C++1z [expr.const]p3:
5168 // A converted constant expression of type T is an expression,
5169 // implicitly converted to type T, where the converted
5170 // expression is a constant expression and the implicit conversion
5171 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005172 // C++1z [stmt.if]p2:
5173 // If the if statement is of the form if constexpr, the value of the
5174 // condition shall be a contextually converted constant expression of type
5175 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005176 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005177 CCE == Sema::CCEK_ConstexprIf
5178 ? TryContextuallyConvertToBool(S, From)
5179 : TryCopyInitialization(S, From, T,
5180 /*SuppressUserConversions=*/false,
5181 /*InOverloadResolution=*/false,
5182 /*AllowObjcWritebackConversion=*/false,
5183 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005184 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005185 switch (ICS.getKind()) {
5186 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005187 SCS = &ICS.Standard;
5188 break;
5189 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005190 // We are converting to a non-class type, so the Before sequence
5191 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005192 SCS = &ICS.UserDefined.After;
5193 break;
5194 case ImplicitConversionSequence::AmbiguousConversion:
5195 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005196 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5197 return S.Diag(From->getLocStart(),
5198 diag::err_typecheck_converted_constant_expression)
5199 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005200 return ExprError();
5201
5202 case ImplicitConversionSequence::EllipsisConversion:
5203 llvm_unreachable("ellipsis conversion in converted constant expression");
5204 }
5205
Richard Smith410cc892014-11-26 03:26:53 +00005206 // Check that we would only use permitted conversions.
5207 if (!CheckConvertedConstantConversions(S, *SCS)) {
5208 return S.Diag(From->getLocStart(),
5209 diag::err_typecheck_converted_constant_expression_disallowed)
5210 << From->getType() << From->getSourceRange() << T;
5211 }
5212 // [...] and where the reference binding (if any) binds directly.
5213 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5214 return S.Diag(From->getLocStart(),
5215 diag::err_typecheck_converted_constant_expression_indirect)
5216 << From->getType() << From->getSourceRange() << T;
5217 }
5218
5219 ExprResult Result =
5220 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005221 if (Result.isInvalid())
5222 return Result;
5223
5224 // Check for a narrowing implicit conversion.
5225 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005226 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005227 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005228 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005229 case NK_Variable_Narrowing:
5230 // Implicit conversion to a narrower type, and the value is not a constant
5231 // expression. We'll diagnose this in a moment.
5232 case NK_Not_Narrowing:
5233 break;
5234
5235 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005236 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005237 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005238 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005239 break;
5240
5241 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005242 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005243 << CCE << /*Constant*/0 << From->getType() << T;
5244 break;
5245 }
5246
5247 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005248 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005249 Expr::EvalResult Eval;
5250 Eval.Diag = &Notes;
5251
Richard Smith410cc892014-11-26 03:26:53 +00005252 if ((T->isReferenceType()
5253 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5254 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5255 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005256 // The expression can't be folded, so we can't keep it at this position in
5257 // the AST.
5258 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005259 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005260 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005261
5262 if (Notes.empty()) {
5263 // It's a constant expression.
5264 return Result;
5265 }
Richard Smithf8379a02012-01-18 23:55:52 +00005266 }
5267
5268 // It's not a constant expression. Produce an appropriate diagnostic.
5269 if (Notes.size() == 1 &&
5270 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005271 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005272 else {
Richard Smith410cc892014-11-26 03:26:53 +00005273 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005274 << CCE << From->getSourceRange();
5275 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005276 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005277 }
Richard Smith410cc892014-11-26 03:26:53 +00005278 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005279}
5280
Richard Smith410cc892014-11-26 03:26:53 +00005281ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5282 APValue &Value, CCEKind CCE) {
5283 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5284}
5285
5286ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5287 llvm::APSInt &Value,
5288 CCEKind CCE) {
5289 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5290
5291 APValue V;
5292 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5293 if (!R.isInvalid())
5294 Value = V.getInt();
5295 return R;
5296}
5297
5298
John McCallfec112d2011-09-09 06:11:02 +00005299/// dropPointerConversions - If the given standard conversion sequence
5300/// involves any pointer conversions, remove them. This may change
5301/// the result type of the conversion sequence.
5302static void dropPointerConversion(StandardConversionSequence &SCS) {
5303 if (SCS.Second == ICK_Pointer_Conversion) {
5304 SCS.Second = ICK_Identity;
5305 SCS.Third = ICK_Identity;
5306 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5307 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005308}
John McCall5c32be02010-08-24 20:38:10 +00005309
John McCallfec112d2011-09-09 06:11:02 +00005310/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5311/// convert the expression From to an Objective-C pointer type.
5312static ImplicitConversionSequence
5313TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5314 // Do an implicit conversion to 'id'.
5315 QualType Ty = S.Context.getObjCIdType();
5316 ImplicitConversionSequence ICS
5317 = TryImplicitConversion(S, From, Ty,
5318 // FIXME: Are these flags correct?
5319 /*SuppressUserConversions=*/false,
5320 /*AllowExplicit=*/true,
5321 /*InOverloadResolution=*/false,
5322 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005323 /*AllowObjCWritebackConversion=*/false,
5324 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005325
5326 // Strip off any final conversions to 'id'.
5327 switch (ICS.getKind()) {
5328 case ImplicitConversionSequence::BadConversion:
5329 case ImplicitConversionSequence::AmbiguousConversion:
5330 case ImplicitConversionSequence::EllipsisConversion:
5331 break;
5332
5333 case ImplicitConversionSequence::UserDefinedConversion:
5334 dropPointerConversion(ICS.UserDefined.After);
5335 break;
5336
5337 case ImplicitConversionSequence::StandardConversion:
5338 dropPointerConversion(ICS.Standard);
5339 break;
5340 }
5341
5342 return ICS;
5343}
5344
5345/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5346/// conversion of the expression From to an Objective-C pointer type.
5347ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005348 if (checkPlaceholderForOverload(*this, From))
5349 return ExprError();
5350
John McCall8b07ec22010-05-15 11:32:37 +00005351 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005352 ImplicitConversionSequence ICS =
5353 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005354 if (!ICS.isBad())
5355 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005356 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005357}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005358
Richard Smith8dd34252012-02-04 07:07:42 +00005359/// Determine whether the provided type is an integral type, or an enumeration
5360/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005361bool Sema::ICEConvertDiagnoser::match(QualType T) {
5362 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5363 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005364}
5365
Larisse Voufo236bec22013-06-10 06:50:24 +00005366static ExprResult
5367diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5368 Sema::ContextualImplicitConverter &Converter,
5369 QualType T, UnresolvedSetImpl &ViableConversions) {
5370
5371 if (Converter.Suppress)
5372 return ExprError();
5373
5374 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5375 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5376 CXXConversionDecl *Conv =
5377 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5378 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5379 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5380 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005381 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005382}
5383
5384static bool
5385diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5386 Sema::ContextualImplicitConverter &Converter,
5387 QualType T, bool HadMultipleCandidates,
5388 UnresolvedSetImpl &ExplicitConversions) {
5389 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5390 DeclAccessPair Found = ExplicitConversions[0];
5391 CXXConversionDecl *Conversion =
5392 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5393
5394 // The user probably meant to invoke the given explicit
5395 // conversion; use it.
5396 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5397 std::string TypeStr;
5398 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5399
5400 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5401 << FixItHint::CreateInsertion(From->getLocStart(),
5402 "static_cast<" + TypeStr + ">(")
5403 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005404 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005405 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5406
5407 // If we aren't in a SFINAE context, build a call to the
5408 // explicit conversion function.
5409 if (SemaRef.isSFINAEContext())
5410 return true;
5411
Craig Topperc3ec1492014-05-26 06:22:03 +00005412 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005413 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5414 HadMultipleCandidates);
5415 if (Result.isInvalid())
5416 return true;
5417 // Record usage of conversion in an implicit cast.
5418 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005419 CK_UserDefinedConversion, Result.get(),
5420 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005421 }
5422 return false;
5423}
5424
5425static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5426 Sema::ContextualImplicitConverter &Converter,
5427 QualType T, bool HadMultipleCandidates,
5428 DeclAccessPair &Found) {
5429 CXXConversionDecl *Conversion =
5430 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005431 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005432
5433 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5434 if (!Converter.SuppressConversion) {
5435 if (SemaRef.isSFINAEContext())
5436 return true;
5437
5438 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5439 << From->getSourceRange();
5440 }
5441
5442 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5443 HadMultipleCandidates);
5444 if (Result.isInvalid())
5445 return true;
5446 // Record usage of conversion in an implicit cast.
5447 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005448 CK_UserDefinedConversion, Result.get(),
5449 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005450 return false;
5451}
5452
5453static ExprResult finishContextualImplicitConversion(
5454 Sema &SemaRef, SourceLocation Loc, Expr *From,
5455 Sema::ContextualImplicitConverter &Converter) {
5456 if (!Converter.match(From->getType()) && !Converter.Suppress)
5457 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5458 << From->getSourceRange();
5459
5460 return SemaRef.DefaultLvalueConversion(From);
5461}
5462
5463static void
5464collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5465 UnresolvedSetImpl &ViableConversions,
5466 OverloadCandidateSet &CandidateSet) {
5467 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5468 DeclAccessPair FoundDecl = ViableConversions[I];
5469 NamedDecl *D = FoundDecl.getDecl();
5470 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5471 if (isa<UsingShadowDecl>(D))
5472 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5473
5474 CXXConversionDecl *Conv;
5475 FunctionTemplateDecl *ConvTemplate;
5476 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5477 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5478 else
5479 Conv = cast<CXXConversionDecl>(D);
5480
5481 if (ConvTemplate)
5482 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005483 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5484 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005485 else
5486 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005487 ToType, CandidateSet,
5488 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005489 }
5490}
5491
Richard Smithccc11812013-05-21 19:05:48 +00005492/// \brief Attempt to convert the given expression to a type which is accepted
5493/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005494///
Richard Smithccc11812013-05-21 19:05:48 +00005495/// This routine will attempt to convert an expression of class type to a
5496/// type accepted by the specified converter. In C++11 and before, the class
5497/// must have a single non-explicit conversion function converting to a matching
5498/// type. In C++1y, there can be multiple such conversion functions, but only
5499/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005500///
Douglas Gregor4799d032010-06-30 00:20:43 +00005501/// \param Loc The source location of the construct that requires the
5502/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005503///
James Dennett18348b62012-06-22 08:52:37 +00005504/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005505///
Richard Smithccc11812013-05-21 19:05:48 +00005506/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005507///
Douglas Gregor4799d032010-06-30 00:20:43 +00005508/// \returns The expression, converted to an integral or enumeration type if
5509/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005510ExprResult Sema::PerformContextualImplicitConversion(
5511 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005512 // We can't perform any more checking for type-dependent expressions.
5513 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005514 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005515
Eli Friedman1da70392012-01-26 00:26:18 +00005516 // Process placeholders immediately.
5517 if (From->hasPlaceholderType()) {
5518 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005519 if (result.isInvalid())
5520 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005521 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005522 }
5523
Richard Smithccc11812013-05-21 19:05:48 +00005524 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005525 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005526 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005527 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005528
5529 // FIXME: Check for missing '()' if T is a function type?
5530
Richard Smithccc11812013-05-21 19:05:48 +00005531 // We can only perform contextual implicit conversions on objects of class
5532 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005533 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005534 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005535 if (!Converter.Suppress)
5536 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005537 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005539
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005540 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005541 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005542 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005543 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005544
5545 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005546 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005547
Craig Toppere14c0f82014-03-12 04:55:44 +00005548 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005549 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005550 }
Richard Smithccc11812013-05-21 19:05:48 +00005551 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005552
Richard Smithdb0ac552015-12-18 22:40:25 +00005553 if (Converter.Suppress ? !isCompleteType(Loc, T)
5554 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005555 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005557 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005558 UnresolvedSet<4>
5559 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005560 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005561 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005562 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
Larisse Voufo236bec22013-06-10 06:50:24 +00005564 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005565 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005566
Larisse Voufo236bec22013-06-10 06:50:24 +00005567 // To check that there is only one target type, in C++1y:
5568 QualType ToType;
5569 bool HasUniqueTargetType = true;
5570
5571 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005572 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005573 NamedDecl *D = (*I)->getUnderlyingDecl();
5574 CXXConversionDecl *Conversion;
5575 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5576 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005577 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005578 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5579 else
5580 continue; // C++11 does not consider conversion operator templates(?).
5581 } else
5582 Conversion = cast<CXXConversionDecl>(D);
5583
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005584 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005585 "Conversion operator templates are considered potentially "
5586 "viable in C++1y");
5587
5588 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5589 if (Converter.match(CurToType) || ConvTemplate) {
5590
5591 if (Conversion->isExplicit()) {
5592 // FIXME: For C++1y, do we need this restriction?
5593 // cf. diagnoseNoViableConversion()
5594 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005595 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005596 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005597 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005598 if (ToType.isNull())
5599 ToType = CurToType.getUnqualifiedType();
5600 else if (HasUniqueTargetType &&
5601 (CurToType.getUnqualifiedType() != ToType))
5602 HasUniqueTargetType = false;
5603 }
5604 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005605 }
Richard Smith8dd34252012-02-04 07:07:42 +00005606 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005609 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005610 // C++1y [conv]p6:
5611 // ... An expression e of class type E appearing in such a context
5612 // is said to be contextually implicitly converted to a specified
5613 // type T and is well-formed if and only if e can be implicitly
5614 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005615 // for conversion functions whose return type is cv T or reference to
5616 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005617 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618
Larisse Voufo236bec22013-06-10 06:50:24 +00005619 // If no unique T is found:
5620 if (ToType.isNull()) {
5621 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5622 HadMultipleCandidates,
5623 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005624 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005625 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005627
Larisse Voufo236bec22013-06-10 06:50:24 +00005628 // If more than one unique Ts are found:
5629 if (!HasUniqueTargetType)
5630 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5631 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005632
Larisse Voufo236bec22013-06-10 06:50:24 +00005633 // If one unique T is found:
5634 // First, build a candidate set from the previously recorded
5635 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005636 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005637 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5638 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005639
Larisse Voufo236bec22013-06-10 06:50:24 +00005640 // Then, perform overload resolution over the candidate set.
5641 OverloadCandidateSet::iterator Best;
5642 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5643 case OR_Success: {
5644 // Apply this conversion.
5645 DeclAccessPair Found =
5646 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5647 if (recordConversion(*this, Loc, From, Converter, T,
5648 HadMultipleCandidates, Found))
5649 return ExprError();
5650 break;
5651 }
5652 case OR_Ambiguous:
5653 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5654 ViableConversions);
5655 case OR_No_Viable_Function:
5656 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5657 HadMultipleCandidates,
5658 ExplicitConversions))
5659 return ExprError();
5660 // fall through 'OR_Deleted' case.
5661 case OR_Deleted:
5662 // We'll complain below about a non-integral condition type.
5663 break;
5664 }
5665 } else {
5666 switch (ViableConversions.size()) {
5667 case 0: {
5668 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5669 HadMultipleCandidates,
5670 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005671 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005672
Larisse Voufo236bec22013-06-10 06:50:24 +00005673 // We'll complain below about a non-integral condition type.
5674 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005675 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005676 case 1: {
5677 // Apply this conversion.
5678 DeclAccessPair Found = ViableConversions[0];
5679 if (recordConversion(*this, Loc, From, Converter, T,
5680 HadMultipleCandidates, Found))
5681 return ExprError();
5682 break;
5683 }
5684 default:
5685 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5686 ViableConversions);
5687 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005688 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005689
Larisse Voufo236bec22013-06-10 06:50:24 +00005690 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005691}
5692
Richard Smith100b24a2014-04-17 01:52:14 +00005693/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5694/// an acceptable non-member overloaded operator for a call whose
5695/// arguments have types T1 (and, if non-empty, T2). This routine
5696/// implements the check in C++ [over.match.oper]p3b2 concerning
5697/// enumeration types.
5698static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5699 FunctionDecl *Fn,
5700 ArrayRef<Expr *> Args) {
5701 QualType T1 = Args[0]->getType();
5702 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5703
5704 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5705 return true;
5706
5707 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5708 return true;
5709
5710 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5711 if (Proto->getNumParams() < 1)
5712 return false;
5713
5714 if (T1->isEnumeralType()) {
5715 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5716 if (Context.hasSameUnqualifiedType(T1, ArgType))
5717 return true;
5718 }
5719
5720 if (Proto->getNumParams() < 2)
5721 return false;
5722
5723 if (!T2.isNull() && T2->isEnumeralType()) {
5724 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5725 if (Context.hasSameUnqualifiedType(T2, ArgType))
5726 return true;
5727 }
5728
5729 return false;
5730}
5731
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005732/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005733/// candidate functions, using the given function call arguments. If
5734/// @p SuppressUserConversions, then don't allow user-defined
5735/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005736///
James Dennett2a4d13c2012-06-15 07:13:21 +00005737/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005738/// based on an incomplete set of function arguments. This feature is used by
5739/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005740void
5741Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005742 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005743 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005744 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005745 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005746 bool PartialOverloading,
5747 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005748 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005749 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005750 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005751 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005752 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005753
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005754 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005755 if (!isa<CXXConstructorDecl>(Method)) {
5756 // If we get here, it's because we're calling a member function
5757 // that is named without a member access expression (e.g.,
5758 // "this->f") that was either written explicitly or created
5759 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005760 // function, e.g., X::f(). We use an empty type for the implied
5761 // object argument (C++ [over.call.func]p3), and the acting context
5762 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005763 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005765 Args, CandidateSet, SuppressUserConversions,
5766 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005767 return;
5768 }
5769 // We treat a constructor like a non-member function, since its object
5770 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005771 }
5772
Douglas Gregorff7028a2009-11-13 23:59:09 +00005773 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005774 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005775
Richard Smith100b24a2014-04-17 01:52:14 +00005776 // C++ [over.match.oper]p3:
5777 // if no operand has a class type, only those non-member functions in the
5778 // lookup set that have a first parameter of type T1 or "reference to
5779 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5780 // is a right operand) a second parameter of type T2 or "reference to
5781 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5782 // candidate functions.
5783 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5784 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5785 return;
5786
Richard Smith8b86f2d2013-11-04 01:48:18 +00005787 // C++11 [class.copy]p11: [DR1402]
5788 // A defaulted move constructor that is defined as deleted is ignored by
5789 // overload resolution.
5790 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5791 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5792 Constructor->isMoveConstructor())
5793 return;
5794
Douglas Gregor27381f32009-11-23 12:27:39 +00005795 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005796 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005797
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005798 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005799 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005800 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005801 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005802 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005803 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005804 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005805 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005806
John McCall578a1f82014-12-14 01:46:53 +00005807 if (Constructor) {
5808 // C++ [class.copy]p3:
5809 // A member function template is never instantiated to perform the copy
5810 // of a class object to an object of its class type.
5811 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005812 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005813 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005814 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5815 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005816 Candidate.Viable = false;
5817 Candidate.FailureKind = ovl_fail_illegal_constructor;
5818 return;
5819 }
5820 }
5821
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005822 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005823
5824 // (C++ 13.3.2p2): A candidate function having fewer than m
5825 // parameters is viable only if it has an ellipsis in its parameter
5826 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005827 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005828 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005829 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005830 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005831 return;
5832 }
5833
5834 // (C++ 13.3.2p2): A candidate function having more than m parameters
5835 // is viable only if the (m+1)st parameter has a default argument
5836 // (8.3.6). For the purposes of overload resolution, the
5837 // parameter list is truncated on the right, so that there are
5838 // exactly m parameters.
5839 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005840 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005841 // Not enough arguments.
5842 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005843 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005844 return;
5845 }
5846
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005847 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005848 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005849 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005850 // Skip the check for callers that are implicit members, because in this
5851 // case we may not yet know what the member's target is; the target is
5852 // inferred for the member automatically, based on the bases and fields of
5853 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005854 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005855 Candidate.Viable = false;
5856 Candidate.FailureKind = ovl_fail_bad_target;
5857 return;
5858 }
5859
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005860 // Determine the implicit conversion sequences for each of the
5861 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005862 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005863 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005864 // (C++ 13.3.2p3): for F to be a viable function, there shall
5865 // exist for each argument an implicit conversion sequence
5866 // (13.3.3.1) that converts that argument to the corresponding
5867 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005868 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005869 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005870 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005871 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005872 /*InOverloadResolution=*/true,
5873 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005874 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005875 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005876 if (Candidate.Conversions[ArgIdx].isBad()) {
5877 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005878 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005879 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005880 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005881 } else {
5882 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5883 // argument for which there is no corresponding parameter is
5884 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005885 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005886 }
5887 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005888
5889 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5890 Candidate.Viable = false;
5891 Candidate.FailureKind = ovl_fail_enable_if;
5892 Candidate.DeductionFailure.Data = FailedAttr;
5893 return;
5894 }
5895}
5896
Manman Rend2a3cd72016-04-07 19:30:20 +00005897ObjCMethodDecl *
5898Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5899 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5900 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005901 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00005902
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005903 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5904 bool Match = true;
5905 ObjCMethodDecl *Method = Methods[b];
5906 unsigned NumNamedArgs = Sel.getNumArgs();
5907 // Method might have more arguments than selector indicates. This is due
5908 // to addition of c-style arguments in method.
5909 if (Method->param_size() > NumNamedArgs)
5910 NumNamedArgs = Method->param_size();
5911 if (Args.size() < NumNamedArgs)
5912 continue;
5913
5914 for (unsigned i = 0; i < NumNamedArgs; i++) {
5915 // We can't do any type-checking on a type-dependent argument.
5916 if (Args[i]->isTypeDependent()) {
5917 Match = false;
5918 break;
5919 }
5920
5921 ParmVarDecl *param = Method->parameters()[i];
5922 Expr *argExpr = Args[i];
5923 assert(argExpr && "SelectBestMethod(): missing expression");
5924
5925 // Strip the unbridged-cast placeholder expression off unless it's
5926 // a consumed argument.
5927 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5928 !param->hasAttr<CFConsumedAttr>())
5929 argExpr = stripARCUnbridgedCast(argExpr);
5930
5931 // If the parameter is __unknown_anytype, move on to the next method.
5932 if (param->getType() == Context.UnknownAnyTy) {
5933 Match = false;
5934 break;
5935 }
George Burgess IV45461812015-10-11 20:13:20 +00005936
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005937 ImplicitConversionSequence ConversionState
5938 = TryCopyInitialization(*this, argExpr, param->getType(),
5939 /*SuppressUserConversions*/false,
5940 /*InOverloadResolution=*/true,
5941 /*AllowObjCWritebackConversion=*/
5942 getLangOpts().ObjCAutoRefCount,
5943 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00005944 // This function looks for a reasonably-exact match, so we consider
5945 // incompatible pointer conversions to be a failure here.
5946 if (ConversionState.isBad() ||
5947 (ConversionState.isStandard() &&
5948 ConversionState.Standard.Second ==
5949 ICK_Incompatible_Pointer_Conversion)) {
5950 Match = false;
5951 break;
5952 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005953 }
5954 // Promote additional arguments to variadic methods.
5955 if (Match && Method->isVariadic()) {
5956 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5957 if (Args[i]->isTypeDependent()) {
5958 Match = false;
5959 break;
5960 }
5961 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5962 nullptr);
5963 if (Arg.isInvalid()) {
5964 Match = false;
5965 break;
5966 }
5967 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005968 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005969 // Check for extra arguments to non-variadic methods.
5970 if (Args.size() != NumNamedArgs)
5971 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005972 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5973 // Special case when selectors have no argument. In this case, select
5974 // one with the most general result type of 'id'.
5975 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5976 QualType ReturnT = Methods[b]->getReturnType();
5977 if (ReturnT->isObjCIdType())
5978 return Methods[b];
5979 }
5980 }
5981 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005982
5983 if (Match)
5984 return Method;
5985 }
5986 return nullptr;
5987}
5988
George Burgess IV2a6150d2015-10-16 01:17:38 +00005989// specific_attr_iterator iterates over enable_if attributes in reverse, and
5990// enable_if is order-sensitive. As a result, we need to reverse things
5991// sometimes. Size of 4 elements is arbitrary.
5992static SmallVector<EnableIfAttr *, 4>
5993getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5994 SmallVector<EnableIfAttr *, 4> Result;
5995 if (!Function->hasAttrs())
5996 return Result;
5997
5998 const auto &FuncAttrs = Function->getAttrs();
5999 for (Attr *Attr : FuncAttrs)
6000 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6001 Result.push_back(EnableIf);
6002
6003 std::reverse(Result.begin(), Result.end());
6004 return Result;
6005}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006006
6007EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6008 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00006009 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6010 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00006011 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006012
6013 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006014 SmallVector<Expr *, 16> ConvertedArgs;
6015 bool InitializationFailed = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006016
George Burgess IV458b3f32016-08-12 04:19:35 +00006017 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV53b938d2016-08-12 04:12:31 +00006018 // user can't refer to them in the enable_if condition.
6019 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6020
Nick Lewyckye283c552015-08-25 22:33:16 +00006021 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006022 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006023 ExprResult R;
6024 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00006025 !cast<CXXMethodDecl>(Function)->isStatic() &&
6026 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006027 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00006028 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6029 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006030 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00006031 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6032 Context, Function->getParamDecl(I)),
6033 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006034 }
George Burgess IVe96abf72016-02-24 22:31:14 +00006035
6036 if (R.isInvalid()) {
6037 InitializationFailed = true;
6038 break;
6039 }
6040
George Burgess IVe96abf72016-02-24 22:31:14 +00006041 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006042 }
6043
6044 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006045 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006046
Nick Lewyckye283c552015-08-25 22:33:16 +00006047 // Push default arguments if needed.
6048 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6049 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6050 ParmVarDecl *P = Function->getParamDecl(i);
6051 ExprResult R = PerformCopyInitialization(
6052 InitializedEntity::InitializeParameter(Context,
6053 Function->getParamDecl(i)),
6054 SourceLocation(),
6055 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6056 : P->getDefaultArg());
6057 if (R.isInvalid()) {
6058 InitializationFailed = true;
6059 break;
6060 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006061 ConvertedArgs.push_back(R.get());
6062 }
6063
6064 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006065 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006066 }
6067
George Burgess IV2a6150d2015-10-16 01:17:38 +00006068 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006069 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006070 // FIXME: This doesn't consider value-dependent cases, because doing so is
6071 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006072 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006073 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006074 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006075
6076 if (!Result.isInt() || !Result.getInt().getBoolValue())
6077 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006078 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006079 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006080}
6081
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006082/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006083/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006084void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006085 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006086 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006087 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006088 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006089 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006090 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006091 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6092 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006093 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006094 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006095 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006096 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006097 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006098 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006099 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006100 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006101 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006102 } else {
John McCalla0296f72010-03-19 07:35:19 +00006103 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006104 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6105 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006106 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006107 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006108 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006109 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006110 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006111 CandidateSet, SuppressUserConversions,
6112 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006113 else
John McCalla0296f72010-03-19 07:35:19 +00006114 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006115 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006116 CandidateSet, SuppressUserConversions,
6117 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006118 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006119 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006120}
6121
John McCallf0f1cf02009-11-17 07:50:12 +00006122/// AddMethodCandidate - Adds a named decl (which is some kind of
6123/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006124void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006125 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006126 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006127 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006128 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006129 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006130 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006131 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006132
6133 if (isa<UsingShadowDecl>(Decl))
6134 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006135
John McCallf0f1cf02009-11-17 07:50:12 +00006136 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6137 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6138 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006139 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006140 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006141 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006142 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006143 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006144 } else {
John McCalla0296f72010-03-19 07:35:19 +00006145 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006146 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006147 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006148 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006149 }
6150}
6151
Douglas Gregor436424c2008-11-18 23:14:02 +00006152/// AddMethodCandidate - Adds the given C++ member function to the set
6153/// of candidate functions, using the given function call arguments
6154/// and the object argument (@c Object). For example, in a call
6155/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6156/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6157/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006158/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006159void
John McCalla0296f72010-03-19 07:35:19 +00006160Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006161 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006162 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006163 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006164 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006165 bool SuppressUserConversions,
6166 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006167 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006168 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006169 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006170 assert(!isa<CXXConstructorDecl>(Method) &&
6171 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006172
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006173 if (!CandidateSet.isNewCandidate(Method))
6174 return;
6175
Richard Smith8b86f2d2013-11-04 01:48:18 +00006176 // C++11 [class.copy]p23: [DR1402]
6177 // A defaulted move assignment operator that is defined as deleted is
6178 // ignored by overload resolution.
6179 if (Method->isDefaulted() && Method->isDeleted() &&
6180 Method->isMoveAssignmentOperator())
6181 return;
6182
Douglas Gregor27381f32009-11-23 12:27:39 +00006183 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006184 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006185
Douglas Gregor436424c2008-11-18 23:14:02 +00006186 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006187 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006188 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006189 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006190 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006191 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006192 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006193
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006194 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006195
6196 // (C++ 13.3.2p2): A candidate function having fewer than m
6197 // parameters is viable only if it has an ellipsis in its parameter
6198 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006199 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6200 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006201 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006202 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006203 return;
6204 }
6205
6206 // (C++ 13.3.2p2): A candidate function having more than m parameters
6207 // is viable only if the (m+1)st parameter has a default argument
6208 // (8.3.6). For the purposes of overload resolution, the
6209 // parameter list is truncated on the right, so that there are
6210 // exactly m parameters.
6211 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006212 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006213 // Not enough arguments.
6214 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006215 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006216 return;
6217 }
6218
6219 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006220
John McCall6e9f8f62009-12-03 04:06:58 +00006221 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006222 // The implicit object argument is ignored.
6223 Candidate.IgnoreObjectArgument = true;
6224 else {
6225 // Determine the implicit conversion sequence for the object
6226 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006227 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6228 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6229 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006230 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006231 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006232 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006233 return;
6234 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006235 }
6236
Eli Bendersky291a57e2014-09-25 23:59:08 +00006237 // (CUDA B.1): Check for invalid calls between targets.
6238 if (getLangOpts().CUDA)
6239 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006240 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006241 Candidate.Viable = false;
6242 Candidate.FailureKind = ovl_fail_bad_target;
6243 return;
6244 }
6245
Douglas Gregor436424c2008-11-18 23:14:02 +00006246 // Determine the implicit conversion sequences for each of the
6247 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006248 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006249 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006250 // (C++ 13.3.2p3): for F to be a viable function, there shall
6251 // exist for each argument an implicit conversion sequence
6252 // (13.3.3.1) that converts that argument to the corresponding
6253 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006254 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006255 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006256 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006257 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006258 /*InOverloadResolution=*/true,
6259 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006260 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006261 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006262 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006263 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006264 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006265 }
6266 } else {
6267 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6268 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006269 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006270 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006271 }
6272 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006273
6274 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6275 Candidate.Viable = false;
6276 Candidate.FailureKind = ovl_fail_enable_if;
6277 Candidate.DeductionFailure.Data = FailedAttr;
6278 return;
6279 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006280}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006281
Douglas Gregor97628d62009-08-21 00:16:32 +00006282/// \brief Add a C++ member function template as a candidate to the candidate
6283/// set, using template argument deduction to produce an appropriate member
6284/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006285void
Douglas Gregor97628d62009-08-21 00:16:32 +00006286Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006287 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006288 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006289 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006290 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006291 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006292 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006293 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006294 bool SuppressUserConversions,
6295 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006296 if (!CandidateSet.isNewCandidate(MethodTmpl))
6297 return;
6298
Douglas Gregor97628d62009-08-21 00:16:32 +00006299 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006300 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006301 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006302 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006303 // candidate functions in the usual way.113) A given name can refer to one
6304 // or more function templates and also to a set of overloaded non-template
6305 // functions. In such a case, the candidate functions generated from each
6306 // function template are combined with the set of non-template candidate
6307 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006308 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006309 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006310 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006311 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006312 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006313 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006314 Candidate.FoundDecl = FoundDecl;
6315 Candidate.Function = MethodTmpl->getTemplatedDecl();
6316 Candidate.Viable = false;
6317 Candidate.FailureKind = ovl_fail_bad_deduction;
6318 Candidate.IsSurrogate = false;
6319 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006320 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006321 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006322 Info);
6323 return;
6324 }
Mike Stump11289f42009-09-09 15:08:12 +00006325
Douglas Gregor97628d62009-08-21 00:16:32 +00006326 // Add the function template specialization produced by template argument
6327 // deduction as a candidate.
6328 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006329 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006330 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006331 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006332 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006333 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006334}
6335
Douglas Gregor05155d82009-08-21 23:19:43 +00006336/// \brief Add a C++ function template specialization as a candidate
6337/// in the candidate set, using template argument deduction to produce
6338/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006339void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006340Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006341 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006342 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006343 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006344 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006345 bool SuppressUserConversions,
6346 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006347 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6348 return;
6349
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006350 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006351 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006352 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006353 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006354 // candidate functions in the usual way.113) A given name can refer to one
6355 // or more function templates and also to a set of overloaded non-template
6356 // functions. In such a case, the candidate functions generated from each
6357 // function template are combined with the set of non-template candidate
6358 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006359 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006360 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006361 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006362 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006363 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006364 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006365 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006366 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6367 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006368 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006369 Candidate.IsSurrogate = false;
6370 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006371 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006372 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006373 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006374 return;
6375 }
Mike Stump11289f42009-09-09 15:08:12 +00006376
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006377 // Add the function template specialization produced by template argument
6378 // deduction as a candidate.
6379 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006380 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006381 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006382}
Mike Stump11289f42009-09-09 15:08:12 +00006383
Douglas Gregor4b60a152013-11-07 22:34:54 +00006384/// Determine whether this is an allowable conversion from the result
6385/// of an explicit conversion operator to the expected type, per C++
6386/// [over.match.conv]p1 and [over.match.ref]p1.
6387///
6388/// \param ConvType The return type of the conversion function.
6389///
6390/// \param ToType The type we are converting to.
6391///
6392/// \param AllowObjCPointerConversion Allow a conversion from one
6393/// Objective-C pointer to another.
6394///
6395/// \returns true if the conversion is allowable, false otherwise.
6396static bool isAllowableExplicitConversion(Sema &S,
6397 QualType ConvType, QualType ToType,
6398 bool AllowObjCPointerConversion) {
6399 QualType ToNonRefType = ToType.getNonReferenceType();
6400
6401 // Easy case: the types are the same.
6402 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6403 return true;
6404
6405 // Allow qualification conversions.
6406 bool ObjCLifetimeConversion;
6407 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6408 ObjCLifetimeConversion))
6409 return true;
6410
6411 // If we're not allowed to consider Objective-C pointer conversions,
6412 // we're done.
6413 if (!AllowObjCPointerConversion)
6414 return false;
6415
6416 // Is this an Objective-C pointer conversion?
6417 bool IncompatibleObjC = false;
6418 QualType ConvertedType;
6419 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6420 IncompatibleObjC);
6421}
6422
Douglas Gregora1f013e2008-11-07 22:36:19 +00006423/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006424/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006425/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006426/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006427/// (which may or may not be the same type as the type that the
6428/// conversion function produces).
6429void
6430Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006431 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006432 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006433 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006434 OverloadCandidateSet& CandidateSet,
6435 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006436 assert(!Conversion->getDescribedFunctionTemplate() &&
6437 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006438 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006439 if (!CandidateSet.isNewCandidate(Conversion))
6440 return;
6441
Richard Smith2a7d4812013-05-04 07:00:32 +00006442 // If the conversion function has an undeduced return type, trigger its
6443 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006444 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006445 if (DeduceReturnType(Conversion, From->getExprLoc()))
6446 return;
6447 ConvType = Conversion->getConversionType().getNonReferenceType();
6448 }
6449
Richard Smith089c3162013-09-21 21:55:46 +00006450 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6451 // operator is only a candidate if its return type is the target type or
6452 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006453 if (Conversion->isExplicit() &&
6454 !isAllowableExplicitConversion(*this, ConvType, ToType,
6455 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006456 return;
6457
Douglas Gregor27381f32009-11-23 12:27:39 +00006458 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006459 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006460
Douglas Gregora1f013e2008-11-07 22:36:19 +00006461 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006462 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006463 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006464 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006465 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006466 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006467 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006468 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006469 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006470 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006471 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006472
Douglas Gregor6affc782010-08-19 15:37:02 +00006473 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006474 // For conversion functions, the function is considered to be a member of
6475 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006476 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006477 //
6478 // Determine the implicit conversion sequence for the implicit
6479 // object parameter.
6480 QualType ImplicitParamType = From->getType();
6481 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6482 ImplicitParamType = FromPtrType->getPointeeType();
6483 CXXRecordDecl *ConversionContext
6484 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006485
Richard Smith0f59cb32015-12-18 21:45:41 +00006486 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6487 *this, CandidateSet.getLocation(), From->getType(),
6488 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006489
John McCall0d1da222010-01-12 00:44:57 +00006490 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006491 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006492 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006493 return;
6494 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006495
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006496 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006497 // derived to base as such conversions are given Conversion Rank. They only
6498 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6499 QualType FromCanon
6500 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6501 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006502 if (FromCanon == ToCanon ||
6503 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006504 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006505 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006506 return;
6507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006508
Douglas Gregora1f013e2008-11-07 22:36:19 +00006509 // To determine what the conversion from the result of calling the
6510 // conversion function to the type we're eventually trying to
6511 // convert to (ToType), we need to synthesize a call to the
6512 // conversion function and attempt copy initialization from it. This
6513 // makes sure that we get the right semantics with respect to
6514 // lvalues/rvalues and the type. Fortunately, we can allocate this
6515 // call on the stack and we don't need its arguments to be
6516 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006517 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006518 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006519 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6520 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006521 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006522 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006523
Richard Smith48d24642011-07-13 22:53:21 +00006524 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006525 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006526 Candidate.Viable = false;
6527 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6528 return;
6529 }
6530
Richard Smith48d24642011-07-13 22:53:21 +00006531 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006532
Mike Stump11289f42009-09-09 15:08:12 +00006533 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006534 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6535 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006536 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006537 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006538 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006539 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006540 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006541 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006542 /*InOverloadResolution=*/false,
6543 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006544
John McCall0d1da222010-01-12 00:44:57 +00006545 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006546 case ImplicitConversionSequence::StandardConversion:
6547 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006548
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006549 // C++ [over.ics.user]p3:
6550 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006551 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006552 // shall have exact match rank.
6553 if (Conversion->getPrimaryTemplate() &&
6554 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6555 Candidate.Viable = false;
6556 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006557 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006559
Douglas Gregorcba72b12011-01-21 05:18:22 +00006560 // C++0x [dcl.init.ref]p5:
6561 // In the second case, if the reference is an rvalue reference and
6562 // the second standard conversion sequence of the user-defined
6563 // conversion sequence includes an lvalue-to-rvalue conversion, the
6564 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006565 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006566 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6567 Candidate.Viable = false;
6568 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006569 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006570 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006571 break;
6572
6573 case ImplicitConversionSequence::BadConversion:
6574 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006575 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006576 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006577
6578 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006579 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006580 "Can only end up with a standard conversion sequence or failure");
6581 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006582
Craig Topper5fc8fc22014-08-27 06:28:36 +00006583 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006584 Candidate.Viable = false;
6585 Candidate.FailureKind = ovl_fail_enable_if;
6586 Candidate.DeductionFailure.Data = FailedAttr;
6587 return;
6588 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006589}
6590
Douglas Gregor05155d82009-08-21 23:19:43 +00006591/// \brief Adds a conversion function template specialization
6592/// candidate to the overload set, using template argument deduction
6593/// to deduce the template arguments of the conversion function
6594/// template from the type that we are converting to (C++
6595/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006596void
Douglas Gregor05155d82009-08-21 23:19:43 +00006597Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006598 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006599 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006600 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006601 OverloadCandidateSet &CandidateSet,
6602 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006603 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6604 "Only conversion function templates permitted here");
6605
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006606 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6607 return;
6608
Craig Toppere6706e42012-09-19 02:26:47 +00006609 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006610 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006611 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006612 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006613 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006614 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006615 Candidate.FoundDecl = FoundDecl;
6616 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6617 Candidate.Viable = false;
6618 Candidate.FailureKind = ovl_fail_bad_deduction;
6619 Candidate.IsSurrogate = false;
6620 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006621 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006623 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006624 return;
6625 }
Mike Stump11289f42009-09-09 15:08:12 +00006626
Douglas Gregor05155d82009-08-21 23:19:43 +00006627 // Add the conversion function template specialization produced by
6628 // template argument deduction as a candidate.
6629 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006630 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006631 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006632}
6633
Douglas Gregorab7897a2008-11-19 22:57:39 +00006634/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6635/// converts the given @c Object to a function pointer via the
6636/// conversion function @c Conversion, and then attempts to call it
6637/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6638/// the type of function that we'll eventually be calling.
6639void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006640 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006641 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006642 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006643 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006644 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006645 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006646 if (!CandidateSet.isNewCandidate(Conversion))
6647 return;
6648
Douglas Gregor27381f32009-11-23 12:27:39 +00006649 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006650 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006651
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006652 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006653 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006654 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006655 Candidate.Surrogate = Conversion;
6656 Candidate.Viable = true;
6657 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006658 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006659 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006660
6661 // Determine the implicit conversion sequence for the implicit
6662 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006663 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6664 *this, CandidateSet.getLocation(), Object->getType(),
6665 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006666 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006667 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006668 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006669 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006670 return;
6671 }
6672
6673 // The first conversion is actually a user-defined conversion whose
6674 // first conversion is ObjectInit's standard conversion (which is
6675 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006676 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006677 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006678 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006679 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006680 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006681 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006682 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006683 = Candidate.Conversions[0].UserDefined.Before;
6684 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6685
Mike Stump11289f42009-09-09 15:08:12 +00006686 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006687 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006688
6689 // (C++ 13.3.2p2): A candidate function having fewer than m
6690 // parameters is viable only if it has an ellipsis in its parameter
6691 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006692 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006693 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006694 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006695 return;
6696 }
6697
6698 // Function types don't have any default arguments, so just check if
6699 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006700 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006701 // Not enough arguments.
6702 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006703 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006704 return;
6705 }
6706
6707 // Determine the implicit conversion sequences for each of the
6708 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006709 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006710 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006711 // (C++ 13.3.2p3): for F to be a viable function, there shall
6712 // exist for each argument an implicit conversion sequence
6713 // (13.3.3.1) that converts that argument to the corresponding
6714 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006715 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006716 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006717 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006718 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006719 /*InOverloadResolution=*/false,
6720 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006721 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006722 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006723 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006724 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006725 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006726 }
6727 } else {
6728 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6729 // argument for which there is no corresponding parameter is
6730 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006731 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006732 }
6733 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006734
Craig Topper5fc8fc22014-08-27 06:28:36 +00006735 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006736 Candidate.Viable = false;
6737 Candidate.FailureKind = ovl_fail_enable_if;
6738 Candidate.DeductionFailure.Data = FailedAttr;
6739 return;
6740 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006741}
6742
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006743/// \brief Add overload candidates for overloaded operators that are
6744/// member functions.
6745///
6746/// Add the overloaded operator candidates that are member functions
6747/// for the operator Op that was used in an operator expression such
6748/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6749/// CandidateSet will store the added overload candidates. (C++
6750/// [over.match.oper]).
6751void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6752 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006753 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006754 OverloadCandidateSet& CandidateSet,
6755 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006756 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6757
6758 // C++ [over.match.oper]p3:
6759 // For a unary operator @ with an operand of a type whose
6760 // cv-unqualified version is T1, and for a binary operator @ with
6761 // a left operand of a type whose cv-unqualified version is T1 and
6762 // a right operand of a type whose cv-unqualified version is T2,
6763 // three sets of candidate functions, designated member
6764 // candidates, non-member candidates and built-in candidates, are
6765 // constructed as follows:
6766 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006767
Richard Smith0feaf0c2013-04-20 12:41:22 +00006768 // -- If T1 is a complete class type or a class currently being
6769 // defined, the set of member candidates is the result of the
6770 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6771 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006772 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006773 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006774 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006775 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006776 // If the type is neither complete nor being defined, bail out now.
6777 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006778 return;
Mike Stump11289f42009-09-09 15:08:12 +00006779
John McCall27b18f82009-11-17 02:14:36 +00006780 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6781 LookupQualifiedName(Operators, T1Rec->getDecl());
6782 Operators.suppressDiagnostics();
6783
Mike Stump11289f42009-09-09 15:08:12 +00006784 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006785 OperEnd = Operators.end();
6786 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006787 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006788 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006789 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006790 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006791 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006792 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006793 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006794}
6795
Douglas Gregora11693b2008-11-12 17:17:38 +00006796/// AddBuiltinCandidate - Add a candidate for a built-in
6797/// operator. ResultTy and ParamTys are the result and parameter types
6798/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006799/// arguments being passed to the candidate. IsAssignmentOperator
6800/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006801/// operator. NumContextualBoolArguments is the number of arguments
6802/// (at the beginning of the argument list) that will be contextually
6803/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006804void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006805 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006806 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006807 bool IsAssignmentOperator,
6808 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006809 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006810 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006811
Douglas Gregora11693b2008-11-12 17:17:38 +00006812 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006813 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006814 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6815 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006816 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006817 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006818 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006819 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006820 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6821
6822 // Determine the implicit conversion sequences for each of the
6823 // arguments.
6824 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006825 Candidate.ExplicitCallArguments = Args.size();
6826 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006827 // C++ [over.match.oper]p4:
6828 // For the built-in assignment operators, conversions of the
6829 // left operand are restricted as follows:
6830 // -- no temporaries are introduced to hold the left operand, and
6831 // -- no user-defined conversions are applied to the left
6832 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006833 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006834 //
6835 // We block these conversions by turning off user-defined
6836 // conversions, since that is the only way that initialization of
6837 // a reference to a non-class type can occur from something that
6838 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006839 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006840 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006841 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006842 Candidate.Conversions[ArgIdx]
6843 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006844 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006845 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006846 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006847 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006848 /*InOverloadResolution=*/false,
6849 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006850 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006851 }
John McCall0d1da222010-01-12 00:44:57 +00006852 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006853 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006854 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006855 break;
6856 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006857 }
6858}
6859
Craig Toppercd7b0332013-07-01 06:29:40 +00006860namespace {
6861
Douglas Gregora11693b2008-11-12 17:17:38 +00006862/// BuiltinCandidateTypeSet - A set of types that will be used for the
6863/// candidate operator functions for built-in operators (C++
6864/// [over.built]). The types are separated into pointer types and
6865/// enumeration types.
6866class BuiltinCandidateTypeSet {
6867 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006868 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6869 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006870
6871 /// PointerTypes - The set of pointer types that will be used in the
6872 /// built-in candidates.
6873 TypeSet PointerTypes;
6874
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006875 /// MemberPointerTypes - The set of member pointer types that will be
6876 /// used in the built-in candidates.
6877 TypeSet MemberPointerTypes;
6878
Douglas Gregora11693b2008-11-12 17:17:38 +00006879 /// EnumerationTypes - The set of enumeration types that will be
6880 /// used in the built-in candidates.
6881 TypeSet EnumerationTypes;
6882
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006883 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006884 /// candidates.
6885 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006886
6887 /// \brief A flag indicating non-record types are viable candidates
6888 bool HasNonRecordTypes;
6889
6890 /// \brief A flag indicating whether either arithmetic or enumeration types
6891 /// were present in the candidate set.
6892 bool HasArithmeticOrEnumeralTypes;
6893
Douglas Gregor80af3132011-05-21 23:15:46 +00006894 /// \brief A flag indicating whether the nullptr type was present in the
6895 /// candidate set.
6896 bool HasNullPtrType;
6897
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006898 /// Sema - The semantic analysis instance where we are building the
6899 /// candidate type set.
6900 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006901
Douglas Gregora11693b2008-11-12 17:17:38 +00006902 /// Context - The AST context in which we will build the type sets.
6903 ASTContext &Context;
6904
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006905 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6906 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006907 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006908
6909public:
6910 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006911 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006912
Mike Stump11289f42009-09-09 15:08:12 +00006913 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006914 : HasNonRecordTypes(false),
6915 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006916 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006917 SemaRef(SemaRef),
6918 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006919
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006920 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006921 SourceLocation Loc,
6922 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006923 bool AllowExplicitConversions,
6924 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006925
6926 /// pointer_begin - First pointer type found;
6927 iterator pointer_begin() { return PointerTypes.begin(); }
6928
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006929 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006930 iterator pointer_end() { return PointerTypes.end(); }
6931
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006932 /// member_pointer_begin - First member pointer type found;
6933 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6934
6935 /// member_pointer_end - Past the last member pointer type found;
6936 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6937
Douglas Gregora11693b2008-11-12 17:17:38 +00006938 /// enumeration_begin - First enumeration type found;
6939 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6940
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006941 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006942 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006944 iterator vector_begin() { return VectorTypes.begin(); }
6945 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006946
6947 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6948 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006949 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006950};
6951
Craig Toppercd7b0332013-07-01 06:29:40 +00006952} // end anonymous namespace
6953
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006954/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006955/// the set of pointer types along with any more-qualified variants of
6956/// that type. For example, if @p Ty is "int const *", this routine
6957/// will add "int const *", "int const volatile *", "int const
6958/// restrict *", and "int const volatile restrict *" to the set of
6959/// pointer types. Returns true if the add of @p Ty itself succeeded,
6960/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006961///
6962/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006963bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006964BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6965 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006966
Douglas Gregora11693b2008-11-12 17:17:38 +00006967 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00006968 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006969 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006970
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006971 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006972 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006973 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006974 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006975 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6976 PointeeTy = PTy->getPointeeType();
6977 buildObjCPtr = true;
6978 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006979 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006980 }
6981
Sebastian Redl4990a632009-11-18 20:39:26 +00006982 // Don't add qualified variants of arrays. For one, they're not allowed
6983 // (the qualifier would sink to the element type), and for another, the
6984 // only overload situation where it matters is subscript or pointer +- int,
6985 // and those shouldn't have qualifier variants anyway.
6986 if (PointeeTy->isArrayType())
6987 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006988
John McCall8ccfcb52009-09-24 19:53:00 +00006989 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006990 bool hasVolatile = VisibleQuals.hasVolatile();
6991 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006992
John McCall8ccfcb52009-09-24 19:53:00 +00006993 // Iterate through all strict supersets of BaseCVR.
6994 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6995 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006996 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006997 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006998
6999 // Skip over restrict if no restrict found anywhere in the types, or if
7000 // the type cannot be restrict-qualified.
7001 if ((CVR & Qualifiers::Restrict) &&
7002 (!hasRestrict ||
7003 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7004 continue;
7005
7006 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007007 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007008
7009 // Build qualified pointer type.
7010 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007011 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007012 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007013 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007014 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7015
7016 // Insert qualified pointer type.
7017 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007018 }
7019
7020 return true;
7021}
7022
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007023/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7024/// to the set of pointer types along with any more-qualified variants of
7025/// that type. For example, if @p Ty is "int const *", this routine
7026/// will add "int const *", "int const volatile *", "int const
7027/// restrict *", and "int const volatile restrict *" to the set of
7028/// pointer types. Returns true if the add of @p Ty itself succeeded,
7029/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007030///
7031/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007032bool
7033BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7034 QualType Ty) {
7035 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007036 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007037 return false;
7038
John McCall8ccfcb52009-09-24 19:53:00 +00007039 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7040 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007041
John McCall8ccfcb52009-09-24 19:53:00 +00007042 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007043 // Don't add qualified variants of arrays. For one, they're not allowed
7044 // (the qualifier would sink to the element type), and for another, the
7045 // only overload situation where it matters is subscript or pointer +- int,
7046 // and those shouldn't have qualifier variants anyway.
7047 if (PointeeTy->isArrayType())
7048 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007049 const Type *ClassTy = PointerTy->getClass();
7050
7051 // Iterate through all strict supersets of the pointee type's CVR
7052 // qualifiers.
7053 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7054 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7055 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007056
John McCall8ccfcb52009-09-24 19:53:00 +00007057 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007058 MemberPointerTypes.insert(
7059 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007060 }
7061
7062 return true;
7063}
7064
Douglas Gregora11693b2008-11-12 17:17:38 +00007065/// AddTypesConvertedFrom - Add each of the types to which the type @p
7066/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007067/// primarily interested in pointer types and enumeration types. We also
7068/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007069/// AllowUserConversions is true if we should look at the conversion
7070/// functions of a class type, and AllowExplicitConversions if we
7071/// should also include the explicit conversion functions of a class
7072/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007073void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007074BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007075 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007076 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007077 bool AllowExplicitConversions,
7078 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007079 // Only deal with canonical types.
7080 Ty = Context.getCanonicalType(Ty);
7081
7082 // Look through reference types; they aren't part of the type of an
7083 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007084 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007085 Ty = RefTy->getPointeeType();
7086
John McCall33ddac02011-01-19 10:06:00 +00007087 // If we're dealing with an array type, decay to the pointer.
7088 if (Ty->isArrayType())
7089 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7090
7091 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007092 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007093
Chandler Carruth00a38332010-12-13 01:44:01 +00007094 // Flag if we ever add a non-record type.
7095 const RecordType *TyRec = Ty->getAs<RecordType>();
7096 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7097
Chandler Carruth00a38332010-12-13 01:44:01 +00007098 // Flag if we encounter an arithmetic type.
7099 HasArithmeticOrEnumeralTypes =
7100 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7101
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007102 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7103 PointerTypes.insert(Ty);
7104 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007105 // Insert our type, and its more-qualified variants, into the set
7106 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007107 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007108 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007109 } else if (Ty->isMemberPointerType()) {
7110 // Member pointers are far easier, since the pointee can't be converted.
7111 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7112 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007113 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007114 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007115 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007116 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007117 // We treat vector types as arithmetic types in many contexts as an
7118 // extension.
7119 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007120 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007121 } else if (Ty->isNullPtrType()) {
7122 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007123 } else if (AllowUserConversions && TyRec) {
7124 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007125 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007126 return;
Mike Stump11289f42009-09-09 15:08:12 +00007127
Chandler Carruth00a38332010-12-13 01:44:01 +00007128 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007129 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007130 if (isa<UsingShadowDecl>(D))
7131 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007132
Chandler Carruth00a38332010-12-13 01:44:01 +00007133 // Skip conversion function templates; they don't tell us anything
7134 // about which builtin types we can convert to.
7135 if (isa<FunctionTemplateDecl>(D))
7136 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007137
Chandler Carruth00a38332010-12-13 01:44:01 +00007138 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7139 if (AllowExplicitConversions || !Conv->isExplicit()) {
7140 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7141 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007142 }
7143 }
7144 }
7145}
7146
Douglas Gregor84605ae2009-08-24 13:43:27 +00007147/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7148/// the volatile- and non-volatile-qualified assignment operators for the
7149/// given type to the candidate set.
7150static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7151 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007152 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007153 OverloadCandidateSet &CandidateSet) {
7154 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007155
Douglas Gregor84605ae2009-08-24 13:43:27 +00007156 // T& operator=(T&, T)
7157 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7158 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007159 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007160 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007161
Douglas Gregor84605ae2009-08-24 13:43:27 +00007162 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7163 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007164 ParamTypes[0]
7165 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007166 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007167 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007168 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007169 }
7170}
Mike Stump11289f42009-09-09 15:08:12 +00007171
Sebastian Redl1054fae2009-10-25 17:03:50 +00007172/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7173/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007174static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7175 Qualifiers VRQuals;
7176 const RecordType *TyRec;
7177 if (const MemberPointerType *RHSMPType =
7178 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007179 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007180 else
7181 TyRec = ArgExpr->getType()->getAs<RecordType>();
7182 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007183 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007184 VRQuals.addVolatile();
7185 VRQuals.addRestrict();
7186 return VRQuals;
7187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007188
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007189 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007190 if (!ClassDecl->hasDefinition())
7191 return VRQuals;
7192
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007193 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007194 if (isa<UsingShadowDecl>(D))
7195 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7196 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007197 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7198 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7199 CanTy = ResTypeRef->getPointeeType();
7200 // Need to go down the pointer/mempointer chain and add qualifiers
7201 // as see them.
7202 bool done = false;
7203 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007204 if (CanTy.isRestrictQualified())
7205 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007206 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7207 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007208 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007209 CanTy->getAs<MemberPointerType>())
7210 CanTy = ResTypeMPtr->getPointeeType();
7211 else
7212 done = true;
7213 if (CanTy.isVolatileQualified())
7214 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007215 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7216 return VRQuals;
7217 }
7218 }
7219 }
7220 return VRQuals;
7221}
John McCall52872982010-11-13 05:51:15 +00007222
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007223namespace {
John McCall52872982010-11-13 05:51:15 +00007224
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007225/// \brief Helper class to manage the addition of builtin operator overload
7226/// candidates. It provides shared state and utility methods used throughout
7227/// the process, as well as a helper method to add each group of builtin
7228/// operator overloads from the standard to a candidate set.
7229class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007230 // Common instance state available to all overload candidate addition methods.
7231 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007232 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007233 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007234 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007235 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007236 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007237
Chandler Carruthc6586e52010-12-12 10:35:00 +00007238 // Define some constants used to index and iterate over the arithemetic types
7239 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007240 // The "promoted arithmetic types" are the arithmetic
7241 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007242 static const unsigned FirstIntegralType = 4;
7243 static const unsigned LastIntegralType = 21;
7244 static const unsigned FirstPromotedIntegralType = 4,
7245 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007246 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007247 LastPromotedArithmeticType = 12;
7248 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007249
Chandler Carruthc6586e52010-12-12 10:35:00 +00007250 /// \brief Get the canonical type for a given arithmetic type index.
7251 CanQualType getArithmeticType(unsigned index) {
7252 assert(index < NumArithmeticTypes);
7253 static CanQualType ASTContext::* const
7254 ArithmeticTypes[NumArithmeticTypes] = {
7255 // Start of promoted types.
7256 &ASTContext::FloatTy,
7257 &ASTContext::DoubleTy,
7258 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007259 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007260
Chandler Carruthc6586e52010-12-12 10:35:00 +00007261 // Start of integral types.
7262 &ASTContext::IntTy,
7263 &ASTContext::LongTy,
7264 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007265 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007266 &ASTContext::UnsignedIntTy,
7267 &ASTContext::UnsignedLongTy,
7268 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007269 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007270 // End of promoted types.
7271
7272 &ASTContext::BoolTy,
7273 &ASTContext::CharTy,
7274 &ASTContext::WCharTy,
7275 &ASTContext::Char16Ty,
7276 &ASTContext::Char32Ty,
7277 &ASTContext::SignedCharTy,
7278 &ASTContext::ShortTy,
7279 &ASTContext::UnsignedCharTy,
7280 &ASTContext::UnsignedShortTy,
7281 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007282 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007283 };
7284 return S.Context.*ArithmeticTypes[index];
7285 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007286
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007287 /// \brief Gets the canonical type resulting from the usual arithemetic
7288 /// converions for the given arithmetic types.
7289 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7290 // Accelerator table for performing the usual arithmetic conversions.
7291 // The rules are basically:
7292 // - if either is floating-point, use the wider floating-point
7293 // - if same signedness, use the higher rank
7294 // - if same size, use unsigned of the higher rank
7295 // - use the larger type
7296 // These rules, together with the axiom that higher ranks are
7297 // never smaller, are sufficient to precompute all of these results
7298 // *except* when dealing with signed types of higher rank.
7299 // (we could precompute SLL x UI for all known platforms, but it's
7300 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007301 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007302 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007303 Dep=-1,
7304 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007305 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007306 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007307 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007308/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7309/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7310/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7311/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7312/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7313/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7314/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7315/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7316/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7317/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7318/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007319 };
7320
7321 assert(L < LastPromotedArithmeticType);
7322 assert(R < LastPromotedArithmeticType);
7323 int Idx = ConversionsTable[L][R];
7324
7325 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007326 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007327
7328 // Slow path: we need to compare widths.
7329 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007330 CanQualType LT = getArithmeticType(L),
7331 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007332 unsigned LW = S.Context.getIntWidth(LT),
7333 RW = S.Context.getIntWidth(RT);
7334
7335 // If they're different widths, use the signed type.
7336 if (LW > RW) return LT;
7337 else if (LW < RW) return RT;
7338
7339 // Otherwise, use the unsigned type of the signed type's rank.
7340 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7341 assert(L == SLL || R == SLL);
7342 return S.Context.UnsignedLongLongTy;
7343 }
7344
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007345 /// \brief Helper method to factor out the common pattern of adding overloads
7346 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007347 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007348 bool HasVolatile,
7349 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007350 QualType ParamTypes[2] = {
7351 S.Context.getLValueReferenceType(CandidateTy),
7352 S.Context.IntTy
7353 };
7354
7355 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007356 if (Args.size() == 1)
7357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007358 else
Richard Smithe54c3072013-05-05 15:51:06 +00007359 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007360
7361 // Use a heuristic to reduce number of builtin candidates in the set:
7362 // add volatile version only if there are conversions to a volatile type.
7363 if (HasVolatile) {
7364 ParamTypes[0] =
7365 S.Context.getLValueReferenceType(
7366 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007367 if (Args.size() == 1)
7368 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007369 else
Richard Smithe54c3072013-05-05 15:51:06 +00007370 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007371 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007372
7373 // Add restrict version only if there are conversions to a restrict type
7374 // and our candidate type is a non-restrict-qualified pointer.
7375 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7376 !CandidateTy.isRestrictQualified()) {
7377 ParamTypes[0]
7378 = S.Context.getLValueReferenceType(
7379 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007380 if (Args.size() == 1)
7381 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007382 else
Richard Smithe54c3072013-05-05 15:51:06 +00007383 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007384
7385 if (HasVolatile) {
7386 ParamTypes[0]
7387 = S.Context.getLValueReferenceType(
7388 S.Context.getCVRQualifiedType(CandidateTy,
7389 (Qualifiers::Volatile |
7390 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007391 if (Args.size() == 1)
7392 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007393 else
Richard Smithe54c3072013-05-05 15:51:06 +00007394 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007395 }
7396 }
7397
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007398 }
7399
7400public:
7401 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007402 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007403 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007404 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007405 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007406 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007407 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007408 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007409 HasArithmeticOrEnumeralCandidateType(
7410 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007411 CandidateTypes(CandidateTypes),
7412 CandidateSet(CandidateSet) {
7413 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007414 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007415 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007416 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007417 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007418 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007419 assert(getArithmeticType(FirstPromotedArithmeticType)
7420 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007421 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007422 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007423 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007424 "Invalid last promoted arithmetic type");
7425 }
7426
7427 // C++ [over.built]p3:
7428 //
7429 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7430 // is either volatile or empty, there exist candidate operator
7431 // functions of the form
7432 //
7433 // VQ T& operator++(VQ T&);
7434 // T operator++(VQ T&, int);
7435 //
7436 // C++ [over.built]p4:
7437 //
7438 // For every pair (T, VQ), where T is an arithmetic type other
7439 // than bool, and VQ is either volatile or empty, there exist
7440 // candidate operator functions of the form
7441 //
7442 // VQ T& operator--(VQ T&);
7443 // T operator--(VQ T&, int);
7444 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007445 if (!HasArithmeticOrEnumeralCandidateType)
7446 return;
7447
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007448 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7449 Arith < NumArithmeticTypes; ++Arith) {
7450 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007451 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007452 VisibleTypeConversionsQuals.hasVolatile(),
7453 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007454 }
7455 }
7456
7457 // C++ [over.built]p5:
7458 //
7459 // For every pair (T, VQ), where T is a cv-qualified or
7460 // cv-unqualified object type, and VQ is either volatile or
7461 // empty, there exist candidate operator functions of the form
7462 //
7463 // T*VQ& operator++(T*VQ&);
7464 // T*VQ& operator--(T*VQ&);
7465 // T* operator++(T*VQ&, int);
7466 // T* operator--(T*VQ&, int);
7467 void addPlusPlusMinusMinusPointerOverloads() {
7468 for (BuiltinCandidateTypeSet::iterator
7469 Ptr = CandidateTypes[0].pointer_begin(),
7470 PtrEnd = CandidateTypes[0].pointer_end();
7471 Ptr != PtrEnd; ++Ptr) {
7472 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007473 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007474 continue;
7475
7476 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007477 (!(*Ptr).isVolatileQualified() &&
7478 VisibleTypeConversionsQuals.hasVolatile()),
7479 (!(*Ptr).isRestrictQualified() &&
7480 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007481 }
7482 }
7483
7484 // C++ [over.built]p6:
7485 // For every cv-qualified or cv-unqualified object type T, there
7486 // exist candidate operator functions of the form
7487 //
7488 // T& operator*(T*);
7489 //
7490 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007491 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007492 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007493 // T& operator*(T*);
7494 void addUnaryStarPointerOverloads() {
7495 for (BuiltinCandidateTypeSet::iterator
7496 Ptr = CandidateTypes[0].pointer_begin(),
7497 PtrEnd = CandidateTypes[0].pointer_end();
7498 Ptr != PtrEnd; ++Ptr) {
7499 QualType ParamTy = *Ptr;
7500 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007501 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7502 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007503
Douglas Gregor02824322011-01-26 19:30:28 +00007504 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7505 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7506 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007507
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007508 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007509 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 }
7511 }
7512
7513 // C++ [over.built]p9:
7514 // For every promoted arithmetic type T, there exist candidate
7515 // operator functions of the form
7516 //
7517 // T operator+(T);
7518 // T operator-(T);
7519 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007520 if (!HasArithmeticOrEnumeralCandidateType)
7521 return;
7522
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007523 for (unsigned Arith = FirstPromotedArithmeticType;
7524 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007525 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007526 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007527 }
7528
7529 // Extension: We also add these operators for vector types.
7530 for (BuiltinCandidateTypeSet::iterator
7531 Vec = CandidateTypes[0].vector_begin(),
7532 VecEnd = CandidateTypes[0].vector_end();
7533 Vec != VecEnd; ++Vec) {
7534 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007535 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007536 }
7537 }
7538
7539 // C++ [over.built]p8:
7540 // For every type T, there exist candidate operator functions of
7541 // the form
7542 //
7543 // T* operator+(T*);
7544 void addUnaryPlusPointerOverloads() {
7545 for (BuiltinCandidateTypeSet::iterator
7546 Ptr = CandidateTypes[0].pointer_begin(),
7547 PtrEnd = CandidateTypes[0].pointer_end();
7548 Ptr != PtrEnd; ++Ptr) {
7549 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007550 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007551 }
7552 }
7553
7554 // C++ [over.built]p10:
7555 // For every promoted integral type T, there exist candidate
7556 // operator functions of the form
7557 //
7558 // T operator~(T);
7559 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007560 if (!HasArithmeticOrEnumeralCandidateType)
7561 return;
7562
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007563 for (unsigned Int = FirstPromotedIntegralType;
7564 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007565 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007566 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007567 }
7568
7569 // Extension: We also add this operator for vector types.
7570 for (BuiltinCandidateTypeSet::iterator
7571 Vec = CandidateTypes[0].vector_begin(),
7572 VecEnd = CandidateTypes[0].vector_end();
7573 Vec != VecEnd; ++Vec) {
7574 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007575 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007576 }
7577 }
7578
7579 // C++ [over.match.oper]p16:
7580 // For every pointer to member type T, there exist candidate operator
7581 // functions of the form
7582 //
7583 // bool operator==(T,T);
7584 // bool operator!=(T,T);
7585 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7586 /// Set of (canonical) types that we've already handled.
7587 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7588
Richard Smithe54c3072013-05-05 15:51:06 +00007589 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007590 for (BuiltinCandidateTypeSet::iterator
7591 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7592 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7593 MemPtr != MemPtrEnd;
7594 ++MemPtr) {
7595 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007596 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007597 continue;
7598
7599 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007600 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007601 }
7602 }
7603 }
7604
7605 // C++ [over.built]p15:
7606 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007607 // For every T, where T is an enumeration type, a pointer type, or
7608 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007609 //
7610 // bool operator<(T, T);
7611 // bool operator>(T, T);
7612 // bool operator<=(T, T);
7613 // bool operator>=(T, T);
7614 // bool operator==(T, T);
7615 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007616 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007617 // C++ [over.match.oper]p3:
7618 // [...]the built-in candidates include all of the candidate operator
7619 // functions defined in 13.6 that, compared to the given operator, [...]
7620 // do not have the same parameter-type-list as any non-template non-member
7621 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007622 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007623 // Note that in practice, this only affects enumeration types because there
7624 // aren't any built-in candidates of record type, and a user-defined operator
7625 // must have an operand of record or enumeration type. Also, the only other
7626 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007627 // cannot be overloaded for enumeration types, so this is the only place
7628 // where we must suppress candidates like this.
7629 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7630 UserDefinedBinaryOperators;
7631
Richard Smithe54c3072013-05-05 15:51:06 +00007632 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007633 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7634 CandidateTypes[ArgIdx].enumeration_end()) {
7635 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7636 CEnd = CandidateSet.end();
7637 C != CEnd; ++C) {
7638 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7639 continue;
7640
Eli Friedman14f082b2012-09-18 21:52:24 +00007641 if (C->Function->isFunctionTemplateSpecialization())
7642 continue;
7643
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007644 QualType FirstParamType =
7645 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7646 QualType SecondParamType =
7647 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7648
7649 // Skip if either parameter isn't of enumeral type.
7650 if (!FirstParamType->isEnumeralType() ||
7651 !SecondParamType->isEnumeralType())
7652 continue;
7653
7654 // Add this operator to the set of known user-defined operators.
7655 UserDefinedBinaryOperators.insert(
7656 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7657 S.Context.getCanonicalType(SecondParamType)));
7658 }
7659 }
7660 }
7661
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007662 /// Set of (canonical) types that we've already handled.
7663 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7664
Richard Smithe54c3072013-05-05 15:51:06 +00007665 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007666 for (BuiltinCandidateTypeSet::iterator
7667 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7668 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7669 Ptr != PtrEnd; ++Ptr) {
7670 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007671 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007672 continue;
7673
7674 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007675 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007676 }
7677 for (BuiltinCandidateTypeSet::iterator
7678 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7679 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7680 Enum != EnumEnd; ++Enum) {
7681 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7682
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007683 // Don't add the same builtin candidate twice, or if a user defined
7684 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007685 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007686 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7687 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007688 continue;
7689
7690 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007691 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007692 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007693
7694 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7695 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007696 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007697 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007698 NullPtrTy))) {
7699 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007700 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007701 CandidateSet);
7702 }
7703 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007704 }
7705 }
7706
7707 // C++ [over.built]p13:
7708 //
7709 // For every cv-qualified or cv-unqualified object type T
7710 // there exist candidate operator functions of the form
7711 //
7712 // T* operator+(T*, ptrdiff_t);
7713 // T& operator[](T*, ptrdiff_t); [BELOW]
7714 // T* operator-(T*, ptrdiff_t);
7715 // T* operator+(ptrdiff_t, T*);
7716 // T& operator[](ptrdiff_t, T*); [BELOW]
7717 //
7718 // C++ [over.built]p14:
7719 //
7720 // For every T, where T is a pointer to object type, there
7721 // exist candidate operator functions of the form
7722 //
7723 // ptrdiff_t operator-(T, T);
7724 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7725 /// Set of (canonical) types that we've already handled.
7726 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7727
7728 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007729 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007730 S.Context.getPointerDiffType(),
7731 S.Context.getPointerDiffType(),
7732 };
7733 for (BuiltinCandidateTypeSet::iterator
7734 Ptr = CandidateTypes[Arg].pointer_begin(),
7735 PtrEnd = CandidateTypes[Arg].pointer_end();
7736 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007737 QualType PointeeTy = (*Ptr)->getPointeeType();
7738 if (!PointeeTy->isObjectType())
7739 continue;
7740
Eric Christopher9207a522015-08-21 16:24:01 +00007741 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007742 if (Arg == 0 || Op == OO_Plus) {
7743 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7744 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007745 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007746 }
7747 if (Op == OO_Minus) {
7748 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007749 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007750 continue;
7751
7752 QualType ParamTypes[2] = { *Ptr, *Ptr };
7753 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007754 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007755 }
7756 }
7757 }
7758 }
7759
7760 // C++ [over.built]p12:
7761 //
7762 // For every pair of promoted arithmetic types L and R, there
7763 // exist candidate operator functions of the form
7764 //
7765 // LR operator*(L, R);
7766 // LR operator/(L, R);
7767 // LR operator+(L, R);
7768 // LR operator-(L, R);
7769 // bool operator<(L, R);
7770 // bool operator>(L, R);
7771 // bool operator<=(L, R);
7772 // bool operator>=(L, R);
7773 // bool operator==(L, R);
7774 // bool operator!=(L, R);
7775 //
7776 // where LR is the result of the usual arithmetic conversions
7777 // between types L and R.
7778 //
7779 // C++ [over.built]p24:
7780 //
7781 // For every pair of promoted arithmetic types L and R, there exist
7782 // candidate operator functions of the form
7783 //
7784 // LR operator?(bool, L, R);
7785 //
7786 // where LR is the result of the usual arithmetic conversions
7787 // between types L and R.
7788 // Our candidates ignore the first parameter.
7789 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007790 if (!HasArithmeticOrEnumeralCandidateType)
7791 return;
7792
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007793 for (unsigned Left = FirstPromotedArithmeticType;
7794 Left < LastPromotedArithmeticType; ++Left) {
7795 for (unsigned Right = FirstPromotedArithmeticType;
7796 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007797 QualType LandR[2] = { getArithmeticType(Left),
7798 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007799 QualType Result =
7800 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007801 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007802 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007803 }
7804 }
7805
7806 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7807 // conditional operator for vector types.
7808 for (BuiltinCandidateTypeSet::iterator
7809 Vec1 = CandidateTypes[0].vector_begin(),
7810 Vec1End = CandidateTypes[0].vector_end();
7811 Vec1 != Vec1End; ++Vec1) {
7812 for (BuiltinCandidateTypeSet::iterator
7813 Vec2 = CandidateTypes[1].vector_begin(),
7814 Vec2End = CandidateTypes[1].vector_end();
7815 Vec2 != Vec2End; ++Vec2) {
7816 QualType LandR[2] = { *Vec1, *Vec2 };
7817 QualType Result = S.Context.BoolTy;
7818 if (!isComparison) {
7819 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7820 Result = *Vec1;
7821 else
7822 Result = *Vec2;
7823 }
7824
Richard Smithe54c3072013-05-05 15:51:06 +00007825 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007826 }
7827 }
7828 }
7829
7830 // C++ [over.built]p17:
7831 //
7832 // For every pair of promoted integral types L and R, there
7833 // exist candidate operator functions of the form
7834 //
7835 // LR operator%(L, R);
7836 // LR operator&(L, R);
7837 // LR operator^(L, R);
7838 // LR operator|(L, R);
7839 // L operator<<(L, R);
7840 // L operator>>(L, R);
7841 //
7842 // where LR is the result of the usual arithmetic conversions
7843 // between types L and R.
7844 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007845 if (!HasArithmeticOrEnumeralCandidateType)
7846 return;
7847
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007848 for (unsigned Left = FirstPromotedIntegralType;
7849 Left < LastPromotedIntegralType; ++Left) {
7850 for (unsigned Right = FirstPromotedIntegralType;
7851 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007852 QualType LandR[2] = { getArithmeticType(Left),
7853 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007854 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7855 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007856 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007857 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007858 }
7859 }
7860 }
7861
7862 // C++ [over.built]p20:
7863 //
7864 // For every pair (T, VQ), where T is an enumeration or
7865 // pointer to member type and VQ is either volatile or
7866 // empty, there exist candidate operator functions of the form
7867 //
7868 // VQ T& operator=(VQ T&, T);
7869 void addAssignmentMemberPointerOrEnumeralOverloads() {
7870 /// Set of (canonical) types that we've already handled.
7871 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7872
7873 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7874 for (BuiltinCandidateTypeSet::iterator
7875 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7876 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7877 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007878 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879 continue;
7880
Richard Smithe54c3072013-05-05 15:51:06 +00007881 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007882 }
7883
7884 for (BuiltinCandidateTypeSet::iterator
7885 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7886 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7887 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007888 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007889 continue;
7890
Richard Smithe54c3072013-05-05 15:51:06 +00007891 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007892 }
7893 }
7894 }
7895
7896 // C++ [over.built]p19:
7897 //
7898 // For every pair (T, VQ), where T is any type and VQ is either
7899 // volatile or empty, there exist candidate operator functions
7900 // of the form
7901 //
7902 // T*VQ& operator=(T*VQ&, T*);
7903 //
7904 // C++ [over.built]p21:
7905 //
7906 // For every pair (T, VQ), where T is a cv-qualified or
7907 // cv-unqualified object type and VQ is either volatile or
7908 // empty, there exist candidate operator functions of the form
7909 //
7910 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7911 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7912 void addAssignmentPointerOverloads(bool isEqualOp) {
7913 /// Set of (canonical) types that we've already handled.
7914 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7915
7916 for (BuiltinCandidateTypeSet::iterator
7917 Ptr = CandidateTypes[0].pointer_begin(),
7918 PtrEnd = CandidateTypes[0].pointer_end();
7919 Ptr != PtrEnd; ++Ptr) {
7920 // If this is operator=, keep track of the builtin candidates we added.
7921 if (isEqualOp)
7922 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007923 else if (!(*Ptr)->getPointeeType()->isObjectType())
7924 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007925
7926 // non-volatile version
7927 QualType ParamTypes[2] = {
7928 S.Context.getLValueReferenceType(*Ptr),
7929 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7930 };
Richard Smithe54c3072013-05-05 15:51:06 +00007931 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007932 /*IsAssigmentOperator=*/ isEqualOp);
7933
Douglas Gregor5bee2582012-06-04 00:15:09 +00007934 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7935 VisibleTypeConversionsQuals.hasVolatile();
7936 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007937 // volatile version
7938 ParamTypes[0] =
7939 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007940 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007941 /*IsAssigmentOperator=*/isEqualOp);
7942 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007943
7944 if (!(*Ptr).isRestrictQualified() &&
7945 VisibleTypeConversionsQuals.hasRestrict()) {
7946 // restrict version
7947 ParamTypes[0]
7948 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007949 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007950 /*IsAssigmentOperator=*/isEqualOp);
7951
7952 if (NeedVolatile) {
7953 // volatile restrict version
7954 ParamTypes[0]
7955 = S.Context.getLValueReferenceType(
7956 S.Context.getCVRQualifiedType(*Ptr,
7957 (Qualifiers::Volatile |
7958 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007959 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007960 /*IsAssigmentOperator=*/isEqualOp);
7961 }
7962 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007963 }
7964
7965 if (isEqualOp) {
7966 for (BuiltinCandidateTypeSet::iterator
7967 Ptr = CandidateTypes[1].pointer_begin(),
7968 PtrEnd = CandidateTypes[1].pointer_end();
7969 Ptr != PtrEnd; ++Ptr) {
7970 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007971 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007972 continue;
7973
Chandler Carruth8e543b32010-12-12 08:17:55 +00007974 QualType ParamTypes[2] = {
7975 S.Context.getLValueReferenceType(*Ptr),
7976 *Ptr,
7977 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007978
7979 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007980 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007981 /*IsAssigmentOperator=*/true);
7982
Douglas Gregor5bee2582012-06-04 00:15:09 +00007983 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7984 VisibleTypeConversionsQuals.hasVolatile();
7985 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007986 // volatile version
7987 ParamTypes[0] =
7988 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007989 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7990 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007991 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007992
7993 if (!(*Ptr).isRestrictQualified() &&
7994 VisibleTypeConversionsQuals.hasRestrict()) {
7995 // restrict version
7996 ParamTypes[0]
7997 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007998 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7999 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008000
8001 if (NeedVolatile) {
8002 // volatile restrict version
8003 ParamTypes[0]
8004 = S.Context.getLValueReferenceType(
8005 S.Context.getCVRQualifiedType(*Ptr,
8006 (Qualifiers::Volatile |
8007 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8009 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008010 }
8011 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008012 }
8013 }
8014 }
8015
8016 // C++ [over.built]p18:
8017 //
8018 // For every triple (L, VQ, R), where L is an arithmetic type,
8019 // VQ is either volatile or empty, and R is a promoted
8020 // arithmetic type, there exist candidate operator functions of
8021 // the form
8022 //
8023 // VQ L& operator=(VQ L&, R);
8024 // VQ L& operator*=(VQ L&, R);
8025 // VQ L& operator/=(VQ L&, R);
8026 // VQ L& operator+=(VQ L&, R);
8027 // VQ L& operator-=(VQ L&, R);
8028 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008029 if (!HasArithmeticOrEnumeralCandidateType)
8030 return;
8031
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008032 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8033 for (unsigned Right = FirstPromotedArithmeticType;
8034 Right < LastPromotedArithmeticType; ++Right) {
8035 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008036 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008037
8038 // Add this built-in operator as a candidate (VQ is empty).
8039 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008040 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008041 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008042 /*IsAssigmentOperator=*/isEqualOp);
8043
8044 // Add this built-in operator as a candidate (VQ is 'volatile').
8045 if (VisibleTypeConversionsQuals.hasVolatile()) {
8046 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008047 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008048 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008049 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008050 /*IsAssigmentOperator=*/isEqualOp);
8051 }
8052 }
8053 }
8054
8055 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8056 for (BuiltinCandidateTypeSet::iterator
8057 Vec1 = CandidateTypes[0].vector_begin(),
8058 Vec1End = CandidateTypes[0].vector_end();
8059 Vec1 != Vec1End; ++Vec1) {
8060 for (BuiltinCandidateTypeSet::iterator
8061 Vec2 = CandidateTypes[1].vector_begin(),
8062 Vec2End = CandidateTypes[1].vector_end();
8063 Vec2 != Vec2End; ++Vec2) {
8064 QualType ParamTypes[2];
8065 ParamTypes[1] = *Vec2;
8066 // Add this built-in operator as a candidate (VQ is empty).
8067 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008068 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 /*IsAssigmentOperator=*/isEqualOp);
8070
8071 // Add this built-in operator as a candidate (VQ is 'volatile').
8072 if (VisibleTypeConversionsQuals.hasVolatile()) {
8073 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8074 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008075 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008076 /*IsAssigmentOperator=*/isEqualOp);
8077 }
8078 }
8079 }
8080 }
8081
8082 // C++ [over.built]p22:
8083 //
8084 // For every triple (L, VQ, R), where L is an integral type, VQ
8085 // is either volatile or empty, and R is a promoted integral
8086 // type, there exist candidate operator functions of the form
8087 //
8088 // VQ L& operator%=(VQ L&, R);
8089 // VQ L& operator<<=(VQ L&, R);
8090 // VQ L& operator>>=(VQ L&, R);
8091 // VQ L& operator&=(VQ L&, R);
8092 // VQ L& operator^=(VQ L&, R);
8093 // VQ L& operator|=(VQ L&, R);
8094 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008095 if (!HasArithmeticOrEnumeralCandidateType)
8096 return;
8097
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008098 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8099 for (unsigned Right = FirstPromotedIntegralType;
8100 Right < LastPromotedIntegralType; ++Right) {
8101 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008102 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008103
8104 // Add this built-in operator as a candidate (VQ is empty).
8105 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008106 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008107 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008108 if (VisibleTypeConversionsQuals.hasVolatile()) {
8109 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008110 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008111 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8112 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008113 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008114 }
8115 }
8116 }
8117 }
8118
8119 // C++ [over.operator]p23:
8120 //
8121 // There also exist candidate operator functions of the form
8122 //
8123 // bool operator!(bool);
8124 // bool operator&&(bool, bool);
8125 // bool operator||(bool, bool);
8126 void addExclaimOverload() {
8127 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008128 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008129 /*IsAssignmentOperator=*/false,
8130 /*NumContextualBoolArguments=*/1);
8131 }
8132 void addAmpAmpOrPipePipeOverload() {
8133 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008134 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008135 /*IsAssignmentOperator=*/false,
8136 /*NumContextualBoolArguments=*/2);
8137 }
8138
8139 // C++ [over.built]p13:
8140 //
8141 // For every cv-qualified or cv-unqualified object type T there
8142 // exist candidate operator functions of the form
8143 //
8144 // T* operator+(T*, ptrdiff_t); [ABOVE]
8145 // T& operator[](T*, ptrdiff_t);
8146 // T* operator-(T*, ptrdiff_t); [ABOVE]
8147 // T* operator+(ptrdiff_t, T*); [ABOVE]
8148 // T& operator[](ptrdiff_t, T*);
8149 void addSubscriptOverloads() {
8150 for (BuiltinCandidateTypeSet::iterator
8151 Ptr = CandidateTypes[0].pointer_begin(),
8152 PtrEnd = CandidateTypes[0].pointer_end();
8153 Ptr != PtrEnd; ++Ptr) {
8154 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8155 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008156 if (!PointeeType->isObjectType())
8157 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008158
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008159 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8160
8161 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008162 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008163 }
8164
8165 for (BuiltinCandidateTypeSet::iterator
8166 Ptr = CandidateTypes[1].pointer_begin(),
8167 PtrEnd = CandidateTypes[1].pointer_end();
8168 Ptr != PtrEnd; ++Ptr) {
8169 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8170 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008171 if (!PointeeType->isObjectType())
8172 continue;
8173
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008174 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8175
8176 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008177 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008178 }
8179 }
8180
8181 // C++ [over.built]p11:
8182 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8183 // C1 is the same type as C2 or is a derived class of C2, T is an object
8184 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8185 // there exist candidate operator functions of the form
8186 //
8187 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8188 //
8189 // where CV12 is the union of CV1 and CV2.
8190 void addArrowStarOverloads() {
8191 for (BuiltinCandidateTypeSet::iterator
8192 Ptr = CandidateTypes[0].pointer_begin(),
8193 PtrEnd = CandidateTypes[0].pointer_end();
8194 Ptr != PtrEnd; ++Ptr) {
8195 QualType C1Ty = (*Ptr);
8196 QualType C1;
8197 QualifierCollector Q1;
8198 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8199 if (!isa<RecordType>(C1))
8200 continue;
8201 // heuristic to reduce number of builtin candidates in the set.
8202 // Add volatile/restrict version only if there are conversions to a
8203 // volatile/restrict type.
8204 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8205 continue;
8206 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8207 continue;
8208 for (BuiltinCandidateTypeSet::iterator
8209 MemPtr = CandidateTypes[1].member_pointer_begin(),
8210 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8211 MemPtr != MemPtrEnd; ++MemPtr) {
8212 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8213 QualType C2 = QualType(mptr->getClass(), 0);
8214 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008215 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008216 break;
8217 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8218 // build CV12 T&
8219 QualType T = mptr->getPointeeType();
8220 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8221 T.isVolatileQualified())
8222 continue;
8223 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8224 T.isRestrictQualified())
8225 continue;
8226 T = Q1.apply(S.Context, T);
8227 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008228 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008229 }
8230 }
8231 }
8232
8233 // Note that we don't consider the first argument, since it has been
8234 // contextually converted to bool long ago. The candidates below are
8235 // therefore added as binary.
8236 //
8237 // C++ [over.built]p25:
8238 // For every type T, where T is a pointer, pointer-to-member, or scoped
8239 // enumeration type, there exist candidate operator functions of the form
8240 //
8241 // T operator?(bool, T, T);
8242 //
8243 void addConditionalOperatorOverloads() {
8244 /// Set of (canonical) types that we've already handled.
8245 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8246
8247 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8248 for (BuiltinCandidateTypeSet::iterator
8249 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8250 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8251 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008252 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008253 continue;
8254
8255 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008256 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008257 }
8258
8259 for (BuiltinCandidateTypeSet::iterator
8260 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8261 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8262 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008263 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008264 continue;
8265
8266 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008267 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008268 }
8269
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008270 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008271 for (BuiltinCandidateTypeSet::iterator
8272 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8273 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8274 Enum != EnumEnd; ++Enum) {
8275 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8276 continue;
8277
David Blaikie82e95a32014-11-19 07:49:47 +00008278 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008279 continue;
8280
8281 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008282 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008283 }
8284 }
8285 }
8286 }
8287};
8288
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008289} // end anonymous namespace
8290
8291/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8292/// operator overloads to the candidate set (C++ [over.built]), based
8293/// on the operator @p Op and the arguments given. For example, if the
8294/// operator is a binary '+', this routine might add "int
8295/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008296void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8297 SourceLocation OpLoc,
8298 ArrayRef<Expr *> Args,
8299 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008300 // Find all of the types that the arguments can convert to, but only
8301 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008302 // that make use of these types. Also record whether we encounter non-record
8303 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008304 Qualifiers VisibleTypeConversionsQuals;
8305 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008306 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008307 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008308
8309 bool HasNonRecordCandidateType = false;
8310 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008311 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008312 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008313 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008314 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8315 OpLoc,
8316 true,
8317 (Op == OO_Exclaim ||
8318 Op == OO_AmpAmp ||
8319 Op == OO_PipePipe),
8320 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008321 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8322 CandidateTypes[ArgIdx].hasNonRecordTypes();
8323 HasArithmeticOrEnumeralCandidateType =
8324 HasArithmeticOrEnumeralCandidateType ||
8325 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008326 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008327
Chandler Carruth00a38332010-12-13 01:44:01 +00008328 // Exit early when no non-record types have been added to the candidate set
8329 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008330 //
8331 // We can't exit early for !, ||, or &&, since there we have always have
8332 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008333 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008334 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008335 return;
8336
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008337 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008338 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008339 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008340 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008341 CandidateTypes, CandidateSet);
8342
8343 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008344 switch (Op) {
8345 case OO_None:
8346 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008347 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008348
Chandler Carruth5184de02010-12-12 08:51:33 +00008349 case OO_New:
8350 case OO_Delete:
8351 case OO_Array_New:
8352 case OO_Array_Delete:
8353 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008354 llvm_unreachable(
8355 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008356
8357 case OO_Comma:
8358 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008359 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008360 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008361 // -- For the operator ',', the unary operator '&', the
8362 // operator '->', or the operator 'co_await', the
8363 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008364 break;
8365
8366 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008367 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008368 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008369 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008370
8371 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008372 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008373 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008374 } else {
8375 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8376 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8377 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008378 break;
8379
Chandler Carruth5184de02010-12-12 08:51:33 +00008380 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008381 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008382 OpBuilder.addUnaryStarPointerOverloads();
8383 else
8384 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8385 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008386
Chandler Carruth5184de02010-12-12 08:51:33 +00008387 case OO_Slash:
8388 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008389 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008390
8391 case OO_PlusPlus:
8392 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008393 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8394 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008395 break;
8396
Douglas Gregor84605ae2009-08-24 13:43:27 +00008397 case OO_EqualEqual:
8398 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008399 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008400 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008401
Douglas Gregora11693b2008-11-12 17:17:38 +00008402 case OO_Less:
8403 case OO_Greater:
8404 case OO_LessEqual:
8405 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008406 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008407 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8408 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008409
Douglas Gregora11693b2008-11-12 17:17:38 +00008410 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008411 case OO_Caret:
8412 case OO_Pipe:
8413 case OO_LessLess:
8414 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008415 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008416 break;
8417
Chandler Carruth5184de02010-12-12 08:51:33 +00008418 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008419 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008420 // C++ [over.match.oper]p3:
8421 // -- For the operator ',', the unary operator '&', or the
8422 // operator '->', the built-in candidates set is empty.
8423 break;
8424
8425 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8426 break;
8427
8428 case OO_Tilde:
8429 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8430 break;
8431
Douglas Gregora11693b2008-11-12 17:17:38 +00008432 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008433 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008434 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008435
8436 case OO_PlusEqual:
8437 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008438 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008439 // Fall through.
8440
8441 case OO_StarEqual:
8442 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008443 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008444 break;
8445
8446 case OO_PercentEqual:
8447 case OO_LessLessEqual:
8448 case OO_GreaterGreaterEqual:
8449 case OO_AmpEqual:
8450 case OO_CaretEqual:
8451 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008452 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008453 break;
8454
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008455 case OO_Exclaim:
8456 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008457 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008458
Douglas Gregora11693b2008-11-12 17:17:38 +00008459 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008460 case OO_PipePipe:
8461 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008462 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008463
8464 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008465 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008466 break;
8467
8468 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008469 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008470 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008471
8472 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008473 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008474 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8475 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008476 }
8477}
8478
Douglas Gregore254f902009-02-04 00:32:51 +00008479/// \brief Add function candidates found via argument-dependent lookup
8480/// to the set of overloading candidates.
8481///
8482/// This routine performs argument-dependent name lookup based on the
8483/// given function name (which may also be an operator name) and adds
8484/// all of the overload candidates found by ADL to the overload
8485/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008486void
Douglas Gregore254f902009-02-04 00:32:51 +00008487Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008488 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008489 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008490 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008491 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008492 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008493 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008494
John McCall91f61fc2010-01-26 06:04:06 +00008495 // FIXME: This approach for uniquing ADL results (and removing
8496 // redundant candidates from the set) relies on pointer-equality,
8497 // which means we need to key off the canonical decl. However,
8498 // always going back to the canonical decl might not get us the
8499 // right set of default arguments. What default arguments are
8500 // we supposed to consider on ADL candidates, anyway?
8501
Douglas Gregorcabea402009-09-22 15:41:20 +00008502 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008503 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008504
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008505 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008506 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8507 CandEnd = CandidateSet.end();
8508 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008509 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008510 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008511 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008512 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008513 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008514
8515 // For each of the ADL candidates we found, add it to the overload
8516 // set.
John McCall8fe68082010-01-26 07:16:45 +00008517 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008518 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008519 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008520 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008521 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008522
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008523 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8524 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008525 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008526 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008527 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008528 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008529 }
Douglas Gregore254f902009-02-04 00:32:51 +00008530}
8531
George Burgess IV3dc166912016-05-10 01:59:34 +00008532namespace {
8533enum class Comparison { Equal, Better, Worse };
8534}
8535
8536/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8537/// overload resolution.
8538///
8539/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8540/// Cand1's first N enable_if attributes have precisely the same conditions as
8541/// Cand2's first N enable_if attributes (where N = the number of enable_if
8542/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8543///
8544/// Note that you can have a pair of candidates such that Cand1's enable_if
8545/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8546/// worse than Cand1's.
8547static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8548 const FunctionDecl *Cand2) {
8549 // Common case: One (or both) decls don't have enable_if attrs.
8550 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8551 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8552 if (!Cand1Attr || !Cand2Attr) {
8553 if (Cand1Attr == Cand2Attr)
8554 return Comparison::Equal;
8555 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8556 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008557
8558 // FIXME: The next several lines are just
8559 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8560 // instead of reverse order which is how they're stored in the AST.
8561 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8562 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8563
George Burgess IV3dc166912016-05-10 01:59:34 +00008564 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8565 // has fewer enable_if attributes than Cand2.
8566 if (Cand1Attrs.size() < Cand2Attrs.size())
8567 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008568
8569 auto Cand1I = Cand1Attrs.begin();
8570 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8571 for (auto &Cand2A : Cand2Attrs) {
8572 Cand1ID.clear();
8573 Cand2ID.clear();
8574
8575 auto &Cand1A = *Cand1I++;
8576 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8577 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8578 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008579 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008580 }
8581
George Burgess IV3dc166912016-05-10 01:59:34 +00008582 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008583}
8584
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008585/// isBetterOverloadCandidate - Determines whether the first overload
8586/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008587bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8588 const OverloadCandidate &Cand2,
8589 SourceLocation Loc,
8590 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008591 // Define viable functions to be better candidates than non-viable
8592 // functions.
8593 if (!Cand2.Viable)
8594 return Cand1.Viable;
8595 else if (!Cand1.Viable)
8596 return false;
8597
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008598 // C++ [over.match.best]p1:
8599 //
8600 // -- if F is a static member function, ICS1(F) is defined such
8601 // that ICS1(F) is neither better nor worse than ICS1(G) for
8602 // any function G, and, symmetrically, ICS1(G) is neither
8603 // better nor worse than ICS1(F).
8604 unsigned StartArg = 0;
8605 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8606 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008607
George Burgess IVfbad5b22016-09-07 20:03:19 +00008608 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8609 // We don't allow incompatible pointer conversions in C++.
8610 if (!S.getLangOpts().CPlusPlus)
8611 return ICS.isStandard() &&
8612 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8613
8614 // The only ill-formed conversion we allow in C++ is the string literal to
8615 // char* conversion, which is only considered ill-formed after C++11.
8616 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8617 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8618 };
8619
8620 // Define functions that don't require ill-formed conversions for a given
8621 // argument to be better candidates than functions that do.
8622 unsigned NumArgs = Cand1.NumConversions;
8623 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8624 bool HasBetterConversion = false;
8625 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8626 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8627 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8628 if (Cand1Bad != Cand2Bad) {
8629 if (Cand1Bad)
8630 return false;
8631 HasBetterConversion = true;
8632 }
8633 }
8634
8635 if (HasBetterConversion)
8636 return true;
8637
Douglas Gregord3cb3562009-07-07 23:38:56 +00008638 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008639 // A viable function F1 is defined to be a better function than another
8640 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008641 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008642 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008643 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008644 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008645 Cand2.Conversions[ArgIdx])) {
8646 case ImplicitConversionSequence::Better:
8647 // Cand1 has a better conversion sequence.
8648 HasBetterConversion = true;
8649 break;
8650
8651 case ImplicitConversionSequence::Worse:
8652 // Cand1 can't be better than Cand2.
8653 return false;
8654
8655 case ImplicitConversionSequence::Indistinguishable:
8656 // Do nothing.
8657 break;
8658 }
8659 }
8660
Mike Stump11289f42009-09-09 15:08:12 +00008661 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008662 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008663 if (HasBetterConversion)
8664 return true;
8665
Douglas Gregora1f013e2008-11-07 22:36:19 +00008666 // -- the context is an initialization by user-defined conversion
8667 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8668 // from the return type of F1 to the destination type (i.e.,
8669 // the type of the entity being initialized) is a better
8670 // conversion sequence than the standard conversion sequence
8671 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008672 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008673 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008674 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008675 // First check whether we prefer one of the conversion functions over the
8676 // other. This only distinguishes the results in non-standard, extension
8677 // cases such as the conversion from a lambda closure type to a function
8678 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008679 ImplicitConversionSequence::CompareKind Result =
8680 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8681 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008682 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008683 Cand1.FinalConversion,
8684 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008685
Richard Smithec2748a2014-05-17 04:36:39 +00008686 if (Result != ImplicitConversionSequence::Indistinguishable)
8687 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008688
8689 // FIXME: Compare kind of reference binding if conversion functions
8690 // convert to a reference type used in direct reference binding, per
8691 // C++14 [over.match.best]p1 section 2 bullet 3.
8692 }
8693
8694 // -- F1 is a non-template function and F2 is a function template
8695 // specialization, or, if not that,
8696 bool Cand1IsSpecialization = Cand1.Function &&
8697 Cand1.Function->getPrimaryTemplate();
8698 bool Cand2IsSpecialization = Cand2.Function &&
8699 Cand2.Function->getPrimaryTemplate();
8700 if (Cand1IsSpecialization != Cand2IsSpecialization)
8701 return Cand2IsSpecialization;
8702
8703 // -- F1 and F2 are function template specializations, and the function
8704 // template for F1 is more specialized than the template for F2
8705 // according to the partial ordering rules described in 14.5.5.2, or,
8706 // if not that,
8707 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8708 if (FunctionTemplateDecl *BetterTemplate
8709 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8710 Cand2.Function->getPrimaryTemplate(),
8711 Loc,
8712 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8713 : TPOC_Call,
8714 Cand1.ExplicitCallArguments,
8715 Cand2.ExplicitCallArguments))
8716 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008717 }
8718
Richard Smith5179eb72016-06-28 19:03:57 +00008719 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8720 // A derived-class constructor beats an (inherited) base class constructor.
8721 bool Cand1IsInherited =
8722 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8723 bool Cand2IsInherited =
8724 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8725 if (Cand1IsInherited != Cand2IsInherited)
8726 return Cand2IsInherited;
8727 else if (Cand1IsInherited) {
8728 assert(Cand2IsInherited);
8729 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8730 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8731 if (Cand1Class->isDerivedFrom(Cand2Class))
8732 return true;
8733 if (Cand2Class->isDerivedFrom(Cand1Class))
8734 return false;
8735 // Inherited from sibling base classes: still ambiguous.
8736 }
8737
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008738 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00008739 if (Cand1.Function && Cand2.Function) {
8740 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8741 if (Cmp != Comparison::Equal)
8742 return Cmp == Comparison::Better;
8743 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008744
Justin Lebar25c4a812016-03-29 16:24:16 +00008745 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008746 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8747 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8748 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8749 }
8750
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008751 bool HasPS1 = Cand1.Function != nullptr &&
8752 functionHasPassObjectSizeParams(Cand1.Function);
8753 bool HasPS2 = Cand2.Function != nullptr &&
8754 functionHasPassObjectSizeParams(Cand2.Function);
8755 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008756}
8757
Richard Smith2dbe4042015-11-04 19:26:32 +00008758/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008759/// name lookup and overload resolution. This applies when the same internal/no
8760/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008761/// the same header). In such a case, we don't consider the declarations to
8762/// declare the same entity, but we also don't want lookups with both
8763/// declarations visible to be ambiguous in some cases (this happens when using
8764/// a modularized libstdc++).
8765bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8766 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008767 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8768 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8769 if (!VA || !VB)
8770 return false;
8771
8772 // The declarations must be declaring the same name as an internal linkage
8773 // entity in different modules.
8774 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8775 VB->getDeclContext()->getRedeclContext()) ||
8776 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8777 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8778 VA->isExternallyVisible() || VB->isExternallyVisible())
8779 return false;
8780
8781 // Check that the declarations appear to be equivalent.
8782 //
8783 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8784 // For constants and functions, we should check the initializer or body is
8785 // the same. For non-constant variables, we shouldn't allow it at all.
8786 if (Context.hasSameType(VA->getType(), VB->getType()))
8787 return true;
8788
8789 // Enum constants within unnamed enumerations will have different types, but
8790 // may still be similar enough to be interchangeable for our purposes.
8791 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8792 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8793 // Only handle anonymous enums. If the enumerations were named and
8794 // equivalent, they would have been merged to the same type.
8795 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8796 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8797 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8798 !Context.hasSameType(EnumA->getIntegerType(),
8799 EnumB->getIntegerType()))
8800 return false;
8801 // Allow this only if the value is the same for both enumerators.
8802 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8803 }
8804 }
8805
8806 // Nothing else is sufficiently similar.
8807 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008808}
8809
8810void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8811 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8812 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8813
8814 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8815 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8816 << !M << (M ? M->getFullModuleName() : "");
8817
8818 for (auto *E : Equiv) {
8819 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8820 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8821 << !M << (M ? M->getFullModuleName() : "");
8822 }
Richard Smith896c66e2015-10-21 07:13:52 +00008823}
8824
Mike Stump11289f42009-09-09 15:08:12 +00008825/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008826/// within an overload candidate set.
8827///
James Dennettffad8b72012-06-22 08:10:18 +00008828/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008829/// which overload resolution occurs.
8830///
James Dennettffad8b72012-06-22 08:10:18 +00008831/// \param Best If overload resolution was successful or found a deleted
8832/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008833///
8834/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008835OverloadingResult
8836OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008837 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008838 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008839 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8840 std::transform(begin(), end(), std::back_inserter(Candidates),
8841 [](OverloadCandidate &Cand) { return &Cand; });
8842
Justin Lebar66a2ab92016-08-10 00:40:43 +00008843 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8844 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00008845 // compilation mode only one call variant is viable. We need to
8846 // exclude non-viable overload candidates from consideration based
8847 // only on their host/device attributes. Specifically, if one
8848 // candidate call is WrongSide and the other is SameSide, we ignore
8849 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008850 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008851 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8852 bool ContainsSameSideCandidate =
8853 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8854 return Cand->Function &&
8855 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8856 Sema::CFP_SameSide;
8857 });
8858 if (ContainsSameSideCandidate) {
8859 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8860 return Cand->Function &&
8861 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8862 Sema::CFP_WrongSide;
8863 };
8864 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8865 IsWrongSideCandidate),
8866 Candidates.end());
8867 }
8868 }
8869
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008870 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008871 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008872 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008873 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008874 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008875 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008876 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008877
8878 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008879 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008880 return OR_No_Viable_Function;
8881
Richard Smith2dbe4042015-11-04 19:26:32 +00008882 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008883
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008884 // Make sure that this function is better than every other viable
8885 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008886 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008887 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008888 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008889 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008890 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008891 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8892 Cand->Function)) {
8893 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008894 continue;
8895 }
8896
John McCall5c32be02010-08-24 20:38:10 +00008897 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008898 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008899 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008900 }
Mike Stump11289f42009-09-09 15:08:12 +00008901
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008902 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008903 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008904 (Best->Function->isDeleted() ||
8905 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008906 return OR_Deleted;
8907
Richard Smith2dbe4042015-11-04 19:26:32 +00008908 if (!EquivalentCands.empty())
8909 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8910 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008911
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008912 return OR_Success;
8913}
8914
John McCall53262c92010-01-12 02:15:36 +00008915namespace {
8916
8917enum OverloadCandidateKind {
8918 oc_function,
8919 oc_method,
8920 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008921 oc_function_template,
8922 oc_method_template,
8923 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008924 oc_implicit_default_constructor,
8925 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008926 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008927 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008928 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00008929 oc_inherited_constructor,
8930 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00008931};
8932
John McCalle1ac8d12010-01-13 00:25:19 +00008933OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
Richard Smithc2bebe92016-05-11 20:37:46 +00008934 NamedDecl *Found,
John McCalle1ac8d12010-01-13 00:25:19 +00008935 FunctionDecl *Fn,
8936 std::string &Description) {
8937 bool isTemplate = false;
8938
8939 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8940 isTemplate = true;
8941 Description = S.getTemplateArgumentBindingsText(
8942 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8943 }
John McCallfd0b2f82010-01-06 09:43:14 +00008944
8945 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00008946 if (!Ctor->isImplicit()) {
8947 if (isa<ConstructorUsingShadowDecl>(Found))
8948 return isTemplate ? oc_inherited_constructor_template
8949 : oc_inherited_constructor;
8950 else
8951 return isTemplate ? oc_constructor_template : oc_constructor;
8952 }
Sebastian Redl08905022011-02-05 19:23:19 +00008953
Alexis Hunt119c10e2011-05-25 23:16:36 +00008954 if (Ctor->isDefaultConstructor())
8955 return oc_implicit_default_constructor;
8956
8957 if (Ctor->isMoveConstructor())
8958 return oc_implicit_move_constructor;
8959
8960 assert(Ctor->isCopyConstructor() &&
8961 "unexpected sort of implicit constructor");
8962 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008963 }
8964
8965 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8966 // This actually gets spelled 'candidate function' for now, but
8967 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008968 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008969 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008970
Alexis Hunt119c10e2011-05-25 23:16:36 +00008971 if (Meth->isMoveAssignmentOperator())
8972 return oc_implicit_move_assignment;
8973
Douglas Gregor12695102012-02-10 08:36:38 +00008974 if (Meth->isCopyAssignmentOperator())
8975 return oc_implicit_copy_assignment;
8976
8977 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8978 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008979 }
8980
John McCalle1ac8d12010-01-13 00:25:19 +00008981 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008982}
8983
Richard Smith5179eb72016-06-28 19:03:57 +00008984void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
8985 // FIXME: It'd be nice to only emit a note once per using-decl per overload
8986 // set.
8987 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
8988 S.Diag(FoundDecl->getLocation(),
8989 diag::note_ovl_candidate_inherited_constructor)
8990 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00008991}
8992
John McCall53262c92010-01-12 02:15:36 +00008993} // end anonymous namespace
8994
George Burgess IV5f21c712015-10-12 19:57:04 +00008995static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8996 const FunctionDecl *FD) {
8997 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8998 bool AlwaysTrue;
8999 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9000 return false;
9001 if (!AlwaysTrue)
9002 return false;
9003 }
9004 return true;
9005}
9006
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009007/// \brief Returns true if we can take the address of the function.
9008///
9009/// \param Complain - If true, we'll emit a diagnostic
9010/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9011/// we in overload resolution?
9012/// \param Loc - The location of the statement we're complaining about. Ignored
9013/// if we're not complaining, or if we're in overload resolution.
9014static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9015 bool Complain,
9016 bool InOverloadResolution,
9017 SourceLocation Loc) {
9018 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9019 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009020 if (InOverloadResolution)
9021 S.Diag(FD->getLocStart(),
9022 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9023 else
9024 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9025 }
9026 return false;
9027 }
9028
George Burgess IV21081362016-07-24 23:12:40 +00009029 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9030 return P->hasAttr<PassObjectSizeAttr>();
9031 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009032 if (I == FD->param_end())
9033 return true;
9034
9035 if (Complain) {
9036 // Add one to ParamNo because it's user-facing
9037 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9038 if (InOverloadResolution)
9039 S.Diag(FD->getLocation(),
9040 diag::note_ovl_candidate_has_pass_object_size_params)
9041 << ParamNo;
9042 else
9043 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9044 << FD << ParamNo;
9045 }
9046 return false;
9047}
9048
9049static bool checkAddressOfCandidateIsAvailable(Sema &S,
9050 const FunctionDecl *FD) {
9051 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9052 /*InOverloadResolution=*/true,
9053 /*Loc=*/SourceLocation());
9054}
9055
9056bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9057 bool Complain,
9058 SourceLocation Loc) {
9059 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9060 /*InOverloadResolution=*/false,
9061 Loc);
9062}
9063
John McCall53262c92010-01-12 02:15:36 +00009064// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009065void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9066 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009067 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9068 return;
9069
John McCalle1ac8d12010-01-13 00:25:19 +00009070 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009071 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009072 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9073 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009074
9075 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009076 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009077 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009078}
9079
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009080// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009081// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009082void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9083 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009084 assert(OverloadedExpr->getType() == Context.OverloadTy);
9085
9086 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9087 OverloadExpr *OvlExpr = Ovl.Expression;
9088
9089 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9090 IEnd = OvlExpr->decls_end();
9091 I != IEnd; ++I) {
9092 if (FunctionTemplateDecl *FunTmpl =
9093 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009094 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009095 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009096 } else if (FunctionDecl *Fun
9097 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009098 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009099 }
9100 }
9101}
9102
John McCall0d1da222010-01-12 00:44:57 +00009103/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9104/// "lead" diagnostic; it will be given two arguments, the source and
9105/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009106void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9107 Sema &S,
9108 SourceLocation CaretLoc,
9109 const PartialDiagnostic &PDiag) const {
9110 S.Diag(CaretLoc, PDiag)
9111 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009112 // FIXME: The note limiting machinery is borrowed from
9113 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9114 // refactoring here.
9115 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9116 unsigned CandsShown = 0;
9117 AmbiguousConversionSequence::const_iterator I, E;
9118 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9119 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9120 break;
9121 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009122 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009123 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009124 if (I != E)
9125 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009126}
9127
Richard Smith17c00b42014-11-12 01:24:00 +00009128static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009129 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009130 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9131 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009132 assert(Cand->Function && "for now, candidate must be a function");
9133 FunctionDecl *Fn = Cand->Function;
9134
9135 // There's a conversion slot for the object argument if this is a
9136 // non-constructor method. Note that 'I' corresponds the
9137 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009138 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009139 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009140 if (I == 0)
9141 isObjectArgument = true;
9142 else
9143 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009144 }
9145
John McCalle1ac8d12010-01-13 00:25:19 +00009146 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009147 OverloadCandidateKind FnKind =
9148 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009149
John McCall6a61b522010-01-13 09:16:55 +00009150 Expr *FromExpr = Conv.Bad.FromExpr;
9151 QualType FromTy = Conv.Bad.getFromType();
9152 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009153
John McCallfb7ad0f2010-02-02 02:42:52 +00009154 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009155 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009156 Expr *E = FromExpr->IgnoreParens();
9157 if (isa<UnaryOperator>(E))
9158 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009159 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009160
9161 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9162 << (unsigned) FnKind << FnDesc
9163 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9164 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009165 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009166 return;
9167 }
9168
John McCall6d174642010-01-23 08:10:49 +00009169 // Do some hand-waving analysis to see if the non-viability is due
9170 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009171 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9172 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9173 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9174 CToTy = RT->getPointeeType();
9175 else {
9176 // TODO: detect and diagnose the full richness of const mismatches.
9177 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009178 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9179 CFromTy = FromPT->getPointeeType();
9180 CToTy = ToPT->getPointeeType();
9181 }
John McCall47000992010-01-14 03:28:57 +00009182 }
9183
9184 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9185 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009186 Qualifiers FromQs = CFromTy.getQualifiers();
9187 Qualifiers ToQs = CToTy.getQualifiers();
9188
9189 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9190 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9191 << (unsigned) FnKind << FnDesc
9192 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9193 << FromTy
9194 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9195 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009196 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009197 return;
9198 }
9199
John McCall31168b02011-06-15 23:02:42 +00009200 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009201 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009202 << (unsigned) FnKind << FnDesc
9203 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9204 << FromTy
9205 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9206 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009207 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009208 return;
9209 }
9210
Douglas Gregoraec25842011-04-26 23:16:46 +00009211 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9212 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9213 << (unsigned) FnKind << FnDesc
9214 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9215 << FromTy
9216 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9217 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009218 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009219 return;
9220 }
9221
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009222 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9223 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9224 << (unsigned) FnKind << FnDesc
9225 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9226 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009227 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009228 return;
9229 }
9230
John McCall47000992010-01-14 03:28:57 +00009231 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9232 assert(CVR && "unexpected qualifiers mismatch");
9233
9234 if (isObjectArgument) {
9235 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9236 << (unsigned) FnKind << FnDesc
9237 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9238 << FromTy << (CVR - 1);
9239 } else {
9240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9241 << (unsigned) FnKind << FnDesc
9242 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9243 << FromTy << (CVR - 1) << I+1;
9244 }
Richard Smith5179eb72016-06-28 19:03:57 +00009245 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009246 return;
9247 }
9248
Sebastian Redla72462c2011-09-24 17:48:32 +00009249 // Special diagnostic for failure to convert an initializer list, since
9250 // telling the user that it has type void is not useful.
9251 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9252 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9253 << (unsigned) FnKind << FnDesc
9254 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9255 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009256 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009257 return;
9258 }
9259
John McCall6d174642010-01-23 08:10:49 +00009260 // Diagnose references or pointers to incomplete types differently,
9261 // since it's far from impossible that the incompleteness triggered
9262 // the failure.
9263 QualType TempFromTy = FromTy.getNonReferenceType();
9264 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9265 TempFromTy = PTy->getPointeeType();
9266 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009267 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009268 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9269 << (unsigned) FnKind << FnDesc
9270 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009271 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9272 << (unsigned) (Cand->Fix.Kind);
9273
Richard Smith5179eb72016-06-28 19:03:57 +00009274 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009275 return;
9276 }
9277
Douglas Gregor56f2e342010-06-30 23:01:39 +00009278 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009279 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009280 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9281 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9282 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9283 FromPtrTy->getPointeeType()) &&
9284 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9285 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009286 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009287 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009288 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009289 }
9290 } else if (const ObjCObjectPointerType *FromPtrTy
9291 = FromTy->getAs<ObjCObjectPointerType>()) {
9292 if (const ObjCObjectPointerType *ToPtrTy
9293 = ToTy->getAs<ObjCObjectPointerType>())
9294 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9295 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9296 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9297 FromPtrTy->getPointeeType()) &&
9298 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009299 BaseToDerivedConversion = 2;
9300 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009301 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9302 !FromTy->isIncompleteType() &&
9303 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009304 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009305 BaseToDerivedConversion = 3;
9306 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9307 ToTy.getNonReferenceType().getCanonicalType() ==
9308 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009309 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9310 << (unsigned) FnKind << FnDesc
9311 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9312 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009313 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009314 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009315 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009317
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009318 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009319 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009320 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009321 << (unsigned) FnKind << FnDesc
9322 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009323 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009324 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009325 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009326 return;
9327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009328
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009329 if (isa<ObjCObjectPointerType>(CFromTy) &&
9330 isa<PointerType>(CToTy)) {
9331 Qualifiers FromQs = CFromTy.getQualifiers();
9332 Qualifiers ToQs = CToTy.getQualifiers();
9333 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9334 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9335 << (unsigned) FnKind << FnDesc
9336 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9337 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009338 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009339 return;
9340 }
9341 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009342
9343 if (TakingCandidateAddress &&
9344 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9345 return;
9346
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009347 // Emit the generic diagnostic and, optionally, add the hints to it.
9348 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9349 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009350 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009351 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9352 << (unsigned) (Cand->Fix.Kind);
9353
9354 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009355 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9356 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009357 FDiag << *HI;
9358 S.Diag(Fn->getLocation(), FDiag);
9359
Richard Smith5179eb72016-06-28 19:03:57 +00009360 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009361}
9362
Larisse Voufo98b20f12013-07-19 23:00:19 +00009363/// Additional arity mismatch diagnosis specific to a function overload
9364/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9365/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009366static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9367 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009368 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009369 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009370
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009371 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009372 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009373 // right number of arguments, because only overloaded operators have
9374 // the weird behavior of overloading member and non-member functions.
9375 // Just don't report anything.
9376 if (Fn->isInvalidDecl() &&
9377 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009378 return true;
9379
9380 if (NumArgs < MinParams) {
9381 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9382 (Cand->FailureKind == ovl_fail_bad_deduction &&
9383 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9384 } else {
9385 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9386 (Cand->FailureKind == ovl_fail_bad_deduction &&
9387 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9388 }
9389
9390 return false;
9391}
9392
9393/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009394static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9395 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009396 assert(isa<FunctionDecl>(D) &&
9397 "The templated declaration should at least be a function"
9398 " when diagnosing bad template argument deduction due to too many"
9399 " or too few arguments");
9400
9401 FunctionDecl *Fn = cast<FunctionDecl>(D);
9402
9403 // TODO: treat calls to a missing default constructor as a special case
9404 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9405 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009406
John McCall6a61b522010-01-13 09:16:55 +00009407 // at least / at most / exactly
9408 unsigned mode, modeCount;
9409 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009410 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9411 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009412 mode = 0; // "at least"
9413 else
9414 mode = 2; // "exactly"
9415 modeCount = MinParams;
9416 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009417 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009418 mode = 1; // "at most"
9419 else
9420 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009421 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009422 }
9423
9424 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009425 OverloadCandidateKind FnKind =
9426 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009427
Richard Smith10ff50d2012-05-11 05:16:41 +00009428 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9429 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009430 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9431 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009432 else
9433 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009434 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9435 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009436 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009437}
9438
Larisse Voufo98b20f12013-07-19 23:00:19 +00009439/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009440static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9441 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009442 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009443 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009444}
Larisse Voufo47c08452013-07-19 22:53:23 +00009445
Richard Smith17c00b42014-11-12 01:24:00 +00009446static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009447 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9448 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009449 llvm_unreachable("Unsupported: Getting the described template declaration"
9450 " for bad deduction diagnosis");
9451}
9452
9453/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009454static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009455 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009456 unsigned NumArgs,
9457 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009458 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009459 NamedDecl *ParamD;
9460 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9461 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9462 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009463 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009464 case Sema::TDK_Success:
9465 llvm_unreachable("TDK_success while diagnosing bad deduction");
9466
9467 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009468 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009469 S.Diag(Templated->getLocation(),
9470 diag::note_ovl_candidate_incomplete_deduction)
9471 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009472 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009473 return;
9474 }
9475
John McCall42d7d192010-08-05 09:05:08 +00009476 case Sema::TDK_Underqualified: {
9477 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9478 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9479
Larisse Voufo98b20f12013-07-19 23:00:19 +00009480 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009481
9482 // Param will have been canonicalized, but it should just be a
9483 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009484 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009485 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009486 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009487 assert(S.Context.hasSameType(Param, NonCanonParam));
9488
9489 // Arg has also been canonicalized, but there's nothing we can do
9490 // about that. It also doesn't matter as much, because it won't
9491 // have any template parameters in it (because deduction isn't
9492 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009493 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009494
Larisse Voufo98b20f12013-07-19 23:00:19 +00009495 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9496 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009497 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009498 return;
9499 }
9500
9501 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009502 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009503 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009504 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009505 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009506 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009507 which = 1;
9508 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009509 which = 2;
9510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009511
Larisse Voufo98b20f12013-07-19 23:00:19 +00009512 S.Diag(Templated->getLocation(),
9513 diag::note_ovl_candidate_inconsistent_deduction)
9514 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9515 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009516 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009517 return;
9518 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009519
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009520 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009521 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009522 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009523 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009524 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009525 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009526 else {
9527 int index = 0;
9528 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9529 index = TTP->getIndex();
9530 else if (NonTypeTemplateParmDecl *NTTP
9531 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9532 index = NTTP->getIndex();
9533 else
9534 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009535 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009536 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009537 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009538 }
Richard Smith5179eb72016-06-28 19:03:57 +00009539 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009540 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009541
Douglas Gregor02eb4832010-05-08 18:13:28 +00009542 case Sema::TDK_TooManyArguments:
9543 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009544 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009545 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009546
9547 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009548 S.Diag(Templated->getLocation(),
9549 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009550 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009551 return;
9552
9553 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009554 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009555 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009556 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009557 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009558 TemplateArgString = " ";
9559 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009560 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009561 }
9562
Richard Smith6f8d2c62012-05-09 05:17:00 +00009563 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009564 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009565 if (PDiag && PDiag->second.getDiagID() ==
9566 diag::err_typename_nested_not_found_enable_if) {
9567 // FIXME: Use the source range of the condition, and the fully-qualified
9568 // name of the enable_if template. These are both present in PDiag.
9569 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9570 << "'enable_if'" << TemplateArgString;
9571 return;
9572 }
9573
Richard Smith9ca64612012-05-07 09:03:25 +00009574 // Format the SFINAE diagnostic into the argument string.
9575 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9576 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009577 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009578 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009579 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009580 SFINAEArgString = ": ";
9581 R = SourceRange(PDiag->first, PDiag->first);
9582 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9583 }
9584
Larisse Voufo98b20f12013-07-19 23:00:19 +00009585 S.Diag(Templated->getLocation(),
9586 diag::note_ovl_candidate_substitution_failure)
9587 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009588 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009589 return;
9590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009591
Richard Smith8c6eeb92013-01-31 04:03:12 +00009592 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009593 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9594 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009595 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009596 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009597 return;
9598 }
9599
Richard Smith9b534542015-12-31 02:02:54 +00009600 case Sema::TDK_DeducedMismatch: {
9601 // Format the template argument list into the argument string.
9602 SmallString<128> TemplateArgString;
9603 if (TemplateArgumentList *Args =
9604 DeductionFailure.getTemplateArgumentList()) {
9605 TemplateArgString = " ";
9606 TemplateArgString += S.getTemplateArgumentBindingsText(
9607 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9608 }
9609
9610 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9611 << (*DeductionFailure.getCallArgIndex() + 1)
9612 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9613 << TemplateArgString;
9614 break;
9615 }
9616
Richard Trieue3732352013-04-08 21:11:40 +00009617 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009618 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009619 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9620 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009621 if (FirstTA.getKind() == TemplateArgument::Template &&
9622 SecondTA.getKind() == TemplateArgument::Template) {
9623 TemplateName FirstTN = FirstTA.getAsTemplate();
9624 TemplateName SecondTN = SecondTA.getAsTemplate();
9625 if (FirstTN.getKind() == TemplateName::Template &&
9626 SecondTN.getKind() == TemplateName::Template) {
9627 if (FirstTN.getAsTemplateDecl()->getName() ==
9628 SecondTN.getAsTemplateDecl()->getName()) {
9629 // FIXME: This fixes a bad diagnostic where both templates are named
9630 // the same. This particular case is a bit difficult since:
9631 // 1) It is passed as a string to the diagnostic printer.
9632 // 2) The diagnostic printer only attempts to find a better
9633 // name for types, not decls.
9634 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009635 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009636 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9637 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9638 return;
9639 }
9640 }
9641 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009642
9643 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9644 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9645 return;
9646
Faisal Vali2b391ab2013-09-26 19:54:12 +00009647 // FIXME: For generic lambda parameters, check if the function is a lambda
9648 // call operator, and if so, emit a prettier and more informative
9649 // diagnostic that mentions 'auto' and lambda in addition to
9650 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009651 S.Diag(Templated->getLocation(),
9652 diag::note_ovl_candidate_non_deduced_mismatch)
9653 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009654 return;
Richard Trieue3732352013-04-08 21:11:40 +00009655 }
John McCall8b9ed552010-02-01 18:53:26 +00009656 // TODO: diagnose these individually, then kill off
9657 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009658 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009659 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009660 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009661 return;
9662 }
9663}
9664
Larisse Voufo98b20f12013-07-19 23:00:19 +00009665/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009666static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009667 unsigned NumArgs,
9668 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009669 unsigned TDK = Cand->DeductionFailure.Result;
9670 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9671 if (CheckArityMismatch(S, Cand, NumArgs))
9672 return;
9673 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009674 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009675 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009676}
9677
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009678/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009679static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009680 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9681 FunctionDecl *Callee = Cand->Function;
9682
9683 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9684 CalleeTarget = S.IdentifyCUDATarget(Callee);
9685
9686 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009687 OverloadCandidateKind FnKind =
9688 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009689
9690 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009691 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9692
9693 // This could be an implicit constructor for which we could not infer the
9694 // target due to a collsion. Diagnose that case.
9695 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9696 if (Meth != nullptr && Meth->isImplicit()) {
9697 CXXRecordDecl *ParentClass = Meth->getParent();
9698 Sema::CXXSpecialMember CSM;
9699
9700 switch (FnKind) {
9701 default:
9702 return;
9703 case oc_implicit_default_constructor:
9704 CSM = Sema::CXXDefaultConstructor;
9705 break;
9706 case oc_implicit_copy_constructor:
9707 CSM = Sema::CXXCopyConstructor;
9708 break;
9709 case oc_implicit_move_constructor:
9710 CSM = Sema::CXXMoveConstructor;
9711 break;
9712 case oc_implicit_copy_assignment:
9713 CSM = Sema::CXXCopyAssignment;
9714 break;
9715 case oc_implicit_move_assignment:
9716 CSM = Sema::CXXMoveAssignment;
9717 break;
9718 };
9719
9720 bool ConstRHS = false;
9721 if (Meth->getNumParams()) {
9722 if (const ReferenceType *RT =
9723 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9724 ConstRHS = RT->getPointeeType().isConstQualified();
9725 }
9726 }
9727
9728 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9729 /* ConstRHS */ ConstRHS,
9730 /* Diagnose */ true);
9731 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009732}
9733
Richard Smith17c00b42014-11-12 01:24:00 +00009734static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009735 FunctionDecl *Callee = Cand->Function;
9736 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9737
9738 S.Diag(Callee->getLocation(),
9739 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9740 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9741}
9742
John McCall8b9ed552010-02-01 18:53:26 +00009743/// Generates a 'note' diagnostic for an overload candidate. We've
9744/// already generated a primary error at the call site.
9745///
9746/// It really does need to be a single diagnostic with its caret
9747/// pointed at the candidate declaration. Yes, this creates some
9748/// major challenges of technical writing. Yes, this makes pointing
9749/// out problems with specific arguments quite awkward. It's still
9750/// better than generating twenty screens of text for every failed
9751/// overload.
9752///
9753/// It would be great to be able to express per-candidate problems
9754/// more richly for those diagnostic clients that cared, but we'd
9755/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009756static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009757 unsigned NumArgs,
9758 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009759 FunctionDecl *Fn = Cand->Function;
9760
John McCall12f97bc2010-01-08 04:41:39 +00009761 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009762 if (Cand->Viable && (Fn->isDeleted() ||
9763 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009764 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009765 OverloadCandidateKind FnKind =
9766 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009767
9768 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009769 << FnKind << FnDesc
9770 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009771 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCalld3224162010-01-08 00:58:21 +00009772 return;
John McCall12f97bc2010-01-08 04:41:39 +00009773 }
9774
John McCalle1ac8d12010-01-13 00:25:19 +00009775 // We don't really have anything else to say about viable candidates.
9776 if (Cand->Viable) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009777 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009778 return;
9779 }
John McCall0d1da222010-01-12 00:44:57 +00009780
John McCall6a61b522010-01-13 09:16:55 +00009781 switch (Cand->FailureKind) {
9782 case ovl_fail_too_many_arguments:
9783 case ovl_fail_too_few_arguments:
9784 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009785
John McCall6a61b522010-01-13 09:16:55 +00009786 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +00009787 return DiagnoseBadDeduction(S, Cand, NumArgs,
9788 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009789
John McCall578a1f82014-12-14 01:46:53 +00009790 case ovl_fail_illegal_constructor: {
9791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9792 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009793 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +00009794 return;
9795 }
9796
John McCallfe796dd2010-01-23 05:17:32 +00009797 case ovl_fail_trivial_conversion:
9798 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009799 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +00009800 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009801
John McCall65eb8792010-02-25 01:37:24 +00009802 case ovl_fail_bad_conversion: {
9803 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009804 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009805 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009806 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009807
John McCall6a61b522010-01-13 09:16:55 +00009808 // FIXME: this currently happens when we're called from SemaInit
9809 // when user-conversion overload fails. Figure out how to handle
9810 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +00009811 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009812 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009813
9814 case ovl_fail_bad_target:
9815 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009816
9817 case ovl_fail_enable_if:
9818 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009819
9820 case ovl_fail_addr_not_available: {
9821 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9822 (void)Available;
9823 assert(!Available);
9824 break;
9825 }
John McCall65eb8792010-02-25 01:37:24 +00009826 }
John McCalld3224162010-01-08 00:58:21 +00009827}
9828
Richard Smith17c00b42014-11-12 01:24:00 +00009829static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009830 // Desugar the type of the surrogate down to a function type,
9831 // retaining as many typedefs as possible while still showing
9832 // the function type (and, therefore, its parameter types).
9833 QualType FnType = Cand->Surrogate->getConversionType();
9834 bool isLValueReference = false;
9835 bool isRValueReference = false;
9836 bool isPointer = false;
9837 if (const LValueReferenceType *FnTypeRef =
9838 FnType->getAs<LValueReferenceType>()) {
9839 FnType = FnTypeRef->getPointeeType();
9840 isLValueReference = true;
9841 } else if (const RValueReferenceType *FnTypeRef =
9842 FnType->getAs<RValueReferenceType>()) {
9843 FnType = FnTypeRef->getPointeeType();
9844 isRValueReference = true;
9845 }
9846 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9847 FnType = FnTypePtr->getPointeeType();
9848 isPointer = true;
9849 }
9850 // Desugar down to a function type.
9851 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9852 // Reconstruct the pointer/reference as appropriate.
9853 if (isPointer) FnType = S.Context.getPointerType(FnType);
9854 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9855 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9856
9857 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9858 << FnType;
9859}
9860
Richard Smith17c00b42014-11-12 01:24:00 +00009861static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9862 SourceLocation OpLoc,
9863 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009864 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009865 std::string TypeStr("operator");
9866 TypeStr += Opc;
9867 TypeStr += "(";
9868 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009869 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009870 TypeStr += ")";
9871 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9872 } else {
9873 TypeStr += ", ";
9874 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9875 TypeStr += ")";
9876 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9877 }
9878}
9879
Richard Smith17c00b42014-11-12 01:24:00 +00009880static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9881 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009882 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009883 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9884 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009885 if (ICS.isBad()) break; // all meaningless after first invalid
9886 if (!ICS.isAmbiguous()) continue;
9887
Richard Smithc2bebe92016-05-11 20:37:46 +00009888 ICS.DiagnoseAmbiguousConversion(
9889 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009890 }
9891}
9892
Larisse Voufo98b20f12013-07-19 23:00:19 +00009893static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009894 if (Cand->Function)
9895 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009896 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009897 return Cand->Surrogate->getLocation();
9898 return SourceLocation();
9899}
9900
Larisse Voufo98b20f12013-07-19 23:00:19 +00009901static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009902 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009903 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009904 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009905
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009906 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009907 case Sema::TDK_Incomplete:
9908 return 1;
9909
9910 case Sema::TDK_Underqualified:
9911 case Sema::TDK_Inconsistent:
9912 return 2;
9913
9914 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009915 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009916 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009917 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009918 return 3;
9919
9920 case Sema::TDK_InstantiationDepth:
9921 case Sema::TDK_FailedOverloadResolution:
9922 return 4;
9923
9924 case Sema::TDK_InvalidExplicitArguments:
9925 return 5;
9926
9927 case Sema::TDK_TooManyArguments:
9928 case Sema::TDK_TooFewArguments:
9929 return 6;
9930 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009931 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009932}
9933
Richard Smith17c00b42014-11-12 01:24:00 +00009934namespace {
John McCallad2587a2010-01-12 00:48:53 +00009935struct CompareOverloadCandidatesForDisplay {
9936 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009937 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009938 size_t NumArgs;
9939
Richard Smith0f59cb32015-12-18 21:45:41 +00009940 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009941 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009942
9943 bool operator()(const OverloadCandidate *L,
9944 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009945 // Fast-path this check.
9946 if (L == R) return false;
9947
John McCall12f97bc2010-01-08 04:41:39 +00009948 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009949 if (L->Viable) {
9950 if (!R->Viable) return true;
9951
9952 // TODO: introduce a tri-valued comparison for overload
9953 // candidates. Would be more worthwhile if we had a sort
9954 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009955 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9956 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009957 } else if (R->Viable)
9958 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009959
John McCall3712d9e2010-01-15 23:32:50 +00009960 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009961
John McCall3712d9e2010-01-15 23:32:50 +00009962 // Criteria by which we can sort non-viable candidates:
9963 if (!L->Viable) {
9964 // 1. Arity mismatches come after other candidates.
9965 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009966 L->FailureKind == ovl_fail_too_few_arguments) {
9967 if (R->FailureKind == ovl_fail_too_many_arguments ||
9968 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009969 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9970 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9971 if (LDist == RDist) {
9972 if (L->FailureKind == R->FailureKind)
9973 // Sort non-surrogates before surrogates.
9974 return !L->IsSurrogate && R->IsSurrogate;
9975 // Sort candidates requiring fewer parameters than there were
9976 // arguments given after candidates requiring more parameters
9977 // than there were arguments given.
9978 return L->FailureKind == ovl_fail_too_many_arguments;
9979 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009980 return LDist < RDist;
9981 }
John McCall3712d9e2010-01-15 23:32:50 +00009982 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009983 }
John McCall3712d9e2010-01-15 23:32:50 +00009984 if (R->FailureKind == ovl_fail_too_many_arguments ||
9985 R->FailureKind == ovl_fail_too_few_arguments)
9986 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009987
John McCallfe796dd2010-01-23 05:17:32 +00009988 // 2. Bad conversions come first and are ordered by the number
9989 // of bad conversions and quality of good conversions.
9990 if (L->FailureKind == ovl_fail_bad_conversion) {
9991 if (R->FailureKind != ovl_fail_bad_conversion)
9992 return true;
9993
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009994 // The conversion that can be fixed with a smaller number of changes,
9995 // comes first.
9996 unsigned numLFixes = L->Fix.NumConversionsFixed;
9997 unsigned numRFixes = R->Fix.NumConversionsFixed;
9998 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9999 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010000 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010001 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010002 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010003
John McCallfe796dd2010-01-23 05:17:32 +000010004 // If there's any ordering between the defined conversions...
10005 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +000010006 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +000010007
10008 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010009 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010010 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010011 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010012 L->Conversions[I],
10013 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010014 case ImplicitConversionSequence::Better:
10015 leftBetter++;
10016 break;
10017
10018 case ImplicitConversionSequence::Worse:
10019 leftBetter--;
10020 break;
10021
10022 case ImplicitConversionSequence::Indistinguishable:
10023 break;
10024 }
10025 }
10026 if (leftBetter > 0) return true;
10027 if (leftBetter < 0) return false;
10028
10029 } else if (R->FailureKind == ovl_fail_bad_conversion)
10030 return false;
10031
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010032 if (L->FailureKind == ovl_fail_bad_deduction) {
10033 if (R->FailureKind != ovl_fail_bad_deduction)
10034 return true;
10035
10036 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10037 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010038 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010039 } else if (R->FailureKind == ovl_fail_bad_deduction)
10040 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010041
John McCall3712d9e2010-01-15 23:32:50 +000010042 // TODO: others?
10043 }
10044
10045 // Sort everything else by location.
10046 SourceLocation LLoc = GetLocationForCandidate(L);
10047 SourceLocation RLoc = GetLocationForCandidate(R);
10048
10049 // Put candidates without locations (e.g. builtins) at the end.
10050 if (LLoc.isInvalid()) return false;
10051 if (RLoc.isInvalid()) return true;
10052
10053 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010054 }
10055};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010056}
John McCall12f97bc2010-01-08 04:41:39 +000010057
John McCallfe796dd2010-01-23 05:17:32 +000010058/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010059/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010060static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10061 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010062 assert(!Cand->Viable);
10063
10064 // Don't do anything on failures other than bad conversion.
10065 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10066
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010067 // We only want the FixIts if all the arguments can be corrected.
10068 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010069 // Use a implicit copy initialization to check conversion fixes.
10070 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010071
John McCallfe796dd2010-01-23 05:17:32 +000010072 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +000010073 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010074 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +000010075 while (true) {
10076 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10077 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010078 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +000010079 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +000010080 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010081 }
John McCallfe796dd2010-01-23 05:17:32 +000010082 }
10083
10084 if (ConvIdx == ConvCount)
10085 return;
10086
John McCall65eb8792010-02-25 01:37:24 +000010087 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10088 "remaining conversion is initialized?");
10089
Douglas Gregoradc7a702010-04-16 17:45:54 +000010090 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010091 // operation somehow.
10092 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010093
10094 const FunctionProtoType* Proto;
10095 unsigned ArgIdx = ConvIdx;
10096
10097 if (Cand->IsSurrogate) {
10098 QualType ConvType
10099 = Cand->Surrogate->getConversionType().getNonReferenceType();
10100 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10101 ConvType = ConvPtrType->getPointeeType();
10102 Proto = ConvType->getAs<FunctionProtoType>();
10103 ArgIdx--;
10104 } else if (Cand->Function) {
10105 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10106 if (isa<CXXMethodDecl>(Cand->Function) &&
10107 !isa<CXXConstructorDecl>(Cand->Function))
10108 ArgIdx--;
10109 } else {
10110 // Builtin binary operator with a bad first conversion.
10111 assert(ConvCount <= 3);
10112 for (; ConvIdx != ConvCount; ++ConvIdx)
10113 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +000010114 = TryCopyInitialization(S, Args[ConvIdx],
10115 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010116 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +000010117 /*InOverloadResolution*/ true,
10118 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +000010119 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010120 return;
10121 }
10122
10123 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010124 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +000010125 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010126 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +000010127 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10128 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10129 /*InOverloadResolution=*/true,
10130 /*AllowObjCWritebackConversion=*/
10131 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010132 // Store the FixIt in the candidate if it exists.
10133 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010134 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010135 }
John McCallfe796dd2010-01-23 05:17:32 +000010136 else
10137 Cand->Conversions[ConvIdx].setEllipsis();
10138 }
10139}
10140
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010141/// PrintOverloadCandidates - When overload resolution fails, prints
10142/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010143/// set.
John McCall5c32be02010-08-24 20:38:10 +000010144void OverloadCandidateSet::NoteCandidates(Sema &S,
10145 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010146 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +000010147 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +000010148 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +000010149 // Sort the candidates by viability and position. Sorting directly would
10150 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010151 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010152 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10153 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +000010154 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010155 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010156 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010157 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010158 if (Cand->Function || Cand->IsSurrogate)
10159 Cands.push_back(Cand);
10160 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10161 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010162 }
10163 }
10164
John McCallad2587a2010-01-12 00:48:53 +000010165 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010166 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010167
John McCall0d1da222010-01-12 00:44:57 +000010168 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010169
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010170 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010171 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010172 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010173 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10174 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010175
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010176 // Set an arbitrary limit on the number of candidate functions we'll spam
10177 // the user with. FIXME: This limit should depend on details of the
10178 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010179 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010180 break;
10181 }
10182 ++CandsShown;
10183
John McCalld3224162010-01-08 00:58:21 +000010184 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010185 NoteFunctionCandidate(S, Cand, Args.size(),
10186 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010187 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010188 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010189 else {
10190 assert(Cand->Viable &&
10191 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010192 // Generally we only see ambiguities including viable builtin
10193 // operators if overload resolution got screwed up by an
10194 // ambiguous user-defined conversion.
10195 //
10196 // FIXME: It's quite possible for different conversions to see
10197 // different ambiguities, though.
10198 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010199 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010200 ReportedAmbiguousConversions = true;
10201 }
John McCalld3224162010-01-08 00:58:21 +000010202
John McCall0d1da222010-01-12 00:44:57 +000010203 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010204 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010205 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010206 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010207
10208 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010209 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010210}
10211
Larisse Voufo98b20f12013-07-19 23:00:19 +000010212static SourceLocation
10213GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10214 return Cand->Specialization ? Cand->Specialization->getLocation()
10215 : SourceLocation();
10216}
10217
Richard Smith17c00b42014-11-12 01:24:00 +000010218namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010219struct CompareTemplateSpecCandidatesForDisplay {
10220 Sema &S;
10221 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10222
10223 bool operator()(const TemplateSpecCandidate *L,
10224 const TemplateSpecCandidate *R) {
10225 // Fast-path this check.
10226 if (L == R)
10227 return false;
10228
10229 // Assuming that both candidates are not matches...
10230
10231 // Sort by the ranking of deduction failures.
10232 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10233 return RankDeductionFailure(L->DeductionFailure) <
10234 RankDeductionFailure(R->DeductionFailure);
10235
10236 // Sort everything else by location.
10237 SourceLocation LLoc = GetLocationForCandidate(L);
10238 SourceLocation RLoc = GetLocationForCandidate(R);
10239
10240 // Put candidates without locations (e.g. builtins) at the end.
10241 if (LLoc.isInvalid())
10242 return false;
10243 if (RLoc.isInvalid())
10244 return true;
10245
10246 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10247 }
10248};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010249}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010250
10251/// Diagnose a template argument deduction failure.
10252/// We are treating these failures as overload failures due to bad
10253/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010254void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10255 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010256 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010257 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010258}
10259
10260void TemplateSpecCandidateSet::destroyCandidates() {
10261 for (iterator i = begin(), e = end(); i != e; ++i) {
10262 i->DeductionFailure.Destroy();
10263 }
10264}
10265
10266void TemplateSpecCandidateSet::clear() {
10267 destroyCandidates();
10268 Candidates.clear();
10269}
10270
10271/// NoteCandidates - When no template specialization match is found, prints
10272/// diagnostic messages containing the non-matching specializations that form
10273/// the candidate set.
10274/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10275/// OCD == OCD_AllCandidates and Cand->Viable == false.
10276void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10277 // Sort the candidates by position (assuming no candidate is a match).
10278 // Sorting directly would be prohibitive, so we make a set of pointers
10279 // and sort those.
10280 SmallVector<TemplateSpecCandidate *, 32> Cands;
10281 Cands.reserve(size());
10282 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10283 if (Cand->Specialization)
10284 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010285 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010286 // in general, want to list every possible builtin candidate.
10287 }
10288
10289 std::sort(Cands.begin(), Cands.end(),
10290 CompareTemplateSpecCandidatesForDisplay(S));
10291
10292 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10293 // for generalization purposes (?).
10294 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10295
10296 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10297 unsigned CandsShown = 0;
10298 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10299 TemplateSpecCandidate *Cand = *I;
10300
10301 // Set an arbitrary limit on the number of candidates we'll spam
10302 // the user with. FIXME: This limit should depend on details of the
10303 // candidate list.
10304 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10305 break;
10306 ++CandsShown;
10307
10308 assert(Cand->Specialization &&
10309 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010310 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010311 }
10312
10313 if (I != E)
10314 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10315}
10316
Douglas Gregorb491ed32011-02-19 21:32:49 +000010317// [PossiblyAFunctionType] --> [Return]
10318// NonFunctionType --> NonFunctionType
10319// R (A) --> R(A)
10320// R (*)(A) --> R (A)
10321// R (&)(A) --> R (A)
10322// R (S::*)(A) --> R (A)
10323QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10324 QualType Ret = PossiblyAFunctionType;
10325 if (const PointerType *ToTypePtr =
10326 PossiblyAFunctionType->getAs<PointerType>())
10327 Ret = ToTypePtr->getPointeeType();
10328 else if (const ReferenceType *ToTypeRef =
10329 PossiblyAFunctionType->getAs<ReferenceType>())
10330 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010331 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010332 PossiblyAFunctionType->getAs<MemberPointerType>())
10333 Ret = MemTypePtr->getPointeeType();
10334 Ret =
10335 Context.getCanonicalType(Ret).getUnqualifiedType();
10336 return Ret;
10337}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010338
Richard Smith17c00b42014-11-12 01:24:00 +000010339namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010340// A helper class to help with address of function resolution
10341// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010342class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010343 Sema& S;
10344 Expr* SourceExpr;
10345 const QualType& TargetType;
10346 QualType TargetFunctionType; // Extracted function type from target type
10347
10348 bool Complain;
10349 //DeclAccessPair& ResultFunctionAccessPair;
10350 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010351
Douglas Gregorb491ed32011-02-19 21:32:49 +000010352 bool TargetTypeIsNonStaticMemberFunction;
10353 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010354 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010355 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010356
Douglas Gregorb491ed32011-02-19 21:32:49 +000010357 OverloadExpr::FindResult OvlExprInfo;
10358 OverloadExpr *OvlExpr;
10359 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010360 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010361 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010362
Douglas Gregorb491ed32011-02-19 21:32:49 +000010363public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010364 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10365 const QualType &TargetType, bool Complain)
10366 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10367 Complain(Complain), Context(S.getASTContext()),
10368 TargetTypeIsNonStaticMemberFunction(
10369 !!TargetType->getAs<MemberPointerType>()),
10370 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010371 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010372 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010373 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10374 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010375 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010376 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010377
David Majnemera4f7c7a2013-08-01 06:13:59 +000010378 if (TargetFunctionType->isFunctionType()) {
10379 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10380 if (!UME->isImplicitAccess() &&
10381 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10382 StaticMemberFunctionFromBoundPointer = true;
10383 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10384 DeclAccessPair dap;
10385 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10386 OvlExpr, false, &dap)) {
10387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10388 if (!Method->isStatic()) {
10389 // If the target type is a non-function type and the function found
10390 // is a non-static member function, pretend as if that was the
10391 // target, it's the only possible type to end up with.
10392 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010393
David Majnemera4f7c7a2013-08-01 06:13:59 +000010394 // And skip adding the function if its not in the proper form.
10395 // We'll diagnose this due to an empty set of functions.
10396 if (!OvlExprInfo.HasFormOfMemberPointer)
10397 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010398 }
10399
David Majnemera4f7c7a2013-08-01 06:13:59 +000010400 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010401 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010402 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010403 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010404
10405 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010406 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010407
Douglas Gregorb491ed32011-02-19 21:32:49 +000010408 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10409 // C++ [over.over]p4:
10410 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010411 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010412 if (FoundNonTemplateFunction)
10413 EliminateAllTemplateMatches();
10414 else
10415 EliminateAllExceptMostSpecializedTemplate();
10416 }
10417 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010418
Justin Lebar25c4a812016-03-29 16:24:16 +000010419 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010420 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010421 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010422
10423 bool hasComplained() const { return HasComplained; }
10424
Douglas Gregorb491ed32011-02-19 21:32:49 +000010425private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010426 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10427 QualType Discard;
10428 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10429 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010430 }
10431
George Burgess IV6da4c202016-03-23 02:33:58 +000010432 /// \return true if A is considered a better overload candidate for the
10433 /// desired type than B.
10434 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10435 // If A doesn't have exactly the correct type, we don't want to classify it
10436 // as "better" than anything else. This way, the user is required to
10437 // disambiguate for us if there are multiple candidates and no exact match.
10438 return candidateHasExactlyCorrectType(A) &&
10439 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010440 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010441 }
10442
10443 /// \return true if we were able to eliminate all but one overload candidate,
10444 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010445 bool eliminiateSuboptimalOverloadCandidates() {
10446 // Same algorithm as overload resolution -- one pass to pick the "best",
10447 // another pass to be sure that nothing is better than the best.
10448 auto Best = Matches.begin();
10449 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10450 if (isBetterCandidate(I->second, Best->second))
10451 Best = I;
10452
10453 const FunctionDecl *BestFn = Best->second;
10454 auto IsBestOrInferiorToBest = [this, BestFn](
10455 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10456 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10457 };
10458
10459 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10460 // option, so we can potentially give the user a better error
10461 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10462 return false;
10463 Matches[0] = *Best;
10464 Matches.resize(1);
10465 return true;
10466 }
10467
Douglas Gregorb491ed32011-02-19 21:32:49 +000010468 bool isTargetTypeAFunction() const {
10469 return TargetFunctionType->isFunctionType();
10470 }
10471
10472 // [ToType] [Return]
10473
10474 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10475 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10476 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10477 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10478 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10479 }
10480
10481 // return true if any matching specializations were found
10482 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10483 const DeclAccessPair& CurAccessFunPair) {
10484 if (CXXMethodDecl *Method
10485 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10486 // Skip non-static function templates when converting to pointer, and
10487 // static when converting to member pointer.
10488 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10489 return false;
10490 }
10491 else if (TargetTypeIsNonStaticMemberFunction)
10492 return false;
10493
10494 // C++ [over.over]p2:
10495 // If the name is a function template, template argument deduction is
10496 // done (14.8.2.2), and if the argument deduction succeeds, the
10497 // resulting template argument list is used to generate a single
10498 // function template specialization, which is added to the set of
10499 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010500 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010501 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010502 if (Sema::TemplateDeductionResult Result
10503 = S.DeduceTemplateArguments(FunctionTemplate,
10504 &OvlExplicitTemplateArgs,
10505 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010506 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010507 // Make a note of the failed deduction for diagnostics.
10508 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010509 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010510 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010511 return false;
10512 }
10513
Douglas Gregor19a41f12013-04-17 08:45:07 +000010514 // Template argument deduction ensures that we have an exact match or
10515 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010516 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010517 assert(S.isSameOrCompatibleFunctionType(
10518 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010519 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010520
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010521 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010522 return false;
10523
Douglas Gregorb491ed32011-02-19 21:32:49 +000010524 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10525 return true;
10526 }
10527
10528 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10529 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010530 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010531 // Skip non-static functions when converting to pointer, and static
10532 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010533 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10534 return false;
10535 }
10536 else if (TargetTypeIsNonStaticMemberFunction)
10537 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010538
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010539 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010540 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010541 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010542 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010543 return false;
10544
Richard Smith2a7d4812013-05-04 07:00:32 +000010545 // If any candidate has a placeholder return type, trigger its deduction
10546 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010547 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010548 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010549 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10550 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010551 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010552 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010553
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010554 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010555 return false;
10556
George Burgess IV6da4c202016-03-23 02:33:58 +000010557 // If we're in C, we need to support types that aren't exactly identical.
10558 if (!S.getLangOpts().CPlusPlus ||
10559 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010560 Matches.push_back(std::make_pair(
10561 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010562 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010563 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010564 }
Mike Stump11289f42009-09-09 15:08:12 +000010565 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010566
10567 return false;
10568 }
10569
10570 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10571 bool Ret = false;
10572
10573 // If the overload expression doesn't have the form of a pointer to
10574 // member, don't try to convert it to a pointer-to-member type.
10575 if (IsInvalidFormOfPointerToMemberFunction())
10576 return false;
10577
10578 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10579 E = OvlExpr->decls_end();
10580 I != E; ++I) {
10581 // Look through any using declarations to find the underlying function.
10582 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10583
10584 // C++ [over.over]p3:
10585 // Non-member functions and static member functions match
10586 // targets of type "pointer-to-function" or "reference-to-function."
10587 // Nonstatic member functions match targets of
10588 // type "pointer-to-member-function."
10589 // Note that according to DR 247, the containing class does not matter.
10590 if (FunctionTemplateDecl *FunctionTemplate
10591 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10592 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10593 Ret = true;
10594 }
10595 // If we have explicit template arguments supplied, skip non-templates.
10596 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10597 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10598 Ret = true;
10599 }
10600 assert(Ret || Matches.empty());
10601 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010602 }
10603
Douglas Gregorb491ed32011-02-19 21:32:49 +000010604 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010605 // [...] and any given function template specialization F1 is
10606 // eliminated if the set contains a second function template
10607 // specialization whose function template is more specialized
10608 // than the function template of F1 according to the partial
10609 // ordering rules of 14.5.5.2.
10610
10611 // The algorithm specified above is quadratic. We instead use a
10612 // two-pass algorithm (similar to the one used to identify the
10613 // best viable function in an overload set) that identifies the
10614 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010615
10616 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10617 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10618 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010619
Larisse Voufo98b20f12013-07-19 23:00:19 +000010620 // TODO: It looks like FailedCandidates does not serve much purpose
10621 // here, since the no_viable diagnostic has index 0.
10622 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010623 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010624 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010625 S.PDiag(diag::err_addr_ovl_ambiguous)
10626 << Matches[0].second->getDeclName(),
10627 S.PDiag(diag::note_ovl_candidate)
10628 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010629 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010630
Douglas Gregorb491ed32011-02-19 21:32:49 +000010631 if (Result != MatchesCopy.end()) {
10632 // Make it the first and only element
10633 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10634 Matches[0].second = cast<FunctionDecl>(*Result);
10635 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010636 } else
10637 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010639
Douglas Gregorb491ed32011-02-19 21:32:49 +000010640 void EliminateAllTemplateMatches() {
10641 // [...] any function template specializations in the set are
10642 // eliminated if the set also contains a non-template function, [...]
10643 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010644 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010645 ++I;
10646 else {
10647 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010648 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010649 }
10650 }
10651 }
10652
Artem Belevich94a55e82015-09-22 17:22:59 +000010653 void EliminateSuboptimalCudaMatches() {
10654 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10655 }
10656
Douglas Gregorb491ed32011-02-19 21:32:49 +000010657public:
10658 void ComplainNoMatchesFound() const {
10659 assert(Matches.empty());
10660 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10661 << OvlExpr->getName() << TargetFunctionType
10662 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010663 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010664 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10665 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010666 else {
10667 // We have some deduction failure messages. Use them to diagnose
10668 // the function templates, and diagnose the non-template candidates
10669 // normally.
10670 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10671 IEnd = OvlExpr->decls_end();
10672 I != IEnd; ++I)
10673 if (FunctionDecl *Fun =
10674 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010675 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010676 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010677 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010678 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10679 }
10680 }
10681
Douglas Gregorb491ed32011-02-19 21:32:49 +000010682 bool IsInvalidFormOfPointerToMemberFunction() const {
10683 return TargetTypeIsNonStaticMemberFunction &&
10684 !OvlExprInfo.HasFormOfMemberPointer;
10685 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010686
Douglas Gregorb491ed32011-02-19 21:32:49 +000010687 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10688 // TODO: Should we condition this on whether any functions might
10689 // have matched, or is it more appropriate to do that in callers?
10690 // TODO: a fixit wouldn't hurt.
10691 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10692 << TargetType << OvlExpr->getSourceRange();
10693 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010694
10695 bool IsStaticMemberFunctionFromBoundPointer() const {
10696 return StaticMemberFunctionFromBoundPointer;
10697 }
10698
10699 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10700 S.Diag(OvlExpr->getLocStart(),
10701 diag::err_invalid_form_pointer_member_function)
10702 << OvlExpr->getSourceRange();
10703 }
10704
Douglas Gregorb491ed32011-02-19 21:32:49 +000010705 void ComplainOfInvalidConversion() const {
10706 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10707 << OvlExpr->getName() << TargetType;
10708 }
10709
10710 void ComplainMultipleMatchesFound() const {
10711 assert(Matches.size() > 1);
10712 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10713 << OvlExpr->getName()
10714 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010715 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10716 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010717 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010718
10719 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10720
Douglas Gregorb491ed32011-02-19 21:32:49 +000010721 int getNumMatches() const { return Matches.size(); }
10722
10723 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010724 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010725 return Matches[0].second;
10726 }
10727
10728 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010729 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010730 return &Matches[0].first;
10731 }
10732};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010733}
Richard Smith17c00b42014-11-12 01:24:00 +000010734
Douglas Gregorb491ed32011-02-19 21:32:49 +000010735/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10736/// an overloaded function (C++ [over.over]), where @p From is an
10737/// expression with overloaded function type and @p ToType is the type
10738/// we're trying to resolve to. For example:
10739///
10740/// @code
10741/// int f(double);
10742/// int f(int);
10743///
10744/// int (*pfd)(double) = f; // selects f(double)
10745/// @endcode
10746///
10747/// This routine returns the resulting FunctionDecl if it could be
10748/// resolved, and NULL otherwise. When @p Complain is true, this
10749/// routine will emit diagnostics if there is an error.
10750FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010751Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10752 QualType TargetType,
10753 bool Complain,
10754 DeclAccessPair &FoundResult,
10755 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010756 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010757
10758 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10759 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010760 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010761 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010762 bool ShouldComplain = Complain && !Resolver.hasComplained();
10763 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010764 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10765 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10766 else
10767 Resolver.ComplainNoMatchesFound();
10768 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010769 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010770 Resolver.ComplainMultipleMatchesFound();
10771 else if (NumMatches == 1) {
10772 Fn = Resolver.getMatchingFunctionDecl();
10773 assert(Fn);
10774 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010775 if (Complain) {
10776 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10777 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10778 else
10779 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10780 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010781 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010782
10783 if (pHadMultipleCandidates)
10784 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010785 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010786}
10787
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010788/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010789/// resolve that function to a single function that can have its address taken.
10790/// This will modify `Pair` iff it returns non-null.
10791///
10792/// This routine can only realistically succeed if all but one candidates in the
10793/// overload set for SrcExpr cannot have their addresses taken.
10794FunctionDecl *
10795Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10796 DeclAccessPair &Pair) {
10797 OverloadExpr::FindResult R = OverloadExpr::find(E);
10798 OverloadExpr *Ovl = R.Expression;
10799 FunctionDecl *Result = nullptr;
10800 DeclAccessPair DAP;
10801 // Don't use the AddressOfResolver because we're specifically looking for
10802 // cases where we have one overload candidate that lacks
10803 // enable_if/pass_object_size/...
10804 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10805 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10806 if (!FD)
10807 return nullptr;
10808
10809 if (!checkAddressOfFunctionIsAvailable(FD))
10810 continue;
10811
10812 // We have more than one result; quit.
10813 if (Result)
10814 return nullptr;
10815 DAP = I.getPair();
10816 Result = FD;
10817 }
10818
10819 if (Result)
10820 Pair = DAP;
10821 return Result;
10822}
10823
George Burgess IVbeca4a32016-06-08 00:34:22 +000010824/// \brief Given an overloaded function, tries to turn it into a non-overloaded
10825/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10826/// will perform access checks, diagnose the use of the resultant decl, and, if
10827/// necessary, perform a function-to-pointer decay.
10828///
10829/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10830/// Otherwise, returns true. This may emit diagnostics and return true.
10831bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10832 ExprResult &SrcExpr) {
10833 Expr *E = SrcExpr.get();
10834 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10835
10836 DeclAccessPair DAP;
10837 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10838 if (!Found)
10839 return false;
10840
10841 // Emitting multiple diagnostics for a function that is both inaccessible and
10842 // unavailable is consistent with our behavior elsewhere. So, always check
10843 // for both.
10844 DiagnoseUseOfDecl(Found, E->getExprLoc());
10845 CheckAddressOfMemberAccess(E, DAP);
10846 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10847 if (Fixed->getType()->isFunctionType())
10848 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10849 else
10850 SrcExpr = Fixed;
10851 return true;
10852}
10853
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010854/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010855/// resolve that overloaded function expression down to a single function.
10856///
10857/// This routine can only resolve template-ids that refer to a single function
10858/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010859/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010860/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010861///
10862/// If no template-ids are found, no diagnostics are emitted and NULL is
10863/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010864FunctionDecl *
10865Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10866 bool Complain,
10867 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010868 // C++ [over.over]p1:
10869 // [...] [Note: any redundant set of parentheses surrounding the
10870 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010871 // C++ [over.over]p1:
10872 // [...] The overloaded function name can be preceded by the &
10873 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010874
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010875 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010876 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010877 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010878
10879 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010880 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010881 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010882
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010883 // Look through all of the overloaded functions, searching for one
10884 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010885 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010886 for (UnresolvedSetIterator I = ovl->decls_begin(),
10887 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010888 // C++0x [temp.arg.explicit]p3:
10889 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010890 // where deduction is not done, if a template argument list is
10891 // specified and it, along with any default template arguments,
10892 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010893 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010894 FunctionTemplateDecl *FunctionTemplate
10895 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010896
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010897 // C++ [over.over]p2:
10898 // If the name is a function template, template argument deduction is
10899 // done (14.8.2.2), and if the argument deduction succeeds, the
10900 // resulting template argument list is used to generate a single
10901 // function template specialization, which is added to the set of
10902 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010903 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010904 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010905 if (TemplateDeductionResult Result
10906 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010907 Specialization, Info,
10908 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010909 // Make a note of the failed deduction for diagnostics.
10910 // TODO: Actually use the failed-deduction info?
10911 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010912 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010913 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010914 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010915 }
10916
John McCall0009fcc2011-04-26 20:42:42 +000010917 assert(Specialization && "no specialization and no error?");
10918
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010919 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010920 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010921 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010922 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10923 << ovl->getName();
10924 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010925 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010926 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010927 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010928
John McCall0009fcc2011-04-26 20:42:42 +000010929 Matched = Specialization;
10930 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010932
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010933 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010934 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010935 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010936 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010937
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010938 return Matched;
10939}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010940
Douglas Gregor1beec452011-03-12 01:48:56 +000010941
10942
10943
John McCall50a2c2c2011-10-11 23:14:30 +000010944// Resolve and fix an overloaded expression that can be resolved
10945// because it identifies a single function template specialization.
10946//
Douglas Gregor1beec452011-03-12 01:48:56 +000010947// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010948//
10949// Return true if it was logically possible to so resolve the
10950// expression, regardless of whether or not it succeeded. Always
10951// returns true if 'complain' is set.
10952bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10953 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010954 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010955 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010956 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010957 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010958
John McCall50a2c2c2011-10-11 23:14:30 +000010959 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010960
John McCall0009fcc2011-04-26 20:42:42 +000010961 DeclAccessPair found;
10962 ExprResult SingleFunctionExpression;
10963 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10964 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010965 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010966 SrcExpr = ExprError();
10967 return true;
10968 }
John McCall0009fcc2011-04-26 20:42:42 +000010969
10970 // It is only correct to resolve to an instance method if we're
10971 // resolving a form that's permitted to be a pointer to member.
10972 // Otherwise we'll end up making a bound member expression, which
10973 // is illegal in all the contexts we resolve like this.
10974 if (!ovl.HasFormOfMemberPointer &&
10975 isa<CXXMethodDecl>(fn) &&
10976 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010977 if (!complain) return false;
10978
10979 Diag(ovl.Expression->getExprLoc(),
10980 diag::err_bound_member_function)
10981 << 0 << ovl.Expression->getSourceRange();
10982
10983 // TODO: I believe we only end up here if there's a mix of
10984 // static and non-static candidates (otherwise the expression
10985 // would have 'bound member' type, not 'overload' type).
10986 // Ideally we would note which candidate was chosen and why
10987 // the static candidates were rejected.
10988 SrcExpr = ExprError();
10989 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010990 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010991
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010992 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010993 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010994 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010995
10996 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010997 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010998 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010999 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011000 if (SingleFunctionExpression.isInvalid()) {
11001 SrcExpr = ExprError();
11002 return true;
11003 }
11004 }
John McCall0009fcc2011-04-26 20:42:42 +000011005 }
11006
11007 if (!SingleFunctionExpression.isUsable()) {
11008 if (complain) {
11009 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11010 << ovl.Expression->getName()
11011 << DestTypeForComplaining
11012 << OpRangeForComplaining
11013 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011014 NoteAllOverloadCandidates(SrcExpr.get());
11015
11016 SrcExpr = ExprError();
11017 return true;
11018 }
11019
11020 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011021 }
11022
John McCall50a2c2c2011-10-11 23:14:30 +000011023 SrcExpr = SingleFunctionExpression;
11024 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011025}
11026
Douglas Gregorcabea402009-09-22 15:41:20 +000011027/// \brief Add a single candidate to the overload set.
11028static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011029 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011030 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011031 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011032 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011033 bool PartialOverloading,
11034 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011035 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011036 if (isa<UsingShadowDecl>(Callee))
11037 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11038
Douglas Gregorcabea402009-09-22 15:41:20 +000011039 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011040 if (ExplicitTemplateArgs) {
11041 assert(!KnownValid && "Explicit template arguments?");
11042 return;
11043 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011044 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11045 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011046 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011047 return;
John McCalld14a8642009-11-21 08:51:07 +000011048 }
11049
11050 if (FunctionTemplateDecl *FuncTemplate
11051 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011052 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011053 ExplicitTemplateArgs, Args, CandidateSet,
11054 /*SuppressUsedConversions=*/false,
11055 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011056 return;
11057 }
11058
Richard Smith95ce4f62011-06-26 22:19:54 +000011059 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011060}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011061
Douglas Gregorcabea402009-09-22 15:41:20 +000011062/// \brief Add the overload candidates named by callee and/or found by argument
11063/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011064void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011065 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011066 OverloadCandidateSet &CandidateSet,
11067 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011068
11069#ifndef NDEBUG
11070 // Verify that ArgumentDependentLookup is consistent with the rules
11071 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011072 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011073 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11074 // and let Y be the lookup set produced by argument dependent
11075 // lookup (defined as follows). If X contains
11076 //
11077 // -- a declaration of a class member, or
11078 //
11079 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011080 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011081 //
11082 // -- a declaration that is neither a function or a function
11083 // template
11084 //
11085 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011086
John McCall57500772009-12-16 12:17:52 +000011087 if (ULE->requiresADL()) {
11088 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11089 E = ULE->decls_end(); I != E; ++I) {
11090 assert(!(*I)->getDeclContext()->isRecord());
11091 assert(isa<UsingShadowDecl>(*I) ||
11092 !(*I)->getDeclContext()->isFunctionOrMethod());
11093 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011094 }
11095 }
11096#endif
11097
John McCall57500772009-12-16 12:17:52 +000011098 // It would be nice to avoid this copy.
11099 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011100 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011101 if (ULE->hasExplicitTemplateArgs()) {
11102 ULE->copyTemplateArgumentsInto(TABuffer);
11103 ExplicitTemplateArgs = &TABuffer;
11104 }
11105
11106 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11107 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011108 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11109 CandidateSet, PartialOverloading,
11110 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011111
John McCall57500772009-12-16 12:17:52 +000011112 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011113 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011114 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011115 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011116}
John McCalld681c392009-12-16 08:11:27 +000011117
Richard Smith0603bbb2013-06-12 22:56:54 +000011118/// Determine whether a declaration with the specified name could be moved into
11119/// a different namespace.
11120static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11121 switch (Name.getCXXOverloadedOperator()) {
11122 case OO_New: case OO_Array_New:
11123 case OO_Delete: case OO_Array_Delete:
11124 return false;
11125
11126 default:
11127 return true;
11128 }
11129}
11130
Richard Smith998a5912011-06-05 22:42:48 +000011131/// Attempt to recover from an ill-formed use of a non-dependent name in a
11132/// template, where the non-dependent name was declared after the template
11133/// was defined. This is common in code written for a compilers which do not
11134/// correctly implement two-stage name lookup.
11135///
11136/// Returns true if a viable candidate was found and a diagnostic was issued.
11137static bool
11138DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11139 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011140 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011141 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011142 ArrayRef<Expr *> Args,
11143 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011144 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11145 return false;
11146
11147 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011148 if (DC->isTransparentContext())
11149 continue;
11150
Richard Smith998a5912011-06-05 22:42:48 +000011151 SemaRef.LookupQualifiedName(R, DC);
11152
11153 if (!R.empty()) {
11154 R.suppressDiagnostics();
11155
11156 if (isa<CXXRecordDecl>(DC)) {
11157 // Don't diagnose names we find in classes; we get much better
11158 // diagnostics for these from DiagnoseEmptyLookup.
11159 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011160 if (DoDiagnoseEmptyLookup)
11161 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011162 return false;
11163 }
11164
Richard Smith100b24a2014-04-17 01:52:14 +000011165 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011166 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11167 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011168 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011169 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011170
11171 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011172 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011173 // No viable functions. Don't bother the user with notes for functions
11174 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011175 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011176 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011177 }
Richard Smith998a5912011-06-05 22:42:48 +000011178
11179 // Find the namespaces where ADL would have looked, and suggest
11180 // declaring the function there instead.
11181 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11182 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011183 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011184 AssociatedNamespaces,
11185 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011186 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011187 if (canBeDeclaredInNamespace(R.getLookupName())) {
11188 DeclContext *Std = SemaRef.getStdNamespace();
11189 for (Sema::AssociatedNamespaceSet::iterator
11190 it = AssociatedNamespaces.begin(),
11191 end = AssociatedNamespaces.end(); it != end; ++it) {
11192 // Never suggest declaring a function within namespace 'std'.
11193 if (Std && Std->Encloses(*it))
11194 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011195
Richard Smith0603bbb2013-06-12 22:56:54 +000011196 // Never suggest declaring a function within a namespace with a
11197 // reserved name, like __gnu_cxx.
11198 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11199 if (NS &&
11200 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11201 continue;
11202
11203 SuggestedNamespaces.insert(*it);
11204 }
Richard Smith998a5912011-06-05 22:42:48 +000011205 }
11206
11207 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11208 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011209 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011210 SemaRef.Diag(Best->Function->getLocation(),
11211 diag::note_not_found_by_two_phase_lookup)
11212 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011213 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011214 SemaRef.Diag(Best->Function->getLocation(),
11215 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011216 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011217 } else {
11218 // FIXME: It would be useful to list the associated namespaces here,
11219 // but the diagnostics infrastructure doesn't provide a way to produce
11220 // a localized representation of a list of items.
11221 SemaRef.Diag(Best->Function->getLocation(),
11222 diag::note_not_found_by_two_phase_lookup)
11223 << R.getLookupName() << 2;
11224 }
11225
11226 // Try to recover by calling this function.
11227 return true;
11228 }
11229
11230 R.clear();
11231 }
11232
11233 return false;
11234}
11235
11236/// Attempt to recover from ill-formed use of a non-dependent operator in a
11237/// template, where the non-dependent operator was declared after the template
11238/// was defined.
11239///
11240/// Returns true if a viable candidate was found and a diagnostic was issued.
11241static bool
11242DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11243 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011244 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011245 DeclarationName OpName =
11246 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11247 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11248 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011249 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011250 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011251}
11252
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011253namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011254class BuildRecoveryCallExprRAII {
11255 Sema &SemaRef;
11256public:
11257 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11258 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11259 SemaRef.IsBuildingRecoveryCallExpr = true;
11260 }
11261
11262 ~BuildRecoveryCallExprRAII() {
11263 SemaRef.IsBuildingRecoveryCallExpr = false;
11264 }
11265};
11266
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011267}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011268
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011269static std::unique_ptr<CorrectionCandidateCallback>
11270MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11271 bool HasTemplateArgs, bool AllowTypoCorrection) {
11272 if (!AllowTypoCorrection)
11273 return llvm::make_unique<NoTypoCorrectionCCC>();
11274 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11275 HasTemplateArgs, ME);
11276}
11277
John McCalld681c392009-12-16 08:11:27 +000011278/// Attempts to recover from a call where no functions were found.
11279///
11280/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011281static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011282BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011283 UnresolvedLookupExpr *ULE,
11284 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011285 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011286 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011287 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011288 // Do not try to recover if it is already building a recovery call.
11289 // This stops infinite loops for template instantiations like
11290 //
11291 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11292 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11293 //
11294 if (SemaRef.IsBuildingRecoveryCallExpr)
11295 return ExprError();
11296 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011297
11298 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011299 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011300 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011301
John McCall57500772009-12-16 12:17:52 +000011302 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011303 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011304 if (ULE->hasExplicitTemplateArgs()) {
11305 ULE->copyTemplateArgumentsInto(TABuffer);
11306 ExplicitTemplateArgs = &TABuffer;
11307 }
11308
John McCalld681c392009-12-16 08:11:27 +000011309 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11310 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011311 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011312 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011313 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011314 ExplicitTemplateArgs, Args,
11315 &DoDiagnoseEmptyLookup) &&
11316 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11317 S, SS, R,
11318 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11319 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11320 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011321 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011322
John McCall57500772009-12-16 12:17:52 +000011323 assert(!R.empty() && "lookup results empty despite recovery");
11324
11325 // Build an implicit member call if appropriate. Just drop the
11326 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011327 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011328 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011329 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11330 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011331 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011332 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011333 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011334 else
11335 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11336
11337 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011338 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011339
11340 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011341 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011342 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011343 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011344 MultiExprArg(Args.data(), Args.size()),
11345 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011346}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011347
Sam Panzer0f384432012-08-21 00:52:01 +000011348/// \brief Constructs and populates an OverloadedCandidateSet from
11349/// the given function.
11350/// \returns true when an the ExprResult output parameter has been set.
11351bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11352 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011353 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011354 SourceLocation RParenLoc,
11355 OverloadCandidateSet *CandidateSet,
11356 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011357#ifndef NDEBUG
11358 if (ULE->requiresADL()) {
11359 // To do ADL, we must have found an unqualified name.
11360 assert(!ULE->getQualifier() && "qualified name with ADL");
11361
11362 // We don't perform ADL for implicit declarations of builtins.
11363 // Verify that this was correctly set up.
11364 FunctionDecl *F;
11365 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11366 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11367 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011368 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011369
John McCall57500772009-12-16 12:17:52 +000011370 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011371 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011372 }
John McCall57500772009-12-16 12:17:52 +000011373#endif
11374
John McCall4124c492011-10-17 18:40:02 +000011375 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011376 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011377 *Result = ExprError();
11378 return true;
11379 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011380
John McCall57500772009-12-16 12:17:52 +000011381 // Add the functions denoted by the callee to the set of candidate
11382 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011383 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011384
Hans Wennborgb2747382015-06-12 21:23:23 +000011385 if (getLangOpts().MSVCCompat &&
11386 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011387 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11388
11389 OverloadCandidateSet::iterator Best;
11390 if (CandidateSet->empty() ||
11391 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11392 OR_No_Viable_Function) {
11393 // In Microsoft mode, if we are inside a template class member function then
11394 // create a type dependent CallExpr. The goal is to postpone name lookup
11395 // to instantiation time to be able to search into type dependent base
11396 // classes.
11397 CallExpr *CE = new (Context) CallExpr(
11398 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011399 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011400 CE->setValueDependent(true);
11401 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011402 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011403 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011404 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011405 }
John McCalld681c392009-12-16 08:11:27 +000011406
Hans Wennborg64937c62015-06-11 21:21:57 +000011407 if (CandidateSet->empty())
11408 return false;
11409
John McCall4124c492011-10-17 18:40:02 +000011410 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011411 return false;
11412}
John McCall4124c492011-10-17 18:40:02 +000011413
Sam Panzer0f384432012-08-21 00:52:01 +000011414/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11415/// the completed call expression. If overload resolution fails, emits
11416/// diagnostics and returns ExprError()
11417static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11418 UnresolvedLookupExpr *ULE,
11419 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011420 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011421 SourceLocation RParenLoc,
11422 Expr *ExecConfig,
11423 OverloadCandidateSet *CandidateSet,
11424 OverloadCandidateSet::iterator *Best,
11425 OverloadingResult OverloadResult,
11426 bool AllowTypoCorrection) {
11427 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011428 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011429 RParenLoc, /*EmptyLookup=*/true,
11430 AllowTypoCorrection);
11431
11432 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011433 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011434 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011435 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011436 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11437 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011438 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011439 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11440 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011441 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011442
Richard Smith998a5912011-06-05 22:42:48 +000011443 case OR_No_Viable_Function: {
11444 // Try to recover by looking for viable functions which the user might
11445 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011446 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011447 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011448 /*EmptyLookup=*/false,
11449 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011450 if (!Recovery.isInvalid())
11451 return Recovery;
11452
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011453 // If the user passes in a function that we can't take the address of, we
11454 // generally end up emitting really bad error messages. Here, we attempt to
11455 // emit better ones.
11456 for (const Expr *Arg : Args) {
11457 if (!Arg->getType()->isFunctionType())
11458 continue;
11459 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11460 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11461 if (FD &&
11462 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11463 Arg->getExprLoc()))
11464 return ExprError();
11465 }
11466 }
11467
11468 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11469 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011470 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011471 break;
Richard Smith998a5912011-06-05 22:42:48 +000011472 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011473
11474 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011475 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011476 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011477 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011478 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011479
Sam Panzer0f384432012-08-21 00:52:01 +000011480 case OR_Deleted: {
11481 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11482 << (*Best)->Function->isDeleted()
11483 << ULE->getName()
11484 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11485 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011486 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011487
Sam Panzer0f384432012-08-21 00:52:01 +000011488 // We emitted an error for the unvailable/deleted function call but keep
11489 // the call in the AST.
11490 FunctionDecl *FDecl = (*Best)->Function;
11491 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011492 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11493 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011494 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011495 }
11496
Douglas Gregorb412e172010-07-25 18:17:45 +000011497 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011498 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011499}
11500
George Burgess IV7204ed92016-01-07 02:26:57 +000011501static void markUnaddressableCandidatesUnviable(Sema &S,
11502 OverloadCandidateSet &CS) {
11503 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11504 if (I->Viable &&
11505 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11506 I->Viable = false;
11507 I->FailureKind = ovl_fail_addr_not_available;
11508 }
11509 }
11510}
11511
Sam Panzer0f384432012-08-21 00:52:01 +000011512/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11513/// (which eventually refers to the declaration Func) and the call
11514/// arguments Args/NumArgs, attempt to resolve the function call down
11515/// to a specific function. If overload resolution succeeds, returns
11516/// the call expression produced by overload resolution.
11517/// Otherwise, emits diagnostics and returns ExprError.
11518ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11519 UnresolvedLookupExpr *ULE,
11520 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011521 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011522 SourceLocation RParenLoc,
11523 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011524 bool AllowTypoCorrection,
11525 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011526 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11527 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011528 ExprResult result;
11529
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011530 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11531 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011532 return result;
11533
George Burgess IV7204ed92016-01-07 02:26:57 +000011534 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11535 // functions that aren't addressible are considered unviable.
11536 if (CalleesAddressIsTaken)
11537 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11538
Sam Panzer0f384432012-08-21 00:52:01 +000011539 OverloadCandidateSet::iterator Best;
11540 OverloadingResult OverloadResult =
11541 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11542
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011543 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011544 RParenLoc, ExecConfig, &CandidateSet,
11545 &Best, OverloadResult,
11546 AllowTypoCorrection);
11547}
11548
John McCall4c4c1df2010-01-26 03:27:55 +000011549static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011550 return Functions.size() > 1 ||
11551 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11552}
11553
Douglas Gregor084d8552009-03-13 23:49:33 +000011554/// \brief Create a unary operation that may resolve to an overloaded
11555/// operator.
11556///
11557/// \param OpLoc The location of the operator itself (e.g., '*').
11558///
Craig Toppera92ffb02015-12-10 08:51:49 +000011559/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011560///
James Dennett18348b62012-06-22 08:52:37 +000011561/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011562/// considered by overload resolution. The caller needs to build this
11563/// set based on the context using, e.g.,
11564/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11565/// set should not contain any member functions; those will be added
11566/// by CreateOverloadedUnaryOp().
11567///
James Dennett91738ff2012-06-22 10:32:46 +000011568/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011569ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011570Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011571 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011572 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011573 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11574 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11575 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011576 // TODO: provide better source location info.
11577 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011578
John McCall4124c492011-10-17 18:40:02 +000011579 if (checkPlaceholderForOverload(*this, Input))
11580 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011581
Craig Topperc3ec1492014-05-26 06:22:03 +000011582 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011583 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011584
Douglas Gregor084d8552009-03-13 23:49:33 +000011585 // For post-increment and post-decrement, add the implicit '0' as
11586 // the second argument, so that we know this is a post-increment or
11587 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011588 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011589 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011590 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11591 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011592 NumArgs = 2;
11593 }
11594
Richard Smithe54c3072013-05-05 15:51:06 +000011595 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11596
Douglas Gregor084d8552009-03-13 23:49:33 +000011597 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011598 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011599 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11600 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011601
Craig Topperc3ec1492014-05-26 06:22:03 +000011602 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011603 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011604 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011605 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011606 /*ADL*/ true, IsOverloaded(Fns),
11607 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011608 return new (Context)
11609 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11610 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011611 }
11612
11613 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011614 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011615
11616 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011617 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011618
11619 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011620 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011621
John McCall4c4c1df2010-01-26 03:27:55 +000011622 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011623 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011624 /*ExplicitTemplateArgs*/nullptr,
11625 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011626
Douglas Gregor084d8552009-03-13 23:49:33 +000011627 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011628 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011629
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011630 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11631
Douglas Gregor084d8552009-03-13 23:49:33 +000011632 // Perform overload resolution.
11633 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011634 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011635 case OR_Success: {
11636 // We found a built-in operator or an overloaded operator.
11637 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011638
Douglas Gregor084d8552009-03-13 23:49:33 +000011639 if (FnDecl) {
11640 // We matched an overloaded operator. Build a call to that
11641 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011642
Douglas Gregor084d8552009-03-13 23:49:33 +000011643 // Convert the arguments.
11644 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011645 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011646
John Wiegley01296292011-04-08 18:41:53 +000011647 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011648 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011649 Best->FoundDecl, Method);
11650 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011651 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011652 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011653 } else {
11654 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011655 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011656 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011657 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011658 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011659 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011660 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011661 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011662 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011663 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011664 }
11665
Douglas Gregor084d8552009-03-13 23:49:33 +000011666 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011667 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011668 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011669 if (FnExpr.isInvalid())
11670 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011671
Richard Smithc1564702013-11-15 02:58:23 +000011672 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011673 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011674 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11675 ResultTy = ResultTy.getNonLValueExprType(Context);
11676
Eli Friedman030eee42009-11-18 03:58:17 +000011677 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011678 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011679 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011680 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011681
Alp Toker314cc812014-01-25 16:55:45 +000011682 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011683 return ExprError();
11684
John McCallb268a282010-08-23 23:25:46 +000011685 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011686 } else {
11687 // We matched a built-in operator. Convert the arguments, then
11688 // break out so that we will build the appropriate built-in
11689 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011690 ExprResult InputRes =
11691 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11692 Best->Conversions[0], AA_Passing);
11693 if (InputRes.isInvalid())
11694 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011695 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011696 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011697 }
John Wiegley01296292011-04-08 18:41:53 +000011698 }
11699
11700 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011701 // This is an erroneous use of an operator which can be overloaded by
11702 // a non-member function. Check for non-member operators which were
11703 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011704 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011705 // FIXME: Recover by calling the found function.
11706 return ExprError();
11707
John Wiegley01296292011-04-08 18:41:53 +000011708 // No viable function; fall through to handling this as a
11709 // built-in operator, which will produce an error message for us.
11710 break;
11711
11712 case OR_Ambiguous:
11713 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11714 << UnaryOperator::getOpcodeStr(Opc)
11715 << Input->getType()
11716 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011717 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011718 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11719 return ExprError();
11720
11721 case OR_Deleted:
11722 Diag(OpLoc, diag::err_ovl_deleted_oper)
11723 << Best->Function->isDeleted()
11724 << UnaryOperator::getOpcodeStr(Opc)
11725 << getDeletedOrUnavailableSuffix(Best->Function)
11726 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011727 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011728 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011729 return ExprError();
11730 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011731
11732 // Either we found no viable overloaded operator or we matched a
11733 // built-in operator. In either case, fall through to trying to
11734 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011735 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011736}
11737
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011738/// \brief Create a binary operation that may resolve to an overloaded
11739/// operator.
11740///
11741/// \param OpLoc The location of the operator itself (e.g., '+').
11742///
Craig Toppera92ffb02015-12-10 08:51:49 +000011743/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011744///
James Dennett18348b62012-06-22 08:52:37 +000011745/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011746/// considered by overload resolution. The caller needs to build this
11747/// set based on the context using, e.g.,
11748/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11749/// set should not contain any member functions; those will be added
11750/// by CreateOverloadedBinOp().
11751///
11752/// \param LHS Left-hand argument.
11753/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011754ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011755Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011756 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011757 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011758 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011759 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011760 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011761
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011762 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11763 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11764
11765 // If either side is type-dependent, create an appropriate dependent
11766 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011767 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011768 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011769 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011770 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011771 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011772 return new (Context) BinaryOperator(
11773 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11774 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011775
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011776 return new (Context) CompoundAssignOperator(
11777 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11778 Context.DependentTy, Context.DependentTy, OpLoc,
11779 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011780 }
John McCall4c4c1df2010-01-26 03:27:55 +000011781
11782 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011783 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011784 // TODO: provide better source location info in DNLoc component.
11785 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011786 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011787 = UnresolvedLookupExpr::Create(Context, NamingClass,
11788 NestedNameSpecifierLoc(), OpNameInfo,
11789 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011790 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011791 return new (Context)
11792 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11793 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011794 }
11795
John McCall4124c492011-10-17 18:40:02 +000011796 // Always do placeholder-like conversions on the RHS.
11797 if (checkPlaceholderForOverload(*this, Args[1]))
11798 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011799
John McCall526ab472011-10-25 17:37:35 +000011800 // Do placeholder-like conversion on the LHS; note that we should
11801 // not get here with a PseudoObject LHS.
11802 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011803 if (checkPlaceholderForOverload(*this, Args[0]))
11804 return ExprError();
11805
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011806 // If this is the assignment operator, we only perform overload resolution
11807 // if the left-hand side is a class or enumeration type. This is actually
11808 // a hack. The standard requires that we do overload resolution between the
11809 // various built-in candidates, but as DR507 points out, this can lead to
11810 // problems. So we do it this way, which pretty much follows what GCC does.
11811 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011812 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011813 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011814
John McCalle26a8722010-12-04 08:14:53 +000011815 // If this is the .* operator, which is not overloadable, just
11816 // create a built-in binary operator.
11817 if (Opc == BO_PtrMemD)
11818 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11819
Douglas Gregor084d8552009-03-13 23:49:33 +000011820 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011821 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011822
11823 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011824 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011825
11826 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011827 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011828
Richard Smith0daabd72014-09-23 20:31:39 +000011829 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11830 // performed for an assignment operator (nor for operator[] nor operator->,
11831 // which don't get here).
11832 if (Opc != BO_Assign)
11833 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11834 /*ExplicitTemplateArgs*/ nullptr,
11835 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011836
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011837 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011838 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011839
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011840 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11841
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011842 // Perform overload resolution.
11843 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011844 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011845 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011846 // We found a built-in operator or an overloaded operator.
11847 FunctionDecl *FnDecl = Best->Function;
11848
11849 if (FnDecl) {
11850 // We matched an overloaded operator. Build a call to that
11851 // operator.
11852
11853 // Convert the arguments.
11854 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011855 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011856 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011857
Chandler Carruth8e543b32010-12-12 08:17:55 +000011858 ExprResult Arg1 =
11859 PerformCopyInitialization(
11860 InitializedEntity::InitializeParameter(Context,
11861 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011862 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011863 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011864 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011865
John Wiegley01296292011-04-08 18:41:53 +000011866 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011867 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011868 Best->FoundDecl, Method);
11869 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011870 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011871 Args[0] = Arg0.getAs<Expr>();
11872 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011873 } else {
11874 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011875 ExprResult Arg0 = PerformCopyInitialization(
11876 InitializedEntity::InitializeParameter(Context,
11877 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011878 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011879 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011880 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011881
Chandler Carruth8e543b32010-12-12 08:17:55 +000011882 ExprResult Arg1 =
11883 PerformCopyInitialization(
11884 InitializedEntity::InitializeParameter(Context,
11885 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011886 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011887 if (Arg1.isInvalid())
11888 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011889 Args[0] = LHS = Arg0.getAs<Expr>();
11890 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011891 }
11892
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011893 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011894 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011895 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011896 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011897 if (FnExpr.isInvalid())
11898 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011899
Richard Smithc1564702013-11-15 02:58:23 +000011900 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011901 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011902 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11903 ResultTy = ResultTy.getNonLValueExprType(Context);
11904
John McCallb268a282010-08-23 23:25:46 +000011905 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011906 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011907 Args, ResultTy, VK, OpLoc,
11908 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011909
Alp Toker314cc812014-01-25 16:55:45 +000011910 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011911 FnDecl))
11912 return ExprError();
11913
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011914 ArrayRef<const Expr *> ArgsArray(Args, 2);
11915 // Cut off the implicit 'this'.
11916 if (isa<CXXMethodDecl>(FnDecl))
11917 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011918
11919 // Check for a self move.
11920 if (Op == OO_Equal)
11921 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11922
Douglas Gregorb4866e82015-06-19 18:13:19 +000011923 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011924 TheCall->getSourceRange(), VariadicDoesNotApply);
11925
John McCallb268a282010-08-23 23:25:46 +000011926 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011927 } else {
11928 // We matched a built-in operator. Convert the arguments, then
11929 // break out so that we will build the appropriate built-in
11930 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011931 ExprResult ArgsRes0 =
11932 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11933 Best->Conversions[0], AA_Passing);
11934 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011935 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011936 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011937
John Wiegley01296292011-04-08 18:41:53 +000011938 ExprResult ArgsRes1 =
11939 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11940 Best->Conversions[1], AA_Passing);
11941 if (ArgsRes1.isInvalid())
11942 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011943 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011944 break;
11945 }
11946 }
11947
Douglas Gregor66950a32009-09-30 21:46:01 +000011948 case OR_No_Viable_Function: {
11949 // C++ [over.match.oper]p9:
11950 // If the operator is the operator , [...] and there are no
11951 // viable functions, then the operator is assumed to be the
11952 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011953 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011954 break;
11955
Chandler Carruth8e543b32010-12-12 08:17:55 +000011956 // For class as left operand for assignment or compound assigment
11957 // operator do not fall through to handling in built-in, but report that
11958 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011959 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011960 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011961 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011962 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11963 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011964 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011965 if (Args[0]->getType()->isIncompleteType()) {
11966 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11967 << Args[0]->getType()
11968 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11969 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011970 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011971 // This is an erroneous use of an operator which can be overloaded by
11972 // a non-member function. Check for non-member operators which were
11973 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011974 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011975 // FIXME: Recover by calling the found function.
11976 return ExprError();
11977
Douglas Gregor66950a32009-09-30 21:46:01 +000011978 // No viable function; try to create a built-in operation, which will
11979 // produce an error. Then, show the non-viable candidates.
11980 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011982 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011983 "C++ binary operator overloading is missing candidates!");
11984 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011985 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011986 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011987 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011988 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011989
11990 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011991 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011992 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011993 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011994 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011995 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011996 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011997 return ExprError();
11998
11999 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012000 if (isImplicitlyDeleted(Best->Function)) {
12001 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12002 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012003 << Context.getRecordType(Method->getParent())
12004 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012005
Richard Smithde1a4872012-12-28 12:23:24 +000012006 // The user probably meant to call this special member. Just
12007 // explain why it's deleted.
12008 NoteDeletedFunction(Method);
12009 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012010 } else {
12011 Diag(OpLoc, diag::err_ovl_deleted_oper)
12012 << Best->Function->isDeleted()
12013 << BinaryOperator::getOpcodeStr(Opc)
12014 << getDeletedOrUnavailableSuffix(Best->Function)
12015 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12016 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012017 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012018 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012019 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012020 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012021
Douglas Gregor66950a32009-09-30 21:46:01 +000012022 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012023 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012024}
12025
John McCalldadc5752010-08-24 06:29:42 +000012026ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012027Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12028 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012029 Expr *Base, Expr *Idx) {
12030 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012031 DeclarationName OpName =
12032 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12033
12034 // If either side is type-dependent, create an appropriate dependent
12035 // expression.
12036 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12037
Craig Topperc3ec1492014-05-26 06:22:03 +000012038 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012039 // CHECKME: no 'operator' keyword?
12040 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12041 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012042 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012043 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012044 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012045 /*ADL*/ true, /*Overloaded*/ false,
12046 UnresolvedSetIterator(),
12047 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012048 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012049
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012050 return new (Context)
12051 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12052 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012053 }
12054
John McCall4124c492011-10-17 18:40:02 +000012055 // Handle placeholders on both operands.
12056 if (checkPlaceholderForOverload(*this, Args[0]))
12057 return ExprError();
12058 if (checkPlaceholderForOverload(*this, Args[1]))
12059 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012060
Sebastian Redladba46e2009-10-29 20:17:01 +000012061 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012062 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012063
12064 // Subscript can only be overloaded as a member function.
12065
12066 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012067 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012068
12069 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012070 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012071
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012072 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12073
Sebastian Redladba46e2009-10-29 20:17:01 +000012074 // Perform overload resolution.
12075 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012076 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012077 case OR_Success: {
12078 // We found a built-in operator or an overloaded operator.
12079 FunctionDecl *FnDecl = Best->Function;
12080
12081 if (FnDecl) {
12082 // We matched an overloaded operator. Build a call to that
12083 // operator.
12084
John McCalla0296f72010-03-19 07:35:19 +000012085 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012086
Sebastian Redladba46e2009-10-29 20:17:01 +000012087 // Convert the arguments.
12088 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012089 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012090 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012091 Best->FoundDecl, Method);
12092 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012093 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012094 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012095
Anders Carlssona68e51e2010-01-29 18:37:50 +000012096 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012097 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012098 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012099 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012100 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012101 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012102 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012103 if (InputInit.isInvalid())
12104 return ExprError();
12105
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012106 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012107
Sebastian Redladba46e2009-10-29 20:17:01 +000012108 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012109 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12110 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012111 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012112 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012113 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012114 OpLocInfo.getLoc(),
12115 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012116 if (FnExpr.isInvalid())
12117 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012118
Richard Smithc1564702013-11-15 02:58:23 +000012119 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012120 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012121 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12122 ResultTy = ResultTy.getNonLValueExprType(Context);
12123
John McCallb268a282010-08-23 23:25:46 +000012124 CXXOperatorCallExpr *TheCall =
12125 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012126 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012127 ResultTy, VK, RLoc,
12128 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012129
Alp Toker314cc812014-01-25 16:55:45 +000012130 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012131 return ExprError();
12132
John McCallb268a282010-08-23 23:25:46 +000012133 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012134 } else {
12135 // We matched a built-in operator. Convert the arguments, then
12136 // break out so that we will build the appropriate built-in
12137 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012138 ExprResult ArgsRes0 =
12139 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12140 Best->Conversions[0], AA_Passing);
12141 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012142 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012143 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012144
12145 ExprResult ArgsRes1 =
12146 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12147 Best->Conversions[1], AA_Passing);
12148 if (ArgsRes1.isInvalid())
12149 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012150 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012151
12152 break;
12153 }
12154 }
12155
12156 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012157 if (CandidateSet.empty())
12158 Diag(LLoc, diag::err_ovl_no_oper)
12159 << Args[0]->getType() << /*subscript*/ 0
12160 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12161 else
12162 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12163 << Args[0]->getType()
12164 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012165 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012166 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012167 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012168 }
12169
12170 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012171 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012172 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012173 << Args[0]->getType() << Args[1]->getType()
12174 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012175 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012176 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012177 return ExprError();
12178
12179 case OR_Deleted:
12180 Diag(LLoc, diag::err_ovl_deleted_oper)
12181 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012182 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012183 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012184 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012185 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012186 return ExprError();
12187 }
12188
12189 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012190 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012191}
12192
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012193/// BuildCallToMemberFunction - Build a call to a member
12194/// function. MemExpr is the expression that refers to the member
12195/// function (and includes the object parameter), Args/NumArgs are the
12196/// arguments to the function call (not including the object
12197/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012198/// expression refers to a non-static member function or an overloaded
12199/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012200ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012201Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012202 SourceLocation LParenLoc,
12203 MultiExprArg Args,
12204 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012205 assert(MemExprE->getType() == Context.BoundMemberTy ||
12206 MemExprE->getType() == Context.OverloadTy);
12207
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012208 // Dig out the member expression. This holds both the object
12209 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012210 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012211
John McCall0009fcc2011-04-26 20:42:42 +000012212 // Determine whether this is a call to a pointer-to-member function.
12213 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12214 assert(op->getType() == Context.BoundMemberTy);
12215 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12216
12217 QualType fnType =
12218 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12219
12220 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12221 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012222 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012223
12224 // Check that the object type isn't more qualified than the
12225 // member function we're calling.
12226 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12227
12228 QualType objectType = op->getLHS()->getType();
12229 if (op->getOpcode() == BO_PtrMemI)
12230 objectType = objectType->castAs<PointerType>()->getPointeeType();
12231 Qualifiers objectQuals = objectType.getQualifiers();
12232
12233 Qualifiers difference = objectQuals - funcQuals;
12234 difference.removeObjCGCAttr();
12235 difference.removeAddressSpace();
12236 if (difference) {
12237 std::string qualsString = difference.getAsString();
12238 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12239 << fnType.getUnqualifiedType()
12240 << qualsString
12241 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12242 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012243
John McCall0009fcc2011-04-26 20:42:42 +000012244 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012245 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012246 resultType, valueKind, RParenLoc);
12247
Alp Toker314cc812014-01-25 16:55:45 +000012248 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012249 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012250 return ExprError();
12251
Craig Topperc3ec1492014-05-26 06:22:03 +000012252 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012253 return ExprError();
12254
Richard Trieu9be9c682013-06-22 02:30:38 +000012255 if (CheckOtherCall(call, proto))
12256 return ExprError();
12257
John McCall0009fcc2011-04-26 20:42:42 +000012258 return MaybeBindToTemporary(call);
12259 }
12260
David Majnemerced8bdf2015-02-25 17:36:15 +000012261 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12262 return new (Context)
12263 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12264
John McCall4124c492011-10-17 18:40:02 +000012265 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012266 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012267 return ExprError();
12268
John McCall10eae182009-11-30 22:42:35 +000012269 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012270 CXXMethodDecl *Method = nullptr;
12271 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12272 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012273 if (isa<MemberExpr>(NakedMemExpr)) {
12274 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012275 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012276 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012277 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012278 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012279 } else {
12280 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012281 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012282
John McCall6e9f8f62009-12-03 04:06:58 +000012283 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012284 Expr::Classification ObjectClassification
12285 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12286 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012287
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012288 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012289 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12290 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012291
John McCall2d74de92009-12-01 22:10:20 +000012292 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012293 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012294 if (UnresExpr->hasExplicitTemplateArgs()) {
12295 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12296 TemplateArgs = &TemplateArgsBuffer;
12297 }
12298
John McCall10eae182009-11-30 22:42:35 +000012299 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12300 E = UnresExpr->decls_end(); I != E; ++I) {
12301
John McCall6e9f8f62009-12-03 04:06:58 +000012302 NamedDecl *Func = *I;
12303 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12304 if (isa<UsingShadowDecl>(Func))
12305 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12306
Douglas Gregor02824322011-01-26 19:30:28 +000012307
Francois Pichet64225792011-01-18 05:04:39 +000012308 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012309 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012310 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012311 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012312 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012313 // If explicit template arguments were provided, we can't call a
12314 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012315 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012316 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012317
John McCalla0296f72010-03-19 07:35:19 +000012318 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012319 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012320 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012321 } else {
John McCall10eae182009-11-30 22:42:35 +000012322 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012323 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012324 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012325 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012326 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012327 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012328 }
Mike Stump11289f42009-09-09 15:08:12 +000012329
John McCall10eae182009-11-30 22:42:35 +000012330 DeclarationName DeclName = UnresExpr->getMemberName();
12331
John McCall4124c492011-10-17 18:40:02 +000012332 UnbridgedCasts.restore();
12333
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012334 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012335 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012336 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012337 case OR_Success:
12338 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012339 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012340 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012341 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12342 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012343 // If FoundDecl is different from Method (such as if one is a template
12344 // and the other a specialization), make sure DiagnoseUseOfDecl is
12345 // called on both.
12346 // FIXME: This would be more comprehensively addressed by modifying
12347 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12348 // being used.
12349 if (Method != FoundDecl.getDecl() &&
12350 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12351 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012352 break;
12353
12354 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012355 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012356 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012357 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012358 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012359 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012360 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012361
12362 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012363 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012364 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012365 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012366 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012367 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012368
12369 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012370 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012371 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012372 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012373 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012374 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012375 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012376 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012377 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012378 }
12379
John McCall16df1e52010-03-30 21:47:33 +000012380 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012381
John McCall2d74de92009-12-01 22:10:20 +000012382 // If overload resolution picked a static member, build a
12383 // non-member call based on that function.
12384 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012385 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12386 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012387 }
12388
John McCall10eae182009-11-30 22:42:35 +000012389 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012390 }
12391
Alp Toker314cc812014-01-25 16:55:45 +000012392 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012393 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12394 ResultType = ResultType.getNonLValueExprType(Context);
12395
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012396 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012397 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012398 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012399 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012400
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012401 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012402 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012403 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012404 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012405
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012406 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012407 // We only need to do this if there was actually an overload; otherwise
12408 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012409 if (!Method->isStatic()) {
12410 ExprResult ObjectArg =
12411 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12412 FoundDecl, Method);
12413 if (ObjectArg.isInvalid())
12414 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012415 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012416 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012417
12418 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012419 const FunctionProtoType *Proto =
12420 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012421 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012422 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012423 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012424
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012425 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012426
Richard Smith55ce3522012-06-25 20:30:08 +000012427 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012428 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012429
George Burgess IVaea6ade2015-09-25 17:53:16 +000012430 // In the case the method to call was not selected by the overloading
12431 // resolution process, we still need to handle the enable_if attribute. Do
12432 // that here, so it will not hide previous -- and more relevant -- errors
12433 if (isa<MemberExpr>(NakedMemExpr)) {
12434 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12435 Diag(MemExprE->getLocStart(),
12436 diag::err_ovl_no_viable_member_function_in_call)
12437 << Method << Method->getSourceRange();
12438 Diag(Method->getLocation(),
12439 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12440 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12441 return ExprError();
12442 }
12443 }
12444
Anders Carlsson47061ee2011-05-06 14:25:31 +000012445 if ((isa<CXXConstructorDecl>(CurContext) ||
12446 isa<CXXDestructorDecl>(CurContext)) &&
12447 TheCall->getMethodDecl()->isPure()) {
12448 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12449
Davide Italianoccb37382015-07-14 23:36:10 +000012450 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12451 MemExpr->performsVirtualDispatch(getLangOpts())) {
12452 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012453 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12454 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12455 << MD->getParent()->getDeclName();
12456
12457 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012458 if (getLangOpts().AppleKext)
12459 Diag(MemExpr->getLocStart(),
12460 diag::note_pure_qualified_call_kext)
12461 << MD->getParent()->getDeclName()
12462 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012463 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012464 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012465
12466 if (CXXDestructorDecl *DD =
12467 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12468 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012469 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012470 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12471 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12472 MemExpr->getMemberLoc());
12473 }
12474
John McCallb268a282010-08-23 23:25:46 +000012475 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012476}
12477
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012478/// BuildCallToObjectOfClassType - Build a call to an object of class
12479/// type (C++ [over.call.object]), which can end up invoking an
12480/// overloaded function call operator (@c operator()) or performing a
12481/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012482ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012483Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012484 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012485 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012486 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012487 if (checkPlaceholderForOverload(*this, Obj))
12488 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012489 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012490
12491 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012492 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012493 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012494
Nico Weberb58e51c2014-11-19 05:21:39 +000012495 assert(Object.get()->getType()->isRecordType() &&
12496 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012497 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012498
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012499 // C++ [over.call.object]p1:
12500 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012501 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012502 // candidate functions includes at least the function call
12503 // operators of T. The function call operators of T are obtained by
12504 // ordinary lookup of the name operator() in the context of
12505 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012506 OverloadCandidateSet CandidateSet(LParenLoc,
12507 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012508 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012509
John Wiegley01296292011-04-08 18:41:53 +000012510 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012511 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012512 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012513
John McCall27b18f82009-11-17 02:14:36 +000012514 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12515 LookupQualifiedName(R, Record->getDecl());
12516 R.suppressDiagnostics();
12517
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012518 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012519 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012520 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012521 Object.get()->Classify(Context),
12522 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012523 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012525
Douglas Gregorab7897a2008-11-19 22:57:39 +000012526 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012527 // In addition, for each (non-explicit in C++0x) conversion function
12528 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012529 //
12530 // operator conversion-type-id () cv-qualifier;
12531 //
12532 // where cv-qualifier is the same cv-qualification as, or a
12533 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012534 // denotes the type "pointer to function of (P1,...,Pn) returning
12535 // R", or the type "reference to pointer to function of
12536 // (P1,...,Pn) returning R", or the type "reference to function
12537 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012538 // is also considered as a candidate function. Similarly,
12539 // surrogate call functions are added to the set of candidate
12540 // functions for each conversion function declared in an
12541 // accessible base class provided the function is not hidden
12542 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012543 const auto &Conversions =
12544 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12545 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012546 NamedDecl *D = *I;
12547 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12548 if (isa<UsingShadowDecl>(D))
12549 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012550
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012551 // Skip over templated conversion functions; they aren't
12552 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012553 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012554 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012555
John McCall6e9f8f62009-12-03 04:06:58 +000012556 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012557 if (!Conv->isExplicit()) {
12558 // Strip the reference type (if any) and then the pointer type (if
12559 // any) to get down to what might be a function type.
12560 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12561 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12562 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012563
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012564 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12565 {
12566 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012567 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012568 }
12569 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012570 }
Mike Stump11289f42009-09-09 15:08:12 +000012571
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012572 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12573
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012574 // Perform overload resolution.
12575 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012576 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012577 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012578 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012579 // Overload resolution succeeded; we'll build the appropriate call
12580 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012581 break;
12582
12583 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012584 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012585 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012586 << Object.get()->getType() << /*call*/ 1
12587 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012588 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012589 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012590 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012591 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012592 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012593 break;
12594
12595 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012596 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012597 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012598 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012599 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012600 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012601
12602 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012603 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012604 diag::err_ovl_deleted_object_call)
12605 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012606 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012607 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012608 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012609 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012610 break;
Mike Stump11289f42009-09-09 15:08:12 +000012611 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012612
Douglas Gregorb412e172010-07-25 18:17:45 +000012613 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012614 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012615
John McCall4124c492011-10-17 18:40:02 +000012616 UnbridgedCasts.restore();
12617
Craig Topperc3ec1492014-05-26 06:22:03 +000012618 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012619 // Since there is no function declaration, this is one of the
12620 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012621 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012622 = cast<CXXConversionDecl>(
12623 Best->Conversions[0].UserDefined.ConversionFunction);
12624
Craig Topperc3ec1492014-05-26 06:22:03 +000012625 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12626 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012627 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12628 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012629 assert(Conv == Best->FoundDecl.getDecl() &&
12630 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012631 // We selected one of the surrogate functions that converts the
12632 // object parameter to a function pointer. Perform the conversion
12633 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012634
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012635 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012636 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012637 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12638 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012639 if (Call.isInvalid())
12640 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012641 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012642 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12643 CK_UserDefinedConversion, Call.get(),
12644 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012645
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012646 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012647 }
12648
Craig Topperc3ec1492014-05-26 06:22:03 +000012649 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012650
Douglas Gregorab7897a2008-11-19 22:57:39 +000012651 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12652 // that calls this method, using Object for the implicit object
12653 // parameter and passing along the remaining arguments.
12654 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012655
12656 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012657 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012658 return ExprError();
12659
Chandler Carruth8e543b32010-12-12 08:17:55 +000012660 const FunctionProtoType *Proto =
12661 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012662
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012663 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012664
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012665 DeclarationNameInfo OpLocInfo(
12666 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12667 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012668 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012669 HadMultipleCandidates,
12670 OpLocInfo.getLoc(),
12671 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012672 if (NewFn.isInvalid())
12673 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012674
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012675 // Build the full argument list for the method call (the implicit object
12676 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012677 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012678 MethodArgs[0] = Object.get();
12679 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12680
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012681 // Once we've built TheCall, all of the expressions are properly
12682 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012683 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012684 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12685 ResultTy = ResultTy.getNonLValueExprType(Context);
12686
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012687 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012688 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012689 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12690 ResultTy, VK, RParenLoc, false);
12691 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012692
Alp Toker314cc812014-01-25 16:55:45 +000012693 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012694 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012695
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012696 // We may have default arguments. If so, we need to allocate more
12697 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012698 if (Args.size() < NumParams)
12699 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012700
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012701 bool IsError = false;
12702
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012703 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012704 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012705 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012706 Best->FoundDecl, Method);
12707 if (ObjRes.isInvalid())
12708 IsError = true;
12709 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012710 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012711 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012712
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012713 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012714 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012715 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012716 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012717 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012718
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012719 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012720
John McCalldadc5752010-08-24 06:29:42 +000012721 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012722 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012723 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012724 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012725 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012726
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012727 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012728 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012729 } else {
John McCalldadc5752010-08-24 06:29:42 +000012730 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012731 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12732 if (DefArg.isInvalid()) {
12733 IsError = true;
12734 break;
12735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012736
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012737 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012738 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012739
12740 TheCall->setArg(i + 1, Arg);
12741 }
12742
12743 // If this is a variadic call, handle args passed through "...".
12744 if (Proto->isVariadic()) {
12745 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012746 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012747 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12748 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012749 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012750 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012751 }
12752 }
12753
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012754 if (IsError) return true;
12755
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012756 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012757
Richard Smith55ce3522012-06-25 20:30:08 +000012758 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012759 return true;
12760
John McCalle172be52010-08-24 06:09:16 +000012761 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012762}
12763
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012764/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012765/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012766/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012767ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012768Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12769 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012770 assert(Base->getType()->isRecordType() &&
12771 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012772
John McCall4124c492011-10-17 18:40:02 +000012773 if (checkPlaceholderForOverload(*this, Base))
12774 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012775
John McCallbc077cf2010-02-08 23:07:23 +000012776 SourceLocation Loc = Base->getExprLoc();
12777
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012778 // C++ [over.ref]p1:
12779 //
12780 // [...] An expression x->m is interpreted as (x.operator->())->m
12781 // for a class object x of type T if T::operator->() exists and if
12782 // the operator is selected as the best match function by the
12783 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012784 DeclarationName OpName =
12785 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012786 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012787 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012788
John McCallbc077cf2010-02-08 23:07:23 +000012789 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012790 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012791 return ExprError();
12792
John McCall27b18f82009-11-17 02:14:36 +000012793 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12794 LookupQualifiedName(R, BaseRecord->getDecl());
12795 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012796
12797 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012798 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012799 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012800 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012801 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012802
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012803 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12804
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012805 // Perform overload resolution.
12806 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012807 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012808 case OR_Success:
12809 // Overload resolution succeeded; we'll build the call below.
12810 break;
12811
12812 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012813 if (CandidateSet.empty()) {
12814 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012815 if (NoArrowOperatorFound) {
12816 // Report this specific error to the caller instead of emitting a
12817 // diagnostic, as requested.
12818 *NoArrowOperatorFound = true;
12819 return ExprError();
12820 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012821 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12822 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012823 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012824 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012825 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012826 }
12827 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012828 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012829 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012830 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012831 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012832
12833 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012834 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12835 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012836 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012837 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012838
12839 case OR_Deleted:
12840 Diag(OpLoc, diag::err_ovl_deleted_oper)
12841 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012842 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012843 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012844 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012845 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012846 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012847 }
12848
Craig Topperc3ec1492014-05-26 06:22:03 +000012849 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012850
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012851 // Convert the object parameter.
12852 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012853 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012854 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012855 Best->FoundDecl, Method);
12856 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012857 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012858 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012859
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012860 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012861 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012862 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012863 if (FnExpr.isInvalid())
12864 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012865
Alp Toker314cc812014-01-25 16:55:45 +000012866 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012867 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12868 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012869 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012870 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012871 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012872
Alp Toker314cc812014-01-25 16:55:45 +000012873 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012874 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012875
12876 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012877}
12878
Richard Smithbcc22fc2012-03-09 08:00:36 +000012879/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12880/// a literal operator described by the provided lookup results.
12881ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12882 DeclarationNameInfo &SuffixInfo,
12883 ArrayRef<Expr*> Args,
12884 SourceLocation LitEndLoc,
12885 TemplateArgumentListInfo *TemplateArgs) {
12886 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012887
Richard Smith100b24a2014-04-17 01:52:14 +000012888 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12889 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012890 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12891 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012892
Richard Smithbcc22fc2012-03-09 08:00:36 +000012893 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12894
Richard Smithbcc22fc2012-03-09 08:00:36 +000012895 // Perform overload resolution. This will usually be trivial, but might need
12896 // to perform substitutions for a literal operator template.
12897 OverloadCandidateSet::iterator Best;
12898 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12899 case OR_Success:
12900 case OR_Deleted:
12901 break;
12902
12903 case OR_No_Viable_Function:
12904 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12905 << R.getLookupName();
12906 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12907 return ExprError();
12908
12909 case OR_Ambiguous:
12910 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12911 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12912 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012913 }
12914
Richard Smithbcc22fc2012-03-09 08:00:36 +000012915 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012916 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12917 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012918 SuffixInfo.getLoc(),
12919 SuffixInfo.getInfo());
12920 if (Fn.isInvalid())
12921 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012922
12923 // Check the argument types. This should almost always be a no-op, except
12924 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012925 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012926 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012927 ExprResult InputInit = PerformCopyInitialization(
12928 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12929 SourceLocation(), Args[ArgIdx]);
12930 if (InputInit.isInvalid())
12931 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012932 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012933 }
12934
Alp Toker314cc812014-01-25 16:55:45 +000012935 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012936 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12937 ResultTy = ResultTy.getNonLValueExprType(Context);
12938
Richard Smithc67fdd42012-03-07 08:35:16 +000012939 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012940 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012941 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012942 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12943
Alp Toker314cc812014-01-25 16:55:45 +000012944 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012945 return ExprError();
12946
Craig Topperc3ec1492014-05-26 06:22:03 +000012947 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012948 return ExprError();
12949
12950 return MaybeBindToTemporary(UDL);
12951}
12952
Sam Panzer0f384432012-08-21 00:52:01 +000012953/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12954/// given LookupResult is non-empty, it is assumed to describe a member which
12955/// will be invoked. Otherwise, the function will be found via argument
12956/// dependent lookup.
12957/// CallExpr is set to a valid expression and FRS_Success returned on success,
12958/// otherwise CallExpr is set to ExprError() and some non-success value
12959/// is returned.
12960Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012961Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12962 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012963 const DeclarationNameInfo &NameInfo,
12964 LookupResult &MemberLookup,
12965 OverloadCandidateSet *CandidateSet,
12966 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012967 Scope *S = nullptr;
12968
Sam Panzer0f384432012-08-21 00:52:01 +000012969 CandidateSet->clear();
12970 if (!MemberLookup.empty()) {
12971 ExprResult MemberRef =
12972 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12973 /*IsPtr=*/false, CXXScopeSpec(),
12974 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012975 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012976 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012977 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012978 if (MemberRef.isInvalid()) {
12979 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012980 return FRS_DiagnosticIssued;
12981 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012982 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012983 if (CallExpr->isInvalid()) {
12984 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012985 return FRS_DiagnosticIssued;
12986 }
12987 } else {
12988 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012989 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012990 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012991 NestedNameSpecifierLoc(), NameInfo,
12992 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012993 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012994
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012995 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012996 CandidateSet, CallExpr);
12997 if (CandidateSet->empty() || CandidateSetError) {
12998 *CallExpr = ExprError();
12999 return FRS_NoViableFunction;
13000 }
13001 OverloadCandidateSet::iterator Best;
13002 OverloadingResult OverloadResult =
13003 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13004
13005 if (OverloadResult == OR_No_Viable_Function) {
13006 *CallExpr = ExprError();
13007 return FRS_NoViableFunction;
13008 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013009 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013010 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013011 OverloadResult,
13012 /*AllowTypoCorrection=*/false);
13013 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13014 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013015 return FRS_DiagnosticIssued;
13016 }
13017 }
13018 return FRS_Success;
13019}
13020
13021
Douglas Gregorcd695e52008-11-10 20:40:00 +000013022/// FixOverloadedFunctionReference - E is an expression that refers to
13023/// a C++ overloaded function (possibly with some parentheses and
13024/// perhaps a '&' around it). We have resolved the overloaded function
13025/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013026/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013027Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013028 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013029 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013030 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13031 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013032 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013033 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013034
Douglas Gregor51c538b2009-11-20 19:42:02 +000013035 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013036 }
13037
Douglas Gregor51c538b2009-11-20 19:42:02 +000013038 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013039 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13040 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013041 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013042 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013043 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013044 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013045 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013046 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013047
13048 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013049 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013050 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013051 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013052 }
13053
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013054 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13055 if (!GSE->isResultDependent()) {
13056 Expr *SubExpr =
13057 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13058 if (SubExpr == GSE->getResultExpr())
13059 return GSE;
13060
13061 // Replace the resulting type information before rebuilding the generic
13062 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013063 ArrayRef<Expr *> A = GSE->getAssocExprs();
13064 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013065 unsigned ResultIdx = GSE->getResultIndex();
13066 AssocExprs[ResultIdx] = SubExpr;
13067
13068 return new (Context) GenericSelectionExpr(
13069 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13070 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13071 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13072 ResultIdx);
13073 }
13074 // Rather than fall through to the unreachable, return the original generic
13075 // selection expression.
13076 return GSE;
13077 }
13078
Douglas Gregor51c538b2009-11-20 19:42:02 +000013079 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013080 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013081 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013082 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13083 if (Method->isStatic()) {
13084 // Do nothing: static member functions aren't any different
13085 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013086 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013087 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013088 // UnresolvedLookupExpr holding an overloaded member function
13089 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013090 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13091 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013092 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013093 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013094
John McCalld14a8642009-11-21 08:51:07 +000013095 assert(isa<DeclRefExpr>(SubExpr)
13096 && "fixed to something other than a decl ref");
13097 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13098 && "fixed to a member ref with no nested name qualifier");
13099
13100 // We have taken the address of a pointer to member
13101 // function. Perform the computation here so that we get the
13102 // appropriate pointer to member type.
13103 QualType ClassType
13104 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13105 QualType MemPtrType
13106 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013107 // Under the MS ABI, lock down the inheritance model now.
13108 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13109 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013110
John McCall7decc9e2010-11-18 06:31:45 +000013111 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13112 VK_RValue, OK_Ordinary,
13113 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013114 }
13115 }
John McCall16df1e52010-03-30 21:47:33 +000013116 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13117 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013118 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013119 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013120
John McCalle3027922010-08-25 11:45:40 +000013121 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013122 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013123 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013124 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013125 }
John McCalld14a8642009-11-21 08:51:07 +000013126
13127 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013128 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013129 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013130 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013131 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13132 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013133 }
13134
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013135 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13136 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013137 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013138 Fn,
John McCall113bee02012-03-10 09:33:50 +000013139 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013140 ULE->getNameLoc(),
13141 Fn->getType(),
13142 VK_LValue,
13143 Found.getDecl(),
13144 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013145 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013146 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13147 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013148 }
13149
John McCall10eae182009-11-30 22:42:35 +000013150 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013151 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013152 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013153 if (MemExpr->hasExplicitTemplateArgs()) {
13154 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13155 TemplateArgs = &TemplateArgsBuffer;
13156 }
John McCall6b51f282009-11-23 01:53:49 +000013157
John McCall2d74de92009-12-01 22:10:20 +000013158 Expr *Base;
13159
John McCall7decc9e2010-11-18 06:31:45 +000013160 // If we're filling in a static method where we used to have an
13161 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013162 if (MemExpr->isImplicitAccess()) {
13163 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013164 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13165 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013166 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013167 Fn,
John McCall113bee02012-03-10 09:33:50 +000013168 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013169 MemExpr->getMemberLoc(),
13170 Fn->getType(),
13171 VK_LValue,
13172 Found.getDecl(),
13173 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013174 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013175 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13176 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013177 } else {
13178 SourceLocation Loc = MemExpr->getMemberLoc();
13179 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013180 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013181 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013182 Base = new (Context) CXXThisExpr(Loc,
13183 MemExpr->getBaseType(),
13184 /*isImplicit=*/true);
13185 }
John McCall2d74de92009-12-01 22:10:20 +000013186 } else
John McCallc3007a22010-10-26 07:05:15 +000013187 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013188
John McCall4adb38c2011-04-27 00:36:17 +000013189 ExprValueKind valueKind;
13190 QualType type;
13191 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13192 valueKind = VK_LValue;
13193 type = Fn->getType();
13194 } else {
13195 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013196 type = Context.BoundMemberTy;
13197 }
13198
13199 MemberExpr *ME = MemberExpr::Create(
13200 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13201 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13202 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13203 OK_Ordinary);
13204 ME->setHadMultipleCandidates(true);
13205 MarkMemberReferenced(ME);
13206 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013208
John McCallc3007a22010-10-26 07:05:15 +000013209 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013210}
13211
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013212ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013213 DeclAccessPair Found,
13214 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013215 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013216}