1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeOrdering.h"
26#include "clang/Basic/Diagnostic.h"
27#include "clang/Basic/DiagnosticOptions.h"
28#include "clang/Basic/OperatorKinds.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Sema/EnterExpressionEvaluationContext.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
36#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaInternal.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
40#include "clang/Sema/TemplateDeduction.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/Support/Casting.h"
49#include <algorithm>
50#include <cstddef>
51#include <cstdlib>
52#include <optional>
53
54using namespace clang;
55using namespace sema;
56
57using AllowedExplicit = Sema::AllowedExplicit;
58
59static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
60 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
61 return P->hasAttr<PassObjectSizeAttr>();
62 });
63}
64
65/// A convenience routine for creating a decayed reference to a function.
66static ExprResult CreateFunctionRefExpr(
67 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
68 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
69 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
70 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
71 return ExprError();
72 // If FoundDecl is different from Fn (such as if one is a template
73 // and the other a specialization), make sure DiagnoseUseOfDecl is
74 // called on both.
75 // FIXME: This would be more comprehensively addressed by modifying
76 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
77 // being used.
78 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
79 return ExprError();
80 DeclRefExpr *DRE = new (S.Context)
81 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
82 if (HadMultipleCandidates)
83 DRE->setHadMultipleCandidates(true);
84
85 S.MarkDeclRefReferenced(E: DRE, Base);
86 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
87 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
88 S.ResolveExceptionSpec(Loc, FPT);
89 DRE->setType(Fn->getType());
90 }
91 }
92 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
93 CK: CK_FunctionToPointerDecay);
94}
95
96static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
97 bool InOverloadResolution,
98 StandardConversionSequence &SCS,
99 bool CStyle,
100 bool AllowObjCWritebackConversion);
101
102static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
103 QualType &ToType,
104 bool InOverloadResolution,
105 StandardConversionSequence &SCS,
106 bool CStyle);
107static OverloadingResult
108IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
109 UserDefinedConversionSequence& User,
110 OverloadCandidateSet& Conversions,
111 AllowedExplicit AllowExplicit,
112 bool AllowObjCConversionOnExplicit);
113
114static ImplicitConversionSequence::CompareKind
115CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
116 const StandardConversionSequence& SCS1,
117 const StandardConversionSequence& SCS2);
118
119static ImplicitConversionSequence::CompareKind
120CompareQualificationConversions(Sema &S,
121 const StandardConversionSequence& SCS1,
122 const StandardConversionSequence& SCS2);
123
124static ImplicitConversionSequence::CompareKind
125CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
126 const StandardConversionSequence& SCS1,
127 const StandardConversionSequence& SCS2);
128
129/// GetConversionRank - Retrieve the implicit conversion rank
130/// corresponding to the given implicit conversion kind.
131ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
132 static const ImplicitConversionRank Rank[] = {
133 ICR_Exact_Match,
134 ICR_Exact_Match,
135 ICR_Exact_Match,
136 ICR_Exact_Match,
137 ICR_Exact_Match,
138 ICR_Exact_Match,
139 ICR_Promotion,
140 ICR_Promotion,
141 ICR_Promotion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_Conversion,
150 ICR_Conversion,
151 ICR_Conversion,
152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_OCL_Scalar_Widening,
155 ICR_Complex_Real_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
158 ICR_Writeback_Conversion,
159 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
160 // it was omitted by the patch that added
161 // ICK_Zero_Event_Conversion
162 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
163 // it was omitted by the patch that added
164 // ICK_Zero_Queue_Conversion
165 ICR_C_Conversion,
166 ICR_C_Conversion_Extension,
167 ICR_Conversion,
168 ICR_HLSL_Dimension_Reduction,
169 ICR_Conversion,
170 ICR_HLSL_Scalar_Widening,
171 };
172 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
173 return Rank[(int)Kind];
174}
175
176ImplicitConversionRank
177clang::GetDimensionConversionRank(ImplicitConversionRank Base,
178 ImplicitConversionKind Dimension) {
179 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
180 if (Rank == ICR_HLSL_Scalar_Widening) {
181 if (Base == ICR_Promotion)
182 return ICR_HLSL_Scalar_Widening_Promotion;
183 if (Base == ICR_Conversion)
184 return ICR_HLSL_Scalar_Widening_Conversion;
185 }
186 if (Rank == ICR_HLSL_Dimension_Reduction) {
187 if (Base == ICR_Promotion)
188 return ICR_HLSL_Dimension_Reduction_Promotion;
189 if (Base == ICR_Conversion)
190 return ICR_HLSL_Dimension_Reduction_Conversion;
191 }
192 return Rank;
193}
194
195/// GetImplicitConversionName - Return the name of this kind of
196/// implicit conversion.
197static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
198 static const char *const Name[] = {
199 "No conversion",
200 "Lvalue-to-rvalue",
201 "Array-to-pointer",
202 "Function-to-pointer",
203 "Function pointer conversion",
204 "Qualification",
205 "Integral promotion",
206 "Floating point promotion",
207 "Complex promotion",
208 "Integral conversion",
209 "Floating conversion",
210 "Complex conversion",
211 "Floating-integral conversion",
212 "Pointer conversion",
213 "Pointer-to-member conversion",
214 "Boolean conversion",
215 "Compatible-types conversion",
216 "Derived-to-base conversion",
217 "Vector conversion",
218 "SVE Vector conversion",
219 "RVV Vector conversion",
220 "Vector splat",
221 "Complex-real conversion",
222 "Block Pointer conversion",
223 "Transparent Union Conversion",
224 "Writeback conversion",
225 "OpenCL Zero Event Conversion",
226 "OpenCL Zero Queue Conversion",
227 "C specific type conversion",
228 "Incompatible pointer conversion",
229 "Fixed point conversion",
230 "HLSL vector truncation",
231 "Non-decaying array conversion",
232 "HLSL vector splat",
233 };
234 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
235 return Name[Kind];
236}
237
238/// StandardConversionSequence - Set the standard conversion
239/// sequence to the identity conversion.
240void StandardConversionSequence::setAsIdentityConversion() {
241 First = ICK_Identity;
242 Second = ICK_Identity;
243 Dimension = ICK_Identity;
244 Third = ICK_Identity;
245 DeprecatedStringLiteralToCharPtr = false;
246 QualificationIncludesObjCLifetime = false;
247 ReferenceBinding = false;
248 DirectBinding = false;
249 IsLvalueReference = true;
250 BindsToFunctionLvalue = false;
251 BindsToRvalue = false;
252 BindsImplicitObjectArgumentWithoutRefQualifier = false;
253 ObjCLifetimeConversionBinding = false;
254 CopyConstructor = nullptr;
255}
256
257/// getRank - Retrieve the rank of this standard conversion sequence
258/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
259/// implicit conversions.
260ImplicitConversionRank StandardConversionSequence::getRank() const {
261 ImplicitConversionRank Rank = ICR_Exact_Match;
262 if (GetConversionRank(Kind: First) > Rank)
263 Rank = GetConversionRank(Kind: First);
264 if (GetConversionRank(Kind: Second) > Rank)
265 Rank = GetConversionRank(Kind: Second);
266 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
267 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
268 if (GetConversionRank(Kind: Third) > Rank)
269 Rank = GetConversionRank(Kind: Third);
270 return Rank;
271}
272
273/// isPointerConversionToBool - Determines whether this conversion is
274/// a conversion of a pointer or pointer-to-member to bool. This is
275/// used as part of the ranking of standard conversion sequences
276/// (C++ 13.3.3.2p4).
277bool StandardConversionSequence::isPointerConversionToBool() const {
278 // Note that FromType has not necessarily been transformed by the
279 // array-to-pointer or function-to-pointer implicit conversions, so
280 // check for their presence as well as checking whether FromType is
281 // a pointer.
282 if (getToType(Idx: 1)->isBooleanType() &&
283 (getFromType()->isPointerType() ||
284 getFromType()->isMemberPointerType() ||
285 getFromType()->isObjCObjectPointerType() ||
286 getFromType()->isBlockPointerType() ||
287 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
288 return true;
289
290 return false;
291}
292
293/// isPointerConversionToVoidPointer - Determines whether this
294/// conversion is a conversion of a pointer to a void pointer. This is
295/// used as part of the ranking of standard conversion sequences (C++
296/// 13.3.3.2p4).
297bool
298StandardConversionSequence::
299isPointerConversionToVoidPointer(ASTContext& Context) const {
300 QualType FromType = getFromType();
301 QualType ToType = getToType(Idx: 1);
302
303 // Note that FromType has not necessarily been transformed by the
304 // array-to-pointer implicit conversion, so check for its presence
305 // and redo the conversion to get a pointer.
306 if (First == ICK_Array_To_Pointer)
307 FromType = Context.getArrayDecayedType(T: FromType);
308
309 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
310 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
311 return ToPtrType->getPointeeType()->isVoidType();
312
313 return false;
314}
315
316/// Skip any implicit casts which could be either part of a narrowing conversion
317/// or after one in an implicit conversion.
318static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
319 const Expr *Converted) {
320 // We can have cleanups wrapping the converted expression; these need to be
321 // preserved so that destructors run if necessary.
322 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
323 Expr *Inner =
324 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
325 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
326 objects: EWC->getObjects());
327 }
328
329 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
330 switch (ICE->getCastKind()) {
331 case CK_NoOp:
332 case CK_IntegralCast:
333 case CK_IntegralToBoolean:
334 case CK_IntegralToFloating:
335 case CK_BooleanToSignedIntegral:
336 case CK_FloatingToIntegral:
337 case CK_FloatingToBoolean:
338 case CK_FloatingCast:
339 Converted = ICE->getSubExpr();
340 continue;
341
342 default:
343 return Converted;
344 }
345 }
346
347 return Converted;
348}
349
350/// Check if this standard conversion sequence represents a narrowing
351/// conversion, according to C++11 [dcl.init.list]p7.
352///
353/// \param Ctx The AST context.
354/// \param Converted The result of applying this standard conversion sequence.
355/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
356/// value of the expression prior to the narrowing conversion.
357/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
358/// type of the expression prior to the narrowing conversion.
359/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
360/// from floating point types to integral types should be ignored.
361NarrowingKind StandardConversionSequence::getNarrowingKind(
362 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
363 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
364 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
365 "narrowing check outside C++");
366
367 // C++11 [dcl.init.list]p7:
368 // A narrowing conversion is an implicit conversion ...
369 QualType FromType = getToType(Idx: 0);
370 QualType ToType = getToType(Idx: 1);
371
372 // A conversion to an enumeration type is narrowing if the conversion to
373 // the underlying type is narrowing. This only arises for expressions of
374 // the form 'Enum{init}'.
375 if (auto *ET = ToType->getAs<EnumType>())
376 ToType = ET->getDecl()->getIntegerType();
377
378 switch (Second) {
379 // 'bool' is an integral type; dispatch to the right place to handle it.
380 case ICK_Boolean_Conversion:
381 if (FromType->isRealFloatingType())
382 goto FloatingIntegralConversion;
383 if (FromType->isIntegralOrUnscopedEnumerationType())
384 goto IntegralConversion;
385 // -- from a pointer type or pointer-to-member type to bool, or
386 return NK_Type_Narrowing;
387
388 // -- from a floating-point type to an integer type, or
389 //
390 // -- from an integer type or unscoped enumeration type to a floating-point
391 // type, except where the source is a constant expression and the actual
392 // value after conversion will fit into the target type and will produce
393 // the original value when converted back to the original type, or
394 case ICK_Floating_Integral:
395 FloatingIntegralConversion:
396 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
397 return NK_Type_Narrowing;
398 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
399 ToType->isRealFloatingType()) {
400 if (IgnoreFloatToIntegralConversion)
401 return NK_Not_Narrowing;
402 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
403 assert(Initializer && "Unknown conversion expression");
404
405 // If it's value-dependent, we can't tell whether it's narrowing.
406 if (Initializer->isValueDependent())
407 return NK_Dependent_Narrowing;
408
409 if (std::optional<llvm::APSInt> IntConstantValue =
410 Initializer->getIntegerConstantExpr(Ctx)) {
411 // Convert the integer to the floating type.
412 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
413 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
414 RM: llvm::APFloat::rmNearestTiesToEven);
415 // And back.
416 llvm::APSInt ConvertedValue = *IntConstantValue;
417 bool ignored;
418 Result.convertToInteger(Result&: ConvertedValue,
419 RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
420 // If the resulting value is different, this was a narrowing conversion.
421 if (*IntConstantValue != ConvertedValue) {
422 ConstantValue = APValue(*IntConstantValue);
423 ConstantType = Initializer->getType();
424 return NK_Constant_Narrowing;
425 }
426 } else {
427 // Variables are always narrowings.
428 return NK_Variable_Narrowing;
429 }
430 }
431 return NK_Not_Narrowing;
432
433 // -- from long double to double or float, or from double to float, except
434 // where the source is a constant expression and the actual value after
435 // conversion is within the range of values that can be represented (even
436 // if it cannot be represented exactly), or
437 case ICK_Floating_Conversion:
438 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
439 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
440 // FromType is larger than ToType.
441 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
442
443 // If it's value-dependent, we can't tell whether it's narrowing.
444 if (Initializer->isValueDependent())
445 return NK_Dependent_Narrowing;
446
447 Expr::EvalResult R;
448 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
449 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)) {
450 // Constant!
451 if (Ctx.getLangOpts().C23)
452 ConstantValue = R.Val;
453 assert(ConstantValue.isFloat());
454 llvm::APFloat FloatVal = ConstantValue.getFloat();
455 // Convert the source value into the target type.
456 bool ignored;
457 llvm::APFloat Converted = FloatVal;
458 llvm::APFloat::opStatus ConvertStatus =
459 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
460 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
461 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
462 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
463 if (Ctx.getLangOpts().C23) {
464 if (FloatVal.isNaN() && Converted.isNaN() &&
465 !FloatVal.isSignaling() && !Converted.isSignaling()) {
466 // Quiet NaNs are considered the same value, regardless of
467 // payloads.
468 return NK_Not_Narrowing;
469 }
470 // For normal values, check exact equality.
471 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
472 ConstantType = Initializer->getType();
473 return NK_Constant_Narrowing;
474 }
475 } else {
476 // If there was no overflow, the source value is within the range of
477 // values that can be represented.
478 if (ConvertStatus & llvm::APFloat::opOverflow) {
479 ConstantType = Initializer->getType();
480 return NK_Constant_Narrowing;
481 }
482 }
483 } else {
484 return NK_Variable_Narrowing;
485 }
486 }
487 return NK_Not_Narrowing;
488
489 // -- from an integer type or unscoped enumeration type to an integer type
490 // that cannot represent all the values of the original type, except where
491 // the source is a constant expression and the actual value after
492 // conversion will fit into the target type and will produce the original
493 // value when converted back to the original type.
494 case ICK_Integral_Conversion:
495 IntegralConversion: {
496 assert(FromType->isIntegralOrUnscopedEnumerationType());
497 assert(ToType->isIntegralOrUnscopedEnumerationType());
498 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
499 const unsigned FromWidth = Ctx.getIntWidth(T: FromType);
500 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
501 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
502
503 if (FromWidth > ToWidth ||
504 (FromWidth == ToWidth && FromSigned != ToSigned) ||
505 (FromSigned && !ToSigned)) {
506 // Not all values of FromType can be represented in ToType.
507 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
508
509 // If it's value-dependent, we can't tell whether it's narrowing.
510 if (Initializer->isValueDependent())
511 return NK_Dependent_Narrowing;
512
513 std::optional<llvm::APSInt> OptInitializerValue;
514 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
515 // Such conversions on variables are always narrowing.
516 return NK_Variable_Narrowing;
517 }
518 llvm::APSInt &InitializerValue = *OptInitializerValue;
519 bool Narrowing = false;
520 if (FromWidth < ToWidth) {
521 // Negative -> unsigned is narrowing. Otherwise, more bits is never
522 // narrowing.
523 if (InitializerValue.isSigned() && InitializerValue.isNegative())
524 Narrowing = true;
525 } else {
526 // Add a bit to the InitializerValue so we don't have to worry about
527 // signed vs. unsigned comparisons.
528 InitializerValue = InitializerValue.extend(
529 width: InitializerValue.getBitWidth() + 1);
530 // Convert the initializer to and from the target width and signed-ness.
531 llvm::APSInt ConvertedValue = InitializerValue;
532 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
533 ConvertedValue.setIsSigned(ToSigned);
534 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
535 ConvertedValue.setIsSigned(InitializerValue.isSigned());
536 // If the result is different, this was a narrowing conversion.
537 if (ConvertedValue != InitializerValue)
538 Narrowing = true;
539 }
540 if (Narrowing) {
541 ConstantType = Initializer->getType();
542 ConstantValue = APValue(InitializerValue);
543 return NK_Constant_Narrowing;
544 }
545 }
546 return NK_Not_Narrowing;
547 }
548 case ICK_Complex_Real:
549 if (FromType->isComplexType() && !ToType->isComplexType())
550 return NK_Type_Narrowing;
551 return NK_Not_Narrowing;
552
553 case ICK_Floating_Promotion:
554 if (Ctx.getLangOpts().C23) {
555 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
556 Expr::EvalResult R;
557 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
558 ConstantValue = R.Val;
559 assert(ConstantValue.isFloat());
560 llvm::APFloat FloatVal = ConstantValue.getFloat();
561 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
562 // value, the unqualified versions of the type of the initializer and
563 // the corresponding real type of the object declared shall be
564 // compatible.
565 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
566 ConstantType = Initializer->getType();
567 return NK_Constant_Narrowing;
568 }
569 }
570 }
571 return NK_Not_Narrowing;
572 default:
573 // Other kinds of conversions are not narrowings.
574 return NK_Not_Narrowing;
575 }
576}
577
578/// dump - Print this standard conversion sequence to standard
579/// error. Useful for debugging overloading issues.
580LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
581 raw_ostream &OS = llvm::errs();
582 bool PrintedSomething = false;
583 if (First != ICK_Identity) {
584 OS << GetImplicitConversionName(Kind: First);
585 PrintedSomething = true;
586 }
587
588 if (Second != ICK_Identity) {
589 if (PrintedSomething) {
590 OS << " -> ";
591 }
592 OS << GetImplicitConversionName(Kind: Second);
593
594 if (CopyConstructor) {
595 OS << " (by copy constructor)";
596 } else if (DirectBinding) {
597 OS << " (direct reference binding)";
598 } else if (ReferenceBinding) {
599 OS << " (reference binding)";
600 }
601 PrintedSomething = true;
602 }
603
604 if (Third != ICK_Identity) {
605 if (PrintedSomething) {
606 OS << " -> ";
607 }
608 OS << GetImplicitConversionName(Kind: Third);
609 PrintedSomething = true;
610 }
611
612 if (!PrintedSomething) {
613 OS << "No conversions required";
614 }
615}
616
617/// dump - Print this user-defined conversion sequence to standard
618/// error. Useful for debugging overloading issues.
619void UserDefinedConversionSequence::dump() const {
620 raw_ostream &OS = llvm::errs();
621 if (Before.First || Before.Second || Before.Third) {
622 Before.dump();
623 OS << " -> ";
624 }
625 if (ConversionFunction)
626 OS << '\'' << *ConversionFunction << '\'';
627 else
628 OS << "aggregate initialization";
629 if (After.First || After.Second || After.Third) {
630 OS << " -> ";
631 After.dump();
632 }
633}
634
635/// dump - Print this implicit conversion sequence to standard
636/// error. Useful for debugging overloading issues.
637void ImplicitConversionSequence::dump() const {
638 raw_ostream &OS = llvm::errs();
639 if (hasInitializerListContainerType())
640 OS << "Worst list element conversion: ";
641 switch (ConversionKind) {
642 case StandardConversion:
643 OS << "Standard conversion: ";
644 Standard.dump();
645 break;
646 case UserDefinedConversion:
647 OS << "User-defined conversion: ";
648 UserDefined.dump();
649 break;
650 case EllipsisConversion:
651 OS << "Ellipsis conversion";
652 break;
653 case AmbiguousConversion:
654 OS << "Ambiguous conversion";
655 break;
656 case BadConversion:
657 OS << "Bad conversion";
658 break;
659 }
660
661 OS << "\n";
662}
663
664void AmbiguousConversionSequence::construct() {
665 new (&conversions()) ConversionSet();
666}
667
668void AmbiguousConversionSequence::destruct() {
669 conversions().~ConversionSet();
670}
671
672void
673AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
674 FromTypePtr = O.FromTypePtr;
675 ToTypePtr = O.ToTypePtr;
676 new (&conversions()) ConversionSet(O.conversions());
677}
678
679namespace {
680 // Structure used by DeductionFailureInfo to store
681 // template argument information.
682 struct DFIArguments {
683 TemplateArgument FirstArg;
684 TemplateArgument SecondArg;
685 };
686 // Structure used by DeductionFailureInfo to store
687 // template parameter and template argument information.
688 struct DFIParamWithArguments : DFIArguments {
689 TemplateParameter Param;
690 };
691 // Structure used by DeductionFailureInfo to store template argument
692 // information and the index of the problematic call argument.
693 struct DFIDeducedMismatchArgs : DFIArguments {
694 TemplateArgumentList *TemplateArgs;
695 unsigned CallArgIndex;
696 };
697 // Structure used by DeductionFailureInfo to store information about
698 // unsatisfied constraints.
699 struct CNSInfo {
700 TemplateArgumentList *TemplateArgs;
701 ConstraintSatisfaction Satisfaction;
702 };
703}
704
705/// Convert from Sema's representation of template deduction information
706/// to the form used in overload-candidate information.
707DeductionFailureInfo
708clang::MakeDeductionFailureInfo(ASTContext &Context,
709 TemplateDeductionResult TDK,
710 TemplateDeductionInfo &Info) {
711 DeductionFailureInfo Result;
712 Result.Result = static_cast<unsigned>(TDK);
713 Result.HasDiagnostic = false;
714 switch (TDK) {
715 case TemplateDeductionResult::Invalid:
716 case TemplateDeductionResult::InstantiationDepth:
717 case TemplateDeductionResult::TooManyArguments:
718 case TemplateDeductionResult::TooFewArguments:
719 case TemplateDeductionResult::MiscellaneousDeductionFailure:
720 case TemplateDeductionResult::CUDATargetMismatch:
721 Result.Data = nullptr;
722 break;
723
724 case TemplateDeductionResult::Incomplete:
725 case TemplateDeductionResult::InvalidExplicitArguments:
726 Result.Data = Info.Param.getOpaqueValue();
727 break;
728
729 case TemplateDeductionResult::DeducedMismatch:
730 case TemplateDeductionResult::DeducedMismatchNested: {
731 // FIXME: Should allocate from normal heap so that we can free this later.
732 auto *Saved = new (Context) DFIDeducedMismatchArgs;
733 Saved->FirstArg = Info.FirstArg;
734 Saved->SecondArg = Info.SecondArg;
735 Saved->TemplateArgs = Info.takeSugared();
736 Saved->CallArgIndex = Info.CallArgIndex;
737 Result.Data = Saved;
738 break;
739 }
740
741 case TemplateDeductionResult::NonDeducedMismatch: {
742 // FIXME: Should allocate from normal heap so that we can free this later.
743 DFIArguments *Saved = new (Context) DFIArguments;
744 Saved->FirstArg = Info.FirstArg;
745 Saved->SecondArg = Info.SecondArg;
746 Result.Data = Saved;
747 break;
748 }
749
750 case TemplateDeductionResult::IncompletePack:
751 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
752 case TemplateDeductionResult::Inconsistent:
753 case TemplateDeductionResult::Underqualified: {
754 // FIXME: Should allocate from normal heap so that we can free this later.
755 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
756 Saved->Param = Info.Param;
757 Saved->FirstArg = Info.FirstArg;
758 Saved->SecondArg = Info.SecondArg;
759 Result.Data = Saved;
760 break;
761 }
762
763 case TemplateDeductionResult::SubstitutionFailure:
764 Result.Data = Info.takeSugared();
765 if (Info.hasSFINAEDiagnostic()) {
766 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
767 SourceLocation(), PartialDiagnostic::NullDiagnostic());
768 Info.takeSFINAEDiagnostic(PD&: *Diag);
769 Result.HasDiagnostic = true;
770 }
771 break;
772
773 case TemplateDeductionResult::ConstraintsNotSatisfied: {
774 CNSInfo *Saved = new (Context) CNSInfo;
775 Saved->TemplateArgs = Info.takeSugared();
776 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
777 Result.Data = Saved;
778 break;
779 }
780
781 case TemplateDeductionResult::Success:
782 case TemplateDeductionResult::NonDependentConversionFailure:
783 case TemplateDeductionResult::AlreadyDiagnosed:
784 llvm_unreachable("not a deduction failure");
785 }
786
787 return Result;
788}
789
790void DeductionFailureInfo::Destroy() {
791 switch (static_cast<TemplateDeductionResult>(Result)) {
792 case TemplateDeductionResult::Success:
793 case TemplateDeductionResult::Invalid:
794 case TemplateDeductionResult::InstantiationDepth:
795 case TemplateDeductionResult::Incomplete:
796 case TemplateDeductionResult::TooManyArguments:
797 case TemplateDeductionResult::TooFewArguments:
798 case TemplateDeductionResult::InvalidExplicitArguments:
799 case TemplateDeductionResult::CUDATargetMismatch:
800 case TemplateDeductionResult::NonDependentConversionFailure:
801 break;
802
803 case TemplateDeductionResult::IncompletePack:
804 case TemplateDeductionResult::Inconsistent:
805 case TemplateDeductionResult::Underqualified:
806 case TemplateDeductionResult::DeducedMismatch:
807 case TemplateDeductionResult::DeducedMismatchNested:
808 case TemplateDeductionResult::NonDeducedMismatch:
809 // FIXME: Destroy the data?
810 Data = nullptr;
811 break;
812
813 case TemplateDeductionResult::SubstitutionFailure:
814 // FIXME: Destroy the template argument list?
815 Data = nullptr;
816 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
817 Diag->~PartialDiagnosticAt();
818 HasDiagnostic = false;
819 }
820 break;
821
822 case TemplateDeductionResult::ConstraintsNotSatisfied:
823 // FIXME: Destroy the template argument list?
824 Data = nullptr;
825 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
826 Diag->~PartialDiagnosticAt();
827 HasDiagnostic = false;
828 }
829 break;
830
831 // Unhandled
832 case TemplateDeductionResult::MiscellaneousDeductionFailure:
833 case TemplateDeductionResult::AlreadyDiagnosed:
834 break;
835 }
836}
837
838PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
839 if (HasDiagnostic)
840 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
841 return nullptr;
842}
843
844TemplateParameter DeductionFailureInfo::getTemplateParameter() {
845 switch (static_cast<TemplateDeductionResult>(Result)) {
846 case TemplateDeductionResult::Success:
847 case TemplateDeductionResult::Invalid:
848 case TemplateDeductionResult::InstantiationDepth:
849 case TemplateDeductionResult::TooManyArguments:
850 case TemplateDeductionResult::TooFewArguments:
851 case TemplateDeductionResult::SubstitutionFailure:
852 case TemplateDeductionResult::DeducedMismatch:
853 case TemplateDeductionResult::DeducedMismatchNested:
854 case TemplateDeductionResult::NonDeducedMismatch:
855 case TemplateDeductionResult::CUDATargetMismatch:
856 case TemplateDeductionResult::NonDependentConversionFailure:
857 case TemplateDeductionResult::ConstraintsNotSatisfied:
858 return TemplateParameter();
859
860 case TemplateDeductionResult::Incomplete:
861 case TemplateDeductionResult::InvalidExplicitArguments:
862 return TemplateParameter::getFromOpaqueValue(VP: Data);
863
864 case TemplateDeductionResult::IncompletePack:
865 case TemplateDeductionResult::Inconsistent:
866 case TemplateDeductionResult::Underqualified:
867 return static_cast<DFIParamWithArguments*>(Data)->Param;
868
869 // Unhandled
870 case TemplateDeductionResult::MiscellaneousDeductionFailure:
871 case TemplateDeductionResult::AlreadyDiagnosed:
872 break;
873 }
874
875 return TemplateParameter();
876}
877
878TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
879 switch (static_cast<TemplateDeductionResult>(Result)) {
880 case TemplateDeductionResult::Success:
881 case TemplateDeductionResult::Invalid:
882 case TemplateDeductionResult::InstantiationDepth:
883 case TemplateDeductionResult::TooManyArguments:
884 case TemplateDeductionResult::TooFewArguments:
885 case TemplateDeductionResult::Incomplete:
886 case TemplateDeductionResult::IncompletePack:
887 case TemplateDeductionResult::InvalidExplicitArguments:
888 case TemplateDeductionResult::Inconsistent:
889 case TemplateDeductionResult::Underqualified:
890 case TemplateDeductionResult::NonDeducedMismatch:
891 case TemplateDeductionResult::CUDATargetMismatch:
892 case TemplateDeductionResult::NonDependentConversionFailure:
893 return nullptr;
894
895 case TemplateDeductionResult::DeducedMismatch:
896 case TemplateDeductionResult::DeducedMismatchNested:
897 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
898
899 case TemplateDeductionResult::SubstitutionFailure:
900 return static_cast<TemplateArgumentList*>(Data);
901
902 case TemplateDeductionResult::ConstraintsNotSatisfied:
903 return static_cast<CNSInfo*>(Data)->TemplateArgs;
904
905 // Unhandled
906 case TemplateDeductionResult::MiscellaneousDeductionFailure:
907 case TemplateDeductionResult::AlreadyDiagnosed:
908 break;
909 }
910
911 return nullptr;
912}
913
914const TemplateArgument *DeductionFailureInfo::getFirstArg() {
915 switch (static_cast<TemplateDeductionResult>(Result)) {
916 case TemplateDeductionResult::Success:
917 case TemplateDeductionResult::Invalid:
918 case TemplateDeductionResult::InstantiationDepth:
919 case TemplateDeductionResult::Incomplete:
920 case TemplateDeductionResult::TooManyArguments:
921 case TemplateDeductionResult::TooFewArguments:
922 case TemplateDeductionResult::InvalidExplicitArguments:
923 case TemplateDeductionResult::SubstitutionFailure:
924 case TemplateDeductionResult::CUDATargetMismatch:
925 case TemplateDeductionResult::NonDependentConversionFailure:
926 case TemplateDeductionResult::ConstraintsNotSatisfied:
927 return nullptr;
928
929 case TemplateDeductionResult::IncompletePack:
930 case TemplateDeductionResult::Inconsistent:
931 case TemplateDeductionResult::Underqualified:
932 case TemplateDeductionResult::DeducedMismatch:
933 case TemplateDeductionResult::DeducedMismatchNested:
934 case TemplateDeductionResult::NonDeducedMismatch:
935 return &static_cast<DFIArguments*>(Data)->FirstArg;
936
937 // Unhandled
938 case TemplateDeductionResult::MiscellaneousDeductionFailure:
939 case TemplateDeductionResult::AlreadyDiagnosed:
940 break;
941 }
942
943 return nullptr;
944}
945
946const TemplateArgument *DeductionFailureInfo::getSecondArg() {
947 switch (static_cast<TemplateDeductionResult>(Result)) {
948 case TemplateDeductionResult::Success:
949 case TemplateDeductionResult::Invalid:
950 case TemplateDeductionResult::InstantiationDepth:
951 case TemplateDeductionResult::Incomplete:
952 case TemplateDeductionResult::IncompletePack:
953 case TemplateDeductionResult::TooManyArguments:
954 case TemplateDeductionResult::TooFewArguments:
955 case TemplateDeductionResult::InvalidExplicitArguments:
956 case TemplateDeductionResult::SubstitutionFailure:
957 case TemplateDeductionResult::CUDATargetMismatch:
958 case TemplateDeductionResult::NonDependentConversionFailure:
959 case TemplateDeductionResult::ConstraintsNotSatisfied:
960 return nullptr;
961
962 case TemplateDeductionResult::Inconsistent:
963 case TemplateDeductionResult::Underqualified:
964 case TemplateDeductionResult::DeducedMismatch:
965 case TemplateDeductionResult::DeducedMismatchNested:
966 case TemplateDeductionResult::NonDeducedMismatch:
967 return &static_cast<DFIArguments*>(Data)->SecondArg;
968
969 // Unhandled
970 case TemplateDeductionResult::MiscellaneousDeductionFailure:
971 case TemplateDeductionResult::AlreadyDiagnosed:
972 break;
973 }
974
975 return nullptr;
976}
977
978std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
979 switch (static_cast<TemplateDeductionResult>(Result)) {
980 case TemplateDeductionResult::DeducedMismatch:
981 case TemplateDeductionResult::DeducedMismatchNested:
982 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
983
984 default:
985 return std::nullopt;
986 }
987}
988
989static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
990 const FunctionDecl *Y) {
991 if (!X || !Y)
992 return false;
993 if (X->getNumParams() != Y->getNumParams())
994 return false;
995 // FIXME: when do rewritten comparison operators
996 // with explicit object parameters correspond?
997 // https://cplusplus.github.io/CWG/issues/2797.html
998 for (unsigned I = 0; I < X->getNumParams(); ++I)
999 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1000 T2: Y->getParamDecl(i: I)->getType()))
1001 return false;
1002 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1003 auto *FTY = Y->getDescribedFunctionTemplate();
1004 if (!FTY)
1005 return false;
1006 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1007 Y: FTY->getTemplateParameters()))
1008 return false;
1009 }
1010 return true;
1011}
1012
1013static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1014 Expr *FirstOperand, FunctionDecl *EqFD) {
1015 assert(EqFD->getOverloadedOperator() ==
1016 OverloadedOperatorKind::OO_EqualEqual);
1017 // C++2a [over.match.oper]p4:
1018 // A non-template function or function template F named operator== is a
1019 // rewrite target with first operand o unless a search for the name operator!=
1020 // in the scope S from the instantiation context of the operator expression
1021 // finds a function or function template that would correspond
1022 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1023 // scope of the class type of o if F is a class member, and the namespace
1024 // scope of which F is a member otherwise. A function template specialization
1025 // named operator== is a rewrite target if its function template is a rewrite
1026 // target.
1027 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1028 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1029 if (isa<CXXMethodDecl>(Val: EqFD)) {
1030 // If F is a class member, search scope is class type of first operand.
1031 QualType RHS = FirstOperand->getType();
1032 auto *RHSRec = RHS->getAs<RecordType>();
1033 if (!RHSRec)
1034 return true;
1035 LookupResult Members(S, NotEqOp, OpLoc,
1036 Sema::LookupNameKind::LookupMemberName);
1037 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec->getDecl());
1038 Members.suppressAccessDiagnostics();
1039 for (NamedDecl *Op : Members)
1040 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1041 return false;
1042 return true;
1043 }
1044 // Otherwise the search scope is the namespace scope of which F is a member.
1045 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1046 auto *NotEqFD = Op->getAsFunction();
1047 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1048 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1049 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1050 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1051 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1052 return false;
1053 }
1054 return true;
1055}
1056
1057bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1058 OverloadedOperatorKind Op) {
1059 if (!AllowRewrittenCandidates)
1060 return false;
1061 return Op == OO_EqualEqual || Op == OO_Spaceship;
1062}
1063
1064bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1065 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1066 auto Op = FD->getOverloadedOperator();
1067 if (!allowsReversed(Op))
1068 return false;
1069 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1070 assert(OriginalArgs.size() == 2);
1071 if (!shouldAddReversedEqEq(
1072 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1073 return false;
1074 }
1075 // Don't bother adding a reversed candidate that can never be a better
1076 // match than the non-reversed version.
1077 return FD->getNumNonObjectParams() != 2 ||
1078 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1079 T2: FD->getParamDecl(i: 1)->getType()) ||
1080 FD->hasAttr<EnableIfAttr>();
1081}
1082
1083void OverloadCandidateSet::destroyCandidates() {
1084 for (iterator i = begin(), e = end(); i != e; ++i) {
1085 for (auto &C : i->Conversions)
1086 C.~ImplicitConversionSequence();
1087 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1088 i->DeductionFailure.Destroy();
1089 }
1090}
1091
1092void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1093 destroyCandidates();
1094 SlabAllocator.Reset();
1095 NumInlineBytesUsed = 0;
1096 Candidates.clear();
1097 Functions.clear();
1098 Kind = CSK;
1099}
1100
1101namespace {
1102 class UnbridgedCastsSet {
1103 struct Entry {
1104 Expr **Addr;
1105 Expr *Saved;
1106 };
1107 SmallVector<Entry, 2> Entries;
1108
1109 public:
1110 void save(Sema &S, Expr *&E) {
1111 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1112 Entry entry = { .Addr: &E, .Saved: E };
1113 Entries.push_back(Elt: entry);
1114 E = S.ObjC().stripARCUnbridgedCast(e: E);
1115 }
1116
1117 void restore() {
1118 for (SmallVectorImpl<Entry>::iterator
1119 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1120 *i->Addr = i->Saved;
1121 }
1122 };
1123}
1124
1125/// checkPlaceholderForOverload - Do any interesting placeholder-like
1126/// preprocessing on the given expression.
1127///
1128/// \param unbridgedCasts a collection to which to add unbridged casts;
1129/// without this, they will be immediately diagnosed as errors
1130///
1131/// Return true on unrecoverable error.
1132static bool
1133checkPlaceholderForOverload(Sema &S, Expr *&E,
1134 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1135 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1136 // We can't handle overloaded expressions here because overload
1137 // resolution might reasonably tweak them.
1138 if (placeholder->getKind() == BuiltinType::Overload) return false;
1139
1140 // If the context potentially accepts unbridged ARC casts, strip
1141 // the unbridged cast and add it to the collection for later restoration.
1142 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1143 unbridgedCasts) {
1144 unbridgedCasts->save(S, E);
1145 return false;
1146 }
1147
1148 // Go ahead and check everything else.
1149 ExprResult result = S.CheckPlaceholderExpr(E);
1150 if (result.isInvalid())
1151 return true;
1152
1153 E = result.get();
1154 return false;
1155 }
1156
1157 // Nothing to do.
1158 return false;
1159}
1160
1161/// checkArgPlaceholdersForOverload - Check a set of call operands for
1162/// placeholders.
1163static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1164 UnbridgedCastsSet &unbridged) {
1165 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1166 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1167 return true;
1168
1169 return false;
1170}
1171
1172Sema::OverloadKind
1173Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1174 NamedDecl *&Match, bool NewIsUsingDecl) {
1175 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1176 I != E; ++I) {
1177 NamedDecl *OldD = *I;
1178
1179 bool OldIsUsingDecl = false;
1180 if (isa<UsingShadowDecl>(Val: OldD)) {
1181 OldIsUsingDecl = true;
1182
1183 // We can always introduce two using declarations into the same
1184 // context, even if they have identical signatures.
1185 if (NewIsUsingDecl) continue;
1186
1187 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1188 }
1189
1190 // A using-declaration does not conflict with another declaration
1191 // if one of them is hidden.
1192 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1193 continue;
1194
1195 // If either declaration was introduced by a using declaration,
1196 // we'll need to use slightly different rules for matching.
1197 // Essentially, these rules are the normal rules, except that
1198 // function templates hide function templates with different
1199 // return types or template parameter lists.
1200 bool UseMemberUsingDeclRules =
1201 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1202 !New->getFriendObjectKind();
1203
1204 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1205 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1206 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1207 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1208 continue;
1209 }
1210
1211 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1212 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1213 continue;
1214
1215 Match = *I;
1216 return Ovl_Match;
1217 }
1218
1219 // Builtins that have custom typechecking or have a reference should
1220 // not be overloadable or redeclarable.
1221 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1222 Match = *I;
1223 return Ovl_NonFunction;
1224 }
1225 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1226 // We can overload with these, which can show up when doing
1227 // redeclaration checks for UsingDecls.
1228 assert(Old.getLookupKind() == LookupUsingDeclName);
1229 } else if (isa<TagDecl>(Val: OldD)) {
1230 // We can always overload with tags by hiding them.
1231 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1232 // Optimistically assume that an unresolved using decl will
1233 // overload; if it doesn't, we'll have to diagnose during
1234 // template instantiation.
1235 //
1236 // Exception: if the scope is dependent and this is not a class
1237 // member, the using declaration can only introduce an enumerator.
1238 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1239 Match = *I;
1240 return Ovl_NonFunction;
1241 }
1242 } else {
1243 // (C++ 13p1):
1244 // Only function declarations can be overloaded; object and type
1245 // declarations cannot be overloaded.
1246 Match = *I;
1247 return Ovl_NonFunction;
1248 }
1249 }
1250
1251 // C++ [temp.friend]p1:
1252 // For a friend function declaration that is not a template declaration:
1253 // -- if the name of the friend is a qualified or unqualified template-id,
1254 // [...], otherwise
1255 // -- if the name of the friend is a qualified-id and a matching
1256 // non-template function is found in the specified class or namespace,
1257 // the friend declaration refers to that function, otherwise,
1258 // -- if the name of the friend is a qualified-id and a matching function
1259 // template is found in the specified class or namespace, the friend
1260 // declaration refers to the deduced specialization of that function
1261 // template, otherwise
1262 // -- the name shall be an unqualified-id [...]
1263 // If we get here for a qualified friend declaration, we've just reached the
1264 // third bullet. If the type of the friend is dependent, skip this lookup
1265 // until instantiation.
1266 if (New->getFriendObjectKind() && New->getQualifier() &&
1267 !New->getDescribedFunctionTemplate() &&
1268 !New->getDependentSpecializationInfo() &&
1269 !New->getType()->isDependentType()) {
1270 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1271 TemplateSpecResult.addAllDecls(Other: Old);
1272 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1273 /*QualifiedFriend*/true)) {
1274 New->setInvalidDecl();
1275 return Ovl_Overload;
1276 }
1277
1278 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1279 return Ovl_Match;
1280 }
1281
1282 return Ovl_Overload;
1283}
1284
1285static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1286 FunctionDecl *Old,
1287 bool UseMemberUsingDeclRules,
1288 bool ConsiderCudaAttrs,
1289 bool UseOverrideRules = false) {
1290 // C++ [basic.start.main]p2: This function shall not be overloaded.
1291 if (New->isMain())
1292 return false;
1293
1294 // MSVCRT user defined entry points cannot be overloaded.
1295 if (New->isMSVCRTEntryPoint())
1296 return false;
1297
1298 NamedDecl *OldDecl = Old;
1299 NamedDecl *NewDecl = New;
1300 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1301 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1302
1303 // C++ [temp.fct]p2:
1304 // A function template can be overloaded with other function templates
1305 // and with normal (non-template) functions.
1306 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1307 return true;
1308
1309 // Is the function New an overload of the function Old?
1310 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1311 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1312
1313 // Compare the signatures (C++ 1.3.10) of the two functions to
1314 // determine whether they are overloads. If we find any mismatch
1315 // in the signature, they are overloads.
1316
1317 // If either of these functions is a K&R-style function (no
1318 // prototype), then we consider them to have matching signatures.
1319 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1320 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1321 return false;
1322
1323 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1324 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1325
1326 // The signature of a function includes the types of its
1327 // parameters (C++ 1.3.10), which includes the presence or absence
1328 // of the ellipsis; see C++ DR 357).
1329 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1330 return true;
1331
1332 // For member-like friends, the enclosing class is part of the signature.
1333 if ((New->isMemberLikeConstrainedFriend() ||
1334 Old->isMemberLikeConstrainedFriend()) &&
1335 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1336 return true;
1337
1338 // Compare the parameter lists.
1339 // This can only be done once we have establish that friend functions
1340 // inhabit the same context, otherwise we might tried to instantiate
1341 // references to non-instantiated entities during constraint substitution.
1342 // GH78101.
1343 if (NewTemplate) {
1344 OldDecl = OldTemplate;
1345 NewDecl = NewTemplate;
1346 // C++ [temp.over.link]p4:
1347 // The signature of a function template consists of its function
1348 // signature, its return type and its template parameter list. The names
1349 // of the template parameters are significant only for establishing the
1350 // relationship between the template parameters and the rest of the
1351 // signature.
1352 //
1353 // We check the return type and template parameter lists for function
1354 // templates first; the remaining checks follow.
1355 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1356 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1357 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1358 bool SameReturnType = SemaRef.Context.hasSameType(
1359 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1360 // FIXME(GH58571): Match template parameter list even for non-constrained
1361 // template heads. This currently ensures that the code prior to C++20 is
1362 // not newly broken.
1363 bool ConstraintsInTemplateHead =
1364 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1365 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1366 // C++ [namespace.udecl]p11:
1367 // The set of declarations named by a using-declarator that inhabits a
1368 // class C does not include member functions and member function
1369 // templates of a base class that "correspond" to (and thus would
1370 // conflict with) a declaration of a function or function template in
1371 // C.
1372 // Comparing return types is not required for the "correspond" check to
1373 // decide whether a member introduced by a shadow declaration is hidden.
1374 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1375 !SameTemplateParameterList)
1376 return true;
1377 if (!UseMemberUsingDeclRules &&
1378 (!SameTemplateParameterList || !SameReturnType))
1379 return true;
1380 }
1381
1382 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1383 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1384
1385 int OldParamsOffset = 0;
1386 int NewParamsOffset = 0;
1387
1388 // When determining if a method is an overload from a base class, act as if
1389 // the implicit object parameter are of the same type.
1390
1391 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1392 if (M->isExplicitObjectMemberFunction())
1393 return Q;
1394
1395 // We do not allow overloading based off of '__restrict'.
1396 Q.removeRestrict();
1397
1398 // We may not have applied the implicit const for a constexpr member
1399 // function yet (because we haven't yet resolved whether this is a static
1400 // or non-static member function). Add it now, on the assumption that this
1401 // is a redeclaration of OldMethod.
1402 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1403 (M->isConstexpr() || M->isConsteval()) &&
1404 !isa<CXXConstructorDecl>(Val: NewMethod))
1405 Q.addConst();
1406 return Q;
1407 };
1408
1409 auto CompareType = [&](QualType Base, QualType D) {
1410 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1411 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1412
1413 auto DS = D.getNonReferenceType().getCanonicalType().split();
1414 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1415
1416 if (BS.Quals != DS.Quals)
1417 return false;
1418
1419 if (OldMethod->isImplicitObjectMemberFunction() &&
1420 OldMethod->getParent() != NewMethod->getParent()) {
1421 QualType ParentType =
1422 SemaRef.Context.getTypeDeclType(Decl: OldMethod->getParent())
1423 .getCanonicalType();
1424 if (ParentType.getTypePtr() != BS.Ty)
1425 return false;
1426 BS.Ty = DS.Ty;
1427 }
1428
1429 // FIXME: should we ignore some type attributes here?
1430 if (BS.Ty != DS.Ty)
1431 return false;
1432
1433 if (Base->isLValueReferenceType())
1434 return D->isLValueReferenceType();
1435 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1436 };
1437
1438 // If the function is a class member, its signature includes the
1439 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1440 auto DiagnoseInconsistentRefQualifiers = [&]() {
1441 if (SemaRef.LangOpts.CPlusPlus23)
1442 return false;
1443 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1444 return false;
1445 if (OldMethod->isExplicitObjectMemberFunction() ||
1446 NewMethod->isExplicitObjectMemberFunction())
1447 return false;
1448 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1449 NewMethod->getRefQualifier() == RQ_None)) {
1450 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1451 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1452 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1453 return true;
1454 }
1455 return false;
1456 };
1457
1458 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1459 OldParamsOffset++;
1460 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1461 NewParamsOffset++;
1462
1463 if (OldType->getNumParams() - OldParamsOffset !=
1464 NewType->getNumParams() - NewParamsOffset ||
1465 !SemaRef.FunctionParamTypesAreEqual(
1466 Old: {OldType->param_type_begin() + OldParamsOffset,
1467 OldType->param_type_end()},
1468 New: {NewType->param_type_begin() + NewParamsOffset,
1469 NewType->param_type_end()},
1470 ArgPos: nullptr)) {
1471 return true;
1472 }
1473
1474 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1475 !NewMethod->isStatic()) {
1476 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1477 const CXXMethodDecl *New) {
1478 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1479 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1480
1481 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1482 return F->getRefQualifier() == RQ_None &&
1483 !F->isExplicitObjectMemberFunction();
1484 };
1485
1486 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1487 CompareType(OldObjectType.getNonReferenceType(),
1488 NewObjectType.getNonReferenceType()))
1489 return true;
1490 return CompareType(OldObjectType, NewObjectType);
1491 }(OldMethod, NewMethod);
1492
1493 if (!HaveCorrespondingObjectParameters) {
1494 if (DiagnoseInconsistentRefQualifiers())
1495 return true;
1496 // CWG2554
1497 // and, if at least one is an explicit object member function, ignoring
1498 // object parameters
1499 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1500 !OldMethod->isExplicitObjectMemberFunction()))
1501 return true;
1502 }
1503 }
1504
1505 if (!UseOverrideRules &&
1506 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1507 Expr *NewRC = New->getTrailingRequiresClause(),
1508 *OldRC = Old->getTrailingRequiresClause();
1509 if ((NewRC != nullptr) != (OldRC != nullptr))
1510 return true;
1511 if (NewRC &&
1512 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC, New: NewDecl, NewConstr: NewRC))
1513 return true;
1514 }
1515
1516 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1517 NewMethod->isImplicitObjectMemberFunction()) {
1518 if (DiagnoseInconsistentRefQualifiers())
1519 return true;
1520 }
1521
1522 // Though pass_object_size is placed on parameters and takes an argument, we
1523 // consider it to be a function-level modifier for the sake of function
1524 // identity. Either the function has one or more parameters with
1525 // pass_object_size or it doesn't.
1526 if (functionHasPassObjectSizeParams(FD: New) !=
1527 functionHasPassObjectSizeParams(FD: Old))
1528 return true;
1529
1530 // enable_if attributes are an order-sensitive part of the signature.
1531 for (specific_attr_iterator<EnableIfAttr>
1532 NewI = New->specific_attr_begin<EnableIfAttr>(),
1533 NewE = New->specific_attr_end<EnableIfAttr>(),
1534 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1535 OldE = Old->specific_attr_end<EnableIfAttr>();
1536 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1537 if (NewI == NewE || OldI == OldE)
1538 return true;
1539 llvm::FoldingSetNodeID NewID, OldID;
1540 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1541 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1542 if (NewID != OldID)
1543 return true;
1544 }
1545
1546 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1547 // Don't allow overloading of destructors. (In theory we could, but it
1548 // would be a giant change to clang.)
1549 if (!isa<CXXDestructorDecl>(Val: New)) {
1550 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1551 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1552 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1553 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1554 "Unexpected invalid target.");
1555
1556 // Allow overloading of functions with same signature and different CUDA
1557 // target attributes.
1558 if (NewTarget != OldTarget)
1559 return true;
1560 }
1561 }
1562 }
1563
1564 // The signatures match; this is not an overload.
1565 return false;
1566}
1567
1568bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1569 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1570 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1571 ConsiderCudaAttrs);
1572}
1573
1574bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1575 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1576 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1577 /*UseMemberUsingDeclRules=*/false,
1578 /*ConsiderCudaAttrs=*/true,
1579 /*UseOverrideRules=*/true);
1580}
1581
1582/// Tries a user-defined conversion from From to ToType.
1583///
1584/// Produces an implicit conversion sequence for when a standard conversion
1585/// is not an option. See TryImplicitConversion for more information.
1586static ImplicitConversionSequence
1587TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1588 bool SuppressUserConversions,
1589 AllowedExplicit AllowExplicit,
1590 bool InOverloadResolution,
1591 bool CStyle,
1592 bool AllowObjCWritebackConversion,
1593 bool AllowObjCConversionOnExplicit) {
1594 ImplicitConversionSequence ICS;
1595
1596 if (SuppressUserConversions) {
1597 // We're not in the case above, so there is no conversion that
1598 // we can perform.
1599 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1600 return ICS;
1601 }
1602
1603 // Attempt user-defined conversion.
1604 OverloadCandidateSet Conversions(From->getExprLoc(),
1605 OverloadCandidateSet::CSK_Normal);
1606 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1607 Conversions, AllowExplicit,
1608 AllowObjCConversionOnExplicit)) {
1609 case OR_Success:
1610 case OR_Deleted:
1611 ICS.setUserDefined();
1612 // C++ [over.ics.user]p4:
1613 // A conversion of an expression of class type to the same class
1614 // type is given Exact Match rank, and a conversion of an
1615 // expression of class type to a base class of that type is
1616 // given Conversion rank, in spite of the fact that a copy
1617 // constructor (i.e., a user-defined conversion function) is
1618 // called for those cases.
1619 if (CXXConstructorDecl *Constructor
1620 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1621 QualType FromCanon
1622 = S.Context.getCanonicalType(T: From->getType().getUnqualifiedType());
1623 QualType ToCanon
1624 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1625 if (Constructor->isCopyConstructor() &&
1626 (FromCanon == ToCanon ||
1627 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromCanon, Base: ToCanon))) {
1628 // Turn this into a "standard" conversion sequence, so that it
1629 // gets ranked with standard conversion sequences.
1630 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1631 ICS.setStandard();
1632 ICS.Standard.setAsIdentityConversion();
1633 ICS.Standard.setFromType(From->getType());
1634 ICS.Standard.setAllToTypes(ToType);
1635 ICS.Standard.CopyConstructor = Constructor;
1636 ICS.Standard.FoundCopyConstructor = Found;
1637 if (ToCanon != FromCanon)
1638 ICS.Standard.Second = ICK_Derived_To_Base;
1639 }
1640 }
1641 break;
1642
1643 case OR_Ambiguous:
1644 ICS.setAmbiguous();
1645 ICS.Ambiguous.setFromType(From->getType());
1646 ICS.Ambiguous.setToType(ToType);
1647 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1648 Cand != Conversions.end(); ++Cand)
1649 if (Cand->Best)
1650 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1651 break;
1652
1653 // Fall through.
1654 case OR_No_Viable_Function:
1655 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1656 break;
1657 }
1658
1659 return ICS;
1660}
1661
1662/// TryImplicitConversion - Attempt to perform an implicit conversion
1663/// from the given expression (Expr) to the given type (ToType). This
1664/// function returns an implicit conversion sequence that can be used
1665/// to perform the initialization. Given
1666///
1667/// void f(float f);
1668/// void g(int i) { f(i); }
1669///
1670/// this routine would produce an implicit conversion sequence to
1671/// describe the initialization of f from i, which will be a standard
1672/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1673/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1674//
1675/// Note that this routine only determines how the conversion can be
1676/// performed; it does not actually perform the conversion. As such,
1677/// it will not produce any diagnostics if no conversion is available,
1678/// but will instead return an implicit conversion sequence of kind
1679/// "BadConversion".
1680///
1681/// If @p SuppressUserConversions, then user-defined conversions are
1682/// not permitted.
1683/// If @p AllowExplicit, then explicit user-defined conversions are
1684/// permitted.
1685///
1686/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1687/// writeback conversion, which allows __autoreleasing id* parameters to
1688/// be initialized with __strong id* or __weak id* arguments.
1689static ImplicitConversionSequence
1690TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1691 bool SuppressUserConversions,
1692 AllowedExplicit AllowExplicit,
1693 bool InOverloadResolution,
1694 bool CStyle,
1695 bool AllowObjCWritebackConversion,
1696 bool AllowObjCConversionOnExplicit) {
1697 ImplicitConversionSequence ICS;
1698 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1699 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1700 ICS.setStandard();
1701 return ICS;
1702 }
1703
1704 if (!S.getLangOpts().CPlusPlus) {
1705 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1706 return ICS;
1707 }
1708
1709 // C++ [over.ics.user]p4:
1710 // A conversion of an expression of class type to the same class
1711 // type is given Exact Match rank, and a conversion of an
1712 // expression of class type to a base class of that type is
1713 // given Conversion rank, in spite of the fact that a copy/move
1714 // constructor (i.e., a user-defined conversion function) is
1715 // called for those cases.
1716 QualType FromType = From->getType();
1717 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1718 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1719 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1720 ICS.setStandard();
1721 ICS.Standard.setAsIdentityConversion();
1722 ICS.Standard.setFromType(FromType);
1723 ICS.Standard.setAllToTypes(ToType);
1724
1725 // We don't actually check at this point whether there is a valid
1726 // copy/move constructor, since overloading just assumes that it
1727 // exists. When we actually perform initialization, we'll find the
1728 // appropriate constructor to copy the returned object, if needed.
1729 ICS.Standard.CopyConstructor = nullptr;
1730
1731 // Determine whether this is considered a derived-to-base conversion.
1732 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1733 ICS.Standard.Second = ICK_Derived_To_Base;
1734
1735 return ICS;
1736 }
1737
1738 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1739 AllowExplicit, InOverloadResolution, CStyle,
1740 AllowObjCWritebackConversion,
1741 AllowObjCConversionOnExplicit);
1742}
1743
1744ImplicitConversionSequence
1745Sema::TryImplicitConversion(Expr *From, QualType ToType,
1746 bool SuppressUserConversions,
1747 AllowedExplicit AllowExplicit,
1748 bool InOverloadResolution,
1749 bool CStyle,
1750 bool AllowObjCWritebackConversion) {
1751 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1752 AllowExplicit, InOverloadResolution, CStyle,
1753 AllowObjCWritebackConversion,
1754 /*AllowObjCConversionOnExplicit=*/false);
1755}
1756
1757ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1758 AssignmentAction Action,
1759 bool AllowExplicit) {
1760 if (checkPlaceholderForOverload(S&: *this, E&: From))
1761 return ExprError();
1762
1763 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1764 bool AllowObjCWritebackConversion
1765 = getLangOpts().ObjCAutoRefCount &&
1766 (Action == AA_Passing || Action == AA_Sending);
1767 if (getLangOpts().ObjC)
1768 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1769 SrcType: From->getType(), SrcExpr&: From);
1770 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1771 S&: *this, From, ToType,
1772 /*SuppressUserConversions=*/false,
1773 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1774 /*InOverloadResolution=*/false,
1775 /*CStyle=*/false, AllowObjCWritebackConversion,
1776 /*AllowObjCConversionOnExplicit=*/false);
1777 return PerformImplicitConversion(From, ToType, ICS, Action);
1778}
1779
1780bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1781 QualType &ResultTy) {
1782 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1783 return false;
1784
1785 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1786 // or F(t noexcept) -> F(t)
1787 // where F adds one of the following at most once:
1788 // - a pointer
1789 // - a member pointer
1790 // - a block pointer
1791 // Changes here need matching changes in FindCompositePointerType.
1792 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1793 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1794 Type::TypeClass TyClass = CanTo->getTypeClass();
1795 if (TyClass != CanFrom->getTypeClass()) return false;
1796 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1797 if (TyClass == Type::Pointer) {
1798 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1799 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1800 } else if (TyClass == Type::BlockPointer) {
1801 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1802 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1803 } else if (TyClass == Type::MemberPointer) {
1804 auto ToMPT = CanTo.castAs<MemberPointerType>();
1805 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1806 // A function pointer conversion cannot change the class of the function.
1807 if (ToMPT->getClass() != FromMPT->getClass())
1808 return false;
1809 CanTo = ToMPT->getPointeeType();
1810 CanFrom = FromMPT->getPointeeType();
1811 } else {
1812 return false;
1813 }
1814
1815 TyClass = CanTo->getTypeClass();
1816 if (TyClass != CanFrom->getTypeClass()) return false;
1817 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1818 return false;
1819 }
1820
1821 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1822 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1823
1824 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1825 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1826
1827 bool Changed = false;
1828
1829 // Drop 'noreturn' if not present in target type.
1830 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1831 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1832 Changed = true;
1833 }
1834
1835 // Drop 'noexcept' if not present in target type.
1836 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn)) {
1837 const auto *ToFPT = cast<FunctionProtoType>(Val: ToFn);
1838 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1839 FromFn = cast<FunctionType>(
1840 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
1841 ESI: EST_None)
1842 .getTypePtr());
1843 Changed = true;
1844 }
1845
1846 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1847 // only if the ExtParameterInfo lists of the two function prototypes can be
1848 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1849 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1850 bool CanUseToFPT, CanUseFromFPT;
1851 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
1852 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
1853 CanUseToFPT && !CanUseFromFPT) {
1854 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1855 ExtInfo.ExtParameterInfos =
1856 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1857 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
1858 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
1859 FromFn = QT->getAs<FunctionType>();
1860 Changed = true;
1861 }
1862
1863 // For C, when called from checkPointerTypesForAssignment,
1864 // we need to not alter FromFn, or else even an innocuous cast
1865 // like dropping effects will fail. In C++ however we do want to
1866 // alter FromFn (because of the way PerformImplicitConversion works).
1867 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1868 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
1869
1870 // Transparently add/drop effects; here we are concerned with
1871 // language rules/canonicalization. Adding/dropping effects is a warning.
1872 const auto FromFX = FromFPT->getFunctionEffects();
1873 const auto ToFX = ToFPT->getFunctionEffects();
1874 if (FromFX != ToFX) {
1875 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1876 ExtInfo.FunctionEffects = ToFX;
1877 QualType QT = Context.getFunctionType(
1878 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
1879 FromFn = QT->getAs<FunctionType>();
1880 Changed = true;
1881 }
1882 }
1883 }
1884
1885 if (!Changed)
1886 return false;
1887
1888 assert(QualType(FromFn, 0).isCanonical());
1889 if (QualType(FromFn, 0) != CanTo) return false;
1890
1891 ResultTy = ToType;
1892 return true;
1893}
1894
1895/// Determine whether the conversion from FromType to ToType is a valid
1896/// floating point conversion.
1897///
1898static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1899 QualType ToType) {
1900 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1901 return false;
1902 // FIXME: disable conversions between long double, __ibm128 and __float128
1903 // if their representation is different until there is back end support
1904 // We of course allow this conversion if long double is really double.
1905
1906 // Conversions between bfloat16 and float16 are currently not supported.
1907 if ((FromType->isBFloat16Type() &&
1908 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1909 (ToType->isBFloat16Type() &&
1910 (FromType->isFloat16Type() || FromType->isHalfType())))
1911 return false;
1912
1913 // Conversions between IEEE-quad and IBM-extended semantics are not
1914 // permitted.
1915 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
1916 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
1917 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1918 &ToSem == &llvm::APFloat::IEEEquad()) ||
1919 (&FromSem == &llvm::APFloat::IEEEquad() &&
1920 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1921 return false;
1922 return true;
1923}
1924
1925static bool IsVectorElementConversion(Sema &S, QualType FromType,
1926 QualType ToType,
1927 ImplicitConversionKind &ICK, Expr *From) {
1928 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1929 return true;
1930
1931 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1932 ICK = ICK_Floating_Promotion;
1933 return true;
1934 }
1935
1936 if (IsFloatingPointConversion(S, FromType, ToType)) {
1937 ICK = ICK_Floating_Conversion;
1938 return true;
1939 }
1940
1941 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1942 ICK = ICK_Boolean_Conversion;
1943 return true;
1944 }
1945
1946 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
1947 (FromType->isIntegralOrUnscopedEnumerationType() &&
1948 ToType->isRealFloatingType())) {
1949 ICK = ICK_Floating_Integral;
1950 return true;
1951 }
1952
1953 if (S.IsIntegralPromotion(From, FromType, ToType)) {
1954 ICK = ICK_Integral_Promotion;
1955 return true;
1956 }
1957
1958 if (FromType->isIntegralOrUnscopedEnumerationType() &&
1959 ToType->isIntegralType(Ctx: S.Context)) {
1960 ICK = ICK_Integral_Conversion;
1961 return true;
1962 }
1963
1964 return false;
1965}
1966
1967/// Determine whether the conversion from FromType to ToType is a valid
1968/// vector conversion.
1969///
1970/// \param ICK Will be set to the vector conversion kind, if this is a vector
1971/// conversion.
1972static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1973 ImplicitConversionKind &ICK,
1974 ImplicitConversionKind &ElConv, Expr *From,
1975 bool InOverloadResolution, bool CStyle) {
1976 // We need at least one of these types to be a vector type to have a vector
1977 // conversion.
1978 if (!ToType->isVectorType() && !FromType->isVectorType())
1979 return false;
1980
1981 // Identical types require no conversions.
1982 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1983 return false;
1984
1985 // There are no conversions between extended vector types, only identity.
1986 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
1987 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
1988 // HLSL allows implicit truncation of vector types.
1989 if (S.getLangOpts().HLSL) {
1990 unsigned FromElts = FromExtType->getNumElements();
1991 unsigned ToElts = ToExtType->getNumElements();
1992 if (FromElts < ToElts)
1993 return false;
1994 if (FromElts == ToElts)
1995 ElConv = ICK_Identity;
1996 else
1997 ElConv = ICK_HLSL_Vector_Truncation;
1998
1999 QualType FromElTy = FromExtType->getElementType();
2000 QualType ToElTy = ToExtType->getElementType();
2001 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2002 return true;
2003 return IsVectorElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2004 }
2005 // There are no conversions between extended vector types other than the
2006 // identity conversion.
2007 return false;
2008 }
2009
2010 // Vector splat from any arithmetic type to a vector.
2011 if (FromType->isArithmeticType()) {
2012 if (S.getLangOpts().HLSL) {
2013 ElConv = ICK_HLSL_Vector_Splat;
2014 QualType ToElTy = ToExtType->getElementType();
2015 return IsVectorElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2016 }
2017 ICK = ICK_Vector_Splat;
2018 return true;
2019 }
2020 }
2021
2022 if (ToType->isSVESizelessBuiltinType() ||
2023 FromType->isSVESizelessBuiltinType())
2024 if (S.Context.areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2025 S.Context.areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2026 ICK = ICK_SVE_Vector_Conversion;
2027 return true;
2028 }
2029
2030 if (ToType->isRVVSizelessBuiltinType() ||
2031 FromType->isRVVSizelessBuiltinType())
2032 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2033 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2034 ICK = ICK_RVV_Vector_Conversion;
2035 return true;
2036 }
2037
2038 // We can perform the conversion between vector types in the following cases:
2039 // 1)vector types are equivalent AltiVec and GCC vector types
2040 // 2)lax vector conversions are permitted and the vector types are of the
2041 // same size
2042 // 3)the destination type does not have the ARM MVE strict-polymorphism
2043 // attribute, which inhibits lax vector conversion for overload resolution
2044 // only
2045 if (ToType->isVectorType() && FromType->isVectorType()) {
2046 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2047 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2048 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2049 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2050 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2051 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2052 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2053 !InOverloadResolution && !CStyle) {
2054 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2055 << FromType << ToType;
2056 }
2057 ICK = ICK_Vector_Conversion;
2058 return true;
2059 }
2060 }
2061
2062 return false;
2063}
2064
2065static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2066 bool InOverloadResolution,
2067 StandardConversionSequence &SCS,
2068 bool CStyle);
2069
2070/// IsStandardConversion - Determines whether there is a standard
2071/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2072/// expression From to the type ToType. Standard conversion sequences
2073/// only consider non-class types; for conversions that involve class
2074/// types, use TryImplicitConversion. If a conversion exists, SCS will
2075/// contain the standard conversion sequence required to perform this
2076/// conversion and this routine will return true. Otherwise, this
2077/// routine will return false and the value of SCS is unspecified.
2078static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2079 bool InOverloadResolution,
2080 StandardConversionSequence &SCS,
2081 bool CStyle,
2082 bool AllowObjCWritebackConversion) {
2083 QualType FromType = From->getType();
2084
2085 // Standard conversions (C++ [conv])
2086 SCS.setAsIdentityConversion();
2087 SCS.IncompatibleObjC = false;
2088 SCS.setFromType(FromType);
2089 SCS.CopyConstructor = nullptr;
2090
2091 // There are no standard conversions for class types in C++, so
2092 // abort early. When overloading in C, however, we do permit them.
2093 if (S.getLangOpts().CPlusPlus &&
2094 (FromType->isRecordType() || ToType->isRecordType()))
2095 return false;
2096
2097 // The first conversion can be an lvalue-to-rvalue conversion,
2098 // array-to-pointer conversion, or function-to-pointer conversion
2099 // (C++ 4p1).
2100
2101 if (FromType == S.Context.OverloadTy) {
2102 DeclAccessPair AccessPair;
2103 if (FunctionDecl *Fn
2104 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2105 Found&: AccessPair)) {
2106 // We were able to resolve the address of the overloaded function,
2107 // so we can convert to the type of that function.
2108 FromType = Fn->getType();
2109 SCS.setFromType(FromType);
2110
2111 // we can sometimes resolve &foo<int> regardless of ToType, so check
2112 // if the type matches (identity) or we are converting to bool
2113 if (!S.Context.hasSameUnqualifiedType(
2114 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2115 QualType resultTy;
2116 // if the function type matches except for [[noreturn]], it's ok
2117 if (!S.IsFunctionConversion(FromType,
2118 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), ResultTy&: resultTy))
2119 // otherwise, only a boolean conversion is standard
2120 if (!ToType->isBooleanType())
2121 return false;
2122 }
2123
2124 // Check if the "from" expression is taking the address of an overloaded
2125 // function and recompute the FromType accordingly. Take advantage of the
2126 // fact that non-static member functions *must* have such an address-of
2127 // expression.
2128 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2129 if (Method && !Method->isStatic() &&
2130 !Method->isExplicitObjectMemberFunction()) {
2131 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2132 "Non-unary operator on non-static member address");
2133 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2134 == UO_AddrOf &&
2135 "Non-address-of operator on non-static member address");
2136 const Type *ClassType
2137 = S.Context.getTypeDeclType(Decl: Method->getParent()).getTypePtr();
2138 FromType = S.Context.getMemberPointerType(T: FromType, Cls: ClassType);
2139 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2140 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2141 UO_AddrOf &&
2142 "Non-address-of operator for overloaded function expression");
2143 FromType = S.Context.getPointerType(T: FromType);
2144 }
2145 } else {
2146 return false;
2147 }
2148 }
2149 // Lvalue-to-rvalue conversion (C++11 4.1):
2150 // A glvalue (3.10) of a non-function, non-array type T can
2151 // be converted to a prvalue.
2152 bool argIsLValue = From->isGLValue();
2153 if (argIsLValue && !FromType->canDecayToPointerType() &&
2154 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2155 SCS.First = ICK_Lvalue_To_Rvalue;
2156
2157 // C11 6.3.2.1p2:
2158 // ... if the lvalue has atomic type, the value has the non-atomic version
2159 // of the type of the lvalue ...
2160 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2161 FromType = Atomic->getValueType();
2162
2163 // If T is a non-class type, the type of the rvalue is the
2164 // cv-unqualified version of T. Otherwise, the type of the rvalue
2165 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2166 // just strip the qualifiers because they don't matter.
2167 FromType = FromType.getUnqualifiedType();
2168 } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2169 ToType->isArrayParameterType()) {
2170 // HLSL constant array parameters do not decay, so if the argument is a
2171 // constant array and the parameter is an ArrayParameterType we have special
2172 // handling here.
2173 FromType = S.Context.getArrayParameterType(Ty: FromType);
2174 if (S.Context.getCanonicalType(T: FromType) !=
2175 S.Context.getCanonicalType(T: ToType))
2176 return false;
2177
2178 SCS.First = ICK_HLSL_Array_RValue;
2179 SCS.setAllToTypes(ToType);
2180 return true;
2181 } else if (FromType->isArrayType()) {
2182 // Array-to-pointer conversion (C++ 4.2)
2183 SCS.First = ICK_Array_To_Pointer;
2184
2185 // An lvalue or rvalue of type "array of N T" or "array of unknown
2186 // bound of T" can be converted to an rvalue of type "pointer to
2187 // T" (C++ 4.2p1).
2188 FromType = S.Context.getArrayDecayedType(T: FromType);
2189
2190 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2191 // This conversion is deprecated in C++03 (D.4)
2192 SCS.DeprecatedStringLiteralToCharPtr = true;
2193
2194 // For the purpose of ranking in overload resolution
2195 // (13.3.3.1.1), this conversion is considered an
2196 // array-to-pointer conversion followed by a qualification
2197 // conversion (4.4). (C++ 4.2p2)
2198 SCS.Second = ICK_Identity;
2199 SCS.Third = ICK_Qualification;
2200 SCS.QualificationIncludesObjCLifetime = false;
2201 SCS.setAllToTypes(FromType);
2202 return true;
2203 }
2204 } else if (FromType->isFunctionType() && argIsLValue) {
2205 // Function-to-pointer conversion (C++ 4.3).
2206 SCS.First = ICK_Function_To_Pointer;
2207
2208 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2209 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2210 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2211 return false;
2212
2213 // An lvalue of function type T can be converted to an rvalue of
2214 // type "pointer to T." The result is a pointer to the
2215 // function. (C++ 4.3p1).
2216 FromType = S.Context.getPointerType(T: FromType);
2217 } else {
2218 // We don't require any conversions for the first step.
2219 SCS.First = ICK_Identity;
2220 }
2221 SCS.setToType(Idx: 0, T: FromType);
2222
2223 // The second conversion can be an integral promotion, floating
2224 // point promotion, integral conversion, floating point conversion,
2225 // floating-integral conversion, pointer conversion,
2226 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2227 // For overloading in C, this can also be a "compatible-type"
2228 // conversion.
2229 bool IncompatibleObjC = false;
2230 ImplicitConversionKind SecondICK = ICK_Identity;
2231 ImplicitConversionKind DimensionICK = ICK_Identity;
2232 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2233 // The unqualified versions of the types are the same: there's no
2234 // conversion to do.
2235 SCS.Second = ICK_Identity;
2236 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2237 // Integral promotion (C++ 4.5).
2238 SCS.Second = ICK_Integral_Promotion;
2239 FromType = ToType.getUnqualifiedType();
2240 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2241 // Floating point promotion (C++ 4.6).
2242 SCS.Second = ICK_Floating_Promotion;
2243 FromType = ToType.getUnqualifiedType();
2244 } else if (S.IsComplexPromotion(FromType, ToType)) {
2245 // Complex promotion (Clang extension)
2246 SCS.Second = ICK_Complex_Promotion;
2247 FromType = ToType.getUnqualifiedType();
2248 } else if (ToType->isBooleanType() &&
2249 (FromType->isArithmeticType() ||
2250 FromType->isAnyPointerType() ||
2251 FromType->isBlockPointerType() ||
2252 FromType->isMemberPointerType())) {
2253 // Boolean conversions (C++ 4.12).
2254 SCS.Second = ICK_Boolean_Conversion;
2255 FromType = S.Context.BoolTy;
2256 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2257 ToType->isIntegralType(Ctx: S.Context)) {
2258 // Integral conversions (C++ 4.7).
2259 SCS.Second = ICK_Integral_Conversion;
2260 FromType = ToType.getUnqualifiedType();
2261 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2262 // Complex conversions (C99 6.3.1.6)
2263 SCS.Second = ICK_Complex_Conversion;
2264 FromType = ToType.getUnqualifiedType();
2265 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2266 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2267 // Complex-real conversions (C99 6.3.1.7)
2268 SCS.Second = ICK_Complex_Real;
2269 FromType = ToType.getUnqualifiedType();
2270 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2271 // Floating point conversions (C++ 4.8).
2272 SCS.Second = ICK_Floating_Conversion;
2273 FromType = ToType.getUnqualifiedType();
2274 } else if ((FromType->isRealFloatingType() &&
2275 ToType->isIntegralType(Ctx: S.Context)) ||
2276 (FromType->isIntegralOrUnscopedEnumerationType() &&
2277 ToType->isRealFloatingType())) {
2278
2279 // Floating-integral conversions (C++ 4.9).
2280 SCS.Second = ICK_Floating_Integral;
2281 FromType = ToType.getUnqualifiedType();
2282 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2283 SCS.Second = ICK_Block_Pointer_Conversion;
2284 } else if (AllowObjCWritebackConversion &&
2285 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2286 SCS.Second = ICK_Writeback_Conversion;
2287 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2288 ConvertedType&: FromType, IncompatibleObjC)) {
2289 // Pointer conversions (C++ 4.10).
2290 SCS.Second = ICK_Pointer_Conversion;
2291 SCS.IncompatibleObjC = IncompatibleObjC;
2292 FromType = FromType.getUnqualifiedType();
2293 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2294 InOverloadResolution, ConvertedType&: FromType)) {
2295 // Pointer to member conversions (4.11).
2296 SCS.Second = ICK_Pointer_Member;
2297 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2298 From, InOverloadResolution, CStyle)) {
2299 SCS.Second = SecondICK;
2300 SCS.Dimension = DimensionICK;
2301 FromType = ToType.getUnqualifiedType();
2302 } else if (!S.getLangOpts().CPlusPlus &&
2303 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2304 // Compatible conversions (Clang extension for C function overloading)
2305 SCS.Second = ICK_Compatible_Conversion;
2306 FromType = ToType.getUnqualifiedType();
2307 } else if (IsTransparentUnionStandardConversion(
2308 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2309 SCS.Second = ICK_TransparentUnionConversion;
2310 FromType = ToType;
2311 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2312 CStyle)) {
2313 // tryAtomicConversion has updated the standard conversion sequence
2314 // appropriately.
2315 return true;
2316 } else if (ToType->isEventT() &&
2317 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2318 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2319 SCS.Second = ICK_Zero_Event_Conversion;
2320 FromType = ToType;
2321 } else if (ToType->isQueueT() &&
2322 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2323 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2324 SCS.Second = ICK_Zero_Queue_Conversion;
2325 FromType = ToType;
2326 } else if (ToType->isSamplerT() &&
2327 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2328 SCS.Second = ICK_Compatible_Conversion;
2329 FromType = ToType;
2330 } else if ((ToType->isFixedPointType() &&
2331 FromType->isConvertibleToFixedPointType()) ||
2332 (FromType->isFixedPointType() &&
2333 ToType->isConvertibleToFixedPointType())) {
2334 SCS.Second = ICK_Fixed_Point_Conversion;
2335 FromType = ToType;
2336 } else {
2337 // No second conversion required.
2338 SCS.Second = ICK_Identity;
2339 }
2340 SCS.setToType(Idx: 1, T: FromType);
2341
2342 // The third conversion can be a function pointer conversion or a
2343 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2344 bool ObjCLifetimeConversion;
2345 if (S.IsFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2346 // Function pointer conversions (removing 'noexcept') including removal of
2347 // 'noreturn' (Clang extension).
2348 SCS.Third = ICK_Function_Conversion;
2349 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2350 ObjCLifetimeConversion)) {
2351 SCS.Third = ICK_Qualification;
2352 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2353 FromType = ToType;
2354 } else {
2355 // No conversion required
2356 SCS.Third = ICK_Identity;
2357 }
2358
2359 // C++ [over.best.ics]p6:
2360 // [...] Any difference in top-level cv-qualification is
2361 // subsumed by the initialization itself and does not constitute
2362 // a conversion. [...]
2363 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2364 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2365 if (CanonFrom.getLocalUnqualifiedType()
2366 == CanonTo.getLocalUnqualifiedType() &&
2367 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2368 FromType = ToType;
2369 CanonFrom = CanonTo;
2370 }
2371
2372 SCS.setToType(Idx: 2, T: FromType);
2373
2374 if (CanonFrom == CanonTo)
2375 return true;
2376
2377 // If we have not converted the argument type to the parameter type,
2378 // this is a bad conversion sequence, unless we're resolving an overload in C.
2379 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2380 return false;
2381
2382 ExprResult ER = ExprResult{From};
2383 Sema::AssignConvertType Conv =
2384 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2385 /*Diagnose=*/false,
2386 /*DiagnoseCFAudited=*/false,
2387 /*ConvertRHS=*/false);
2388 ImplicitConversionKind SecondConv;
2389 switch (Conv) {
2390 case Sema::Compatible:
2391 SecondConv = ICK_C_Only_Conversion;
2392 break;
2393 // For our purposes, discarding qualifiers is just as bad as using an
2394 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2395 // qualifiers, as well.
2396 case Sema::CompatiblePointerDiscardsQualifiers:
2397 case Sema::IncompatiblePointer:
2398 case Sema::IncompatiblePointerSign:
2399 SecondConv = ICK_Incompatible_Pointer_Conversion;
2400 break;
2401 default:
2402 return false;
2403 }
2404
2405 // First can only be an lvalue conversion, so we pretend that this was the
2406 // second conversion. First should already be valid from earlier in the
2407 // function.
2408 SCS.Second = SecondConv;
2409 SCS.setToType(Idx: 1, T: ToType);
2410
2411 // Third is Identity, because Second should rank us worse than any other
2412 // conversion. This could also be ICK_Qualification, but it's simpler to just
2413 // lump everything in with the second conversion, and we don't gain anything
2414 // from making this ICK_Qualification.
2415 SCS.Third = ICK_Identity;
2416 SCS.setToType(Idx: 2, T: ToType);
2417 return true;
2418}
2419
2420static bool
2421IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2422 QualType &ToType,
2423 bool InOverloadResolution,
2424 StandardConversionSequence &SCS,
2425 bool CStyle) {
2426
2427 const RecordType *UT = ToType->getAsUnionType();
2428 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2429 return false;
2430 // The field to initialize within the transparent union.
2431 RecordDecl *UD = UT->getDecl();
2432 // It's compatible if the expression matches any of the fields.
2433 for (const auto *it : UD->fields()) {
2434 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2435 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2436 ToType = it->getType();
2437 return true;
2438 }
2439 }
2440 return false;
2441}
2442
2443bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2444 const BuiltinType *To = ToType->getAs<BuiltinType>();
2445 // All integers are built-in.
2446 if (!To) {
2447 return false;
2448 }
2449
2450 // An rvalue of type char, signed char, unsigned char, short int, or
2451 // unsigned short int can be converted to an rvalue of type int if
2452 // int can represent all the values of the source type; otherwise,
2453 // the source rvalue can be converted to an rvalue of type unsigned
2454 // int (C++ 4.5p1).
2455 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2456 !FromType->isEnumeralType()) {
2457 if ( // We can promote any signed, promotable integer type to an int
2458 (FromType->isSignedIntegerType() ||
2459 // We can promote any unsigned integer type whose size is
2460 // less than int to an int.
2461 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2462 return To->getKind() == BuiltinType::Int;
2463 }
2464
2465 return To->getKind() == BuiltinType::UInt;
2466 }
2467
2468 // C++11 [conv.prom]p3:
2469 // A prvalue of an unscoped enumeration type whose underlying type is not
2470 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2471 // following types that can represent all the values of the enumeration
2472 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2473 // unsigned int, long int, unsigned long int, long long int, or unsigned
2474 // long long int. If none of the types in that list can represent all the
2475 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2476 // type can be converted to an rvalue a prvalue of the extended integer type
2477 // with lowest integer conversion rank (4.13) greater than the rank of long
2478 // long in which all the values of the enumeration can be represented. If
2479 // there are two such extended types, the signed one is chosen.
2480 // C++11 [conv.prom]p4:
2481 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2482 // can be converted to a prvalue of its underlying type. Moreover, if
2483 // integral promotion can be applied to its underlying type, a prvalue of an
2484 // unscoped enumeration type whose underlying type is fixed can also be
2485 // converted to a prvalue of the promoted underlying type.
2486 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2487 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2488 // provided for a scoped enumeration.
2489 if (FromEnumType->getDecl()->isScoped())
2490 return false;
2491
2492 // We can perform an integral promotion to the underlying type of the enum,
2493 // even if that's not the promoted type. Note that the check for promoting
2494 // the underlying type is based on the type alone, and does not consider
2495 // the bitfield-ness of the actual source expression.
2496 if (FromEnumType->getDecl()->isFixed()) {
2497 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2498 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2499 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2500 }
2501
2502 // We have already pre-calculated the promotion type, so this is trivial.
2503 if (ToType->isIntegerType() &&
2504 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2505 return Context.hasSameUnqualifiedType(
2506 T1: ToType, T2: FromEnumType->getDecl()->getPromotionType());
2507
2508 // C++ [conv.prom]p5:
2509 // If the bit-field has an enumerated type, it is treated as any other
2510 // value of that type for promotion purposes.
2511 //
2512 // ... so do not fall through into the bit-field checks below in C++.
2513 if (getLangOpts().CPlusPlus)
2514 return false;
2515 }
2516
2517 // C++0x [conv.prom]p2:
2518 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2519 // to an rvalue a prvalue of the first of the following types that can
2520 // represent all the values of its underlying type: int, unsigned int,
2521 // long int, unsigned long int, long long int, or unsigned long long int.
2522 // If none of the types in that list can represent all the values of its
2523 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2524 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2525 // type.
2526 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2527 ToType->isIntegerType()) {
2528 // Determine whether the type we're converting from is signed or
2529 // unsigned.
2530 bool FromIsSigned = FromType->isSignedIntegerType();
2531 uint64_t FromSize = Context.getTypeSize(T: FromType);
2532
2533 // The types we'll try to promote to, in the appropriate
2534 // order. Try each of these types.
2535 QualType PromoteTypes[6] = {
2536 Context.IntTy, Context.UnsignedIntTy,
2537 Context.LongTy, Context.UnsignedLongTy ,
2538 Context.LongLongTy, Context.UnsignedLongLongTy
2539 };
2540 for (int Idx = 0; Idx < 6; ++Idx) {
2541 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2542 if (FromSize < ToSize ||
2543 (FromSize == ToSize &&
2544 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2545 // We found the type that we can promote to. If this is the
2546 // type we wanted, we have a promotion. Otherwise, no
2547 // promotion.
2548 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2549 }
2550 }
2551 }
2552
2553 // An rvalue for an integral bit-field (9.6) can be converted to an
2554 // rvalue of type int if int can represent all the values of the
2555 // bit-field; otherwise, it can be converted to unsigned int if
2556 // unsigned int can represent all the values of the bit-field. If
2557 // the bit-field is larger yet, no integral promotion applies to
2558 // it. If the bit-field has an enumerated type, it is treated as any
2559 // other value of that type for promotion purposes (C++ 4.5p3).
2560 // FIXME: We should delay checking of bit-fields until we actually perform the
2561 // conversion.
2562 //
2563 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2564 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2565 // bit-fields and those whose underlying type is larger than int) for GCC
2566 // compatibility.
2567 if (From) {
2568 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2569 std::optional<llvm::APSInt> BitWidth;
2570 if (FromType->isIntegralType(Ctx: Context) &&
2571 (BitWidth =
2572 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2573 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2574 ToSize = Context.getTypeSize(T: ToType);
2575
2576 // Are we promoting to an int from a bitfield that fits in an int?
2577 if (*BitWidth < ToSize ||
2578 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2579 return To->getKind() == BuiltinType::Int;
2580 }
2581
2582 // Are we promoting to an unsigned int from an unsigned bitfield
2583 // that fits into an unsigned int?
2584 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2585 return To->getKind() == BuiltinType::UInt;
2586 }
2587
2588 return false;
2589 }
2590 }
2591 }
2592
2593 // An rvalue of type bool can be converted to an rvalue of type int,
2594 // with false becoming zero and true becoming one (C++ 4.5p4).
2595 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2596 return true;
2597 }
2598
2599 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2600 // integral type.
2601 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2602 ToType->isIntegerType())
2603 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2604
2605 return false;
2606}
2607
2608bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2609 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2610 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2611 /// An rvalue of type float can be converted to an rvalue of type
2612 /// double. (C++ 4.6p1).
2613 if (FromBuiltin->getKind() == BuiltinType::Float &&
2614 ToBuiltin->getKind() == BuiltinType::Double)
2615 return true;
2616
2617 // C99 6.3.1.5p1:
2618 // When a float is promoted to double or long double, or a
2619 // double is promoted to long double [...].
2620 if (!getLangOpts().CPlusPlus &&
2621 (FromBuiltin->getKind() == BuiltinType::Float ||
2622 FromBuiltin->getKind() == BuiltinType::Double) &&
2623 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2624 ToBuiltin->getKind() == BuiltinType::Float128 ||
2625 ToBuiltin->getKind() == BuiltinType::Ibm128))
2626 return true;
2627
2628 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2629 // or not native half types are enabled.
2630 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2631 (ToBuiltin->getKind() == BuiltinType::Float ||
2632 ToBuiltin->getKind() == BuiltinType::Double))
2633 return true;
2634
2635 // Half can be promoted to float.
2636 if (!getLangOpts().NativeHalfType &&
2637 FromBuiltin->getKind() == BuiltinType::Half &&
2638 ToBuiltin->getKind() == BuiltinType::Float)
2639 return true;
2640 }
2641
2642 return false;
2643}
2644
2645bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2646 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2647 if (!FromComplex)
2648 return false;
2649
2650 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2651 if (!ToComplex)
2652 return false;
2653
2654 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2655 ToType: ToComplex->getElementType()) ||
2656 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2657 ToType: ToComplex->getElementType());
2658}
2659
2660/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2661/// the pointer type FromPtr to a pointer to type ToPointee, with the
2662/// same type qualifiers as FromPtr has on its pointee type. ToType,
2663/// if non-empty, will be a pointer to ToType that may or may not have
2664/// the right set of qualifiers on its pointee.
2665///
2666static QualType
2667BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2668 QualType ToPointee, QualType ToType,
2669 ASTContext &Context,
2670 bool StripObjCLifetime = false) {
2671 assert((FromPtr->getTypeClass() == Type::Pointer ||
2672 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2673 "Invalid similarly-qualified pointer type");
2674
2675 /// Conversions to 'id' subsume cv-qualifier conversions.
2676 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2677 return ToType.getUnqualifiedType();
2678
2679 QualType CanonFromPointee
2680 = Context.getCanonicalType(T: FromPtr->getPointeeType());
2681 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
2682 Qualifiers Quals = CanonFromPointee.getQualifiers();
2683
2684 if (StripObjCLifetime)
2685 Quals.removeObjCLifetime();
2686
2687 // Exact qualifier match -> return the pointer type we're converting to.
2688 if (CanonToPointee.getLocalQualifiers() == Quals) {
2689 // ToType is exactly what we need. Return it.
2690 if (!ToType.isNull())
2691 return ToType.getUnqualifiedType();
2692
2693 // Build a pointer to ToPointee. It has the right qualifiers
2694 // already.
2695 if (isa<ObjCObjectPointerType>(Val: ToType))
2696 return Context.getObjCObjectPointerType(OIT: ToPointee);
2697 return Context.getPointerType(T: ToPointee);
2698 }
2699
2700 // Just build a canonical type that has the right qualifiers.
2701 QualType QualifiedCanonToPointee
2702 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
2703
2704 if (isa<ObjCObjectPointerType>(Val: ToType))
2705 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
2706 return Context.getPointerType(T: QualifiedCanonToPointee);
2707}
2708
2709static bool isNullPointerConstantForConversion(Expr *Expr,
2710 bool InOverloadResolution,
2711 ASTContext &Context) {
2712 // Handle value-dependent integral null pointer constants correctly.
2713 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2714 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2715 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2716 return !InOverloadResolution;
2717
2718 return Expr->isNullPointerConstant(Ctx&: Context,
2719 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2720 : Expr::NPC_ValueDependentIsNull);
2721}
2722
2723bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2724 bool InOverloadResolution,
2725 QualType& ConvertedType,
2726 bool &IncompatibleObjC) {
2727 IncompatibleObjC = false;
2728 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2729 IncompatibleObjC))
2730 return true;
2731
2732 // Conversion from a null pointer constant to any Objective-C pointer type.
2733 if (ToType->isObjCObjectPointerType() &&
2734 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2735 ConvertedType = ToType;
2736 return true;
2737 }
2738
2739 // Blocks: Block pointers can be converted to void*.
2740 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2741 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2742 ConvertedType = ToType;
2743 return true;
2744 }
2745 // Blocks: A null pointer constant can be converted to a block
2746 // pointer type.
2747 if (ToType->isBlockPointerType() &&
2748 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2749 ConvertedType = ToType;
2750 return true;
2751 }
2752
2753 // If the left-hand-side is nullptr_t, the right side can be a null
2754 // pointer constant.
2755 if (ToType->isNullPtrType() &&
2756 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2757 ConvertedType = ToType;
2758 return true;
2759 }
2760
2761 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2762 if (!ToTypePtr)
2763 return false;
2764
2765 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2766 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2767 ConvertedType = ToType;
2768 return true;
2769 }
2770
2771 // Beyond this point, both types need to be pointers
2772 // , including objective-c pointers.
2773 QualType ToPointeeType = ToTypePtr->getPointeeType();
2774 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2775 !getLangOpts().ObjCAutoRefCount) {
2776 ConvertedType = BuildSimilarlyQualifiedPointerType(
2777 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
2778 Context);
2779 return true;
2780 }
2781 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2782 if (!FromTypePtr)
2783 return false;
2784
2785 QualType FromPointeeType = FromTypePtr->getPointeeType();
2786
2787 // If the unqualified pointee types are the same, this can't be a
2788 // pointer conversion, so don't do all of the work below.
2789 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
2790 return false;
2791
2792 // An rvalue of type "pointer to cv T," where T is an object type,
2793 // can be converted to an rvalue of type "pointer to cv void" (C++
2794 // 4.10p2).
2795 if (FromPointeeType->isIncompleteOrObjectType() &&
2796 ToPointeeType->isVoidType()) {
2797 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
2798 ToPointee: ToPointeeType,
2799 ToType, Context,
2800 /*StripObjCLifetime=*/true);
2801 return true;
2802 }
2803
2804 // MSVC allows implicit function to void* type conversion.
2805 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2806 ToPointeeType->isVoidType()) {
2807 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
2808 ToPointee: ToPointeeType,
2809 ToType, Context);
2810 return true;
2811 }
2812
2813 // When we're overloading in C, we allow a special kind of pointer
2814 // conversion for compatible-but-not-identical pointee types.
2815 if (!getLangOpts().CPlusPlus &&
2816 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
2817 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
2818 ToPointee: ToPointeeType,
2819 ToType, Context);
2820 return true;
2821 }
2822
2823 // C++ [conv.ptr]p3:
2824 //
2825 // An rvalue of type "pointer to cv D," where D is a class type,
2826 // can be converted to an rvalue of type "pointer to cv B," where
2827 // B is a base class (clause 10) of D. If B is an inaccessible
2828 // (clause 11) or ambiguous (10.2) base class of D, a program that
2829 // necessitates this conversion is ill-formed. The result of the
2830 // conversion is a pointer to the base class sub-object of the
2831 // derived class object. The null pointer value is converted to
2832 // the null pointer value of the destination type.
2833 //
2834 // Note that we do not check for ambiguity or inaccessibility
2835 // here. That is handled by CheckPointerConversion.
2836 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2837 ToPointeeType->isRecordType() &&
2838 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
2839 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
2840 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
2841 ToPointee: ToPointeeType,
2842 ToType, Context);
2843 return true;
2844 }
2845
2846 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2847 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
2848 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
2849 ToPointee: ToPointeeType,
2850 ToType, Context);
2851 return true;
2852 }
2853
2854 return false;
2855}
2856
2857/// Adopt the given qualifiers for the given type.
2858static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2859 Qualifiers TQs = T.getQualifiers();
2860
2861 // Check whether qualifiers already match.
2862 if (TQs == Qs)
2863 return T;
2864
2865 if (Qs.compatiblyIncludes(other: TQs))
2866 return Context.getQualifiedType(T, Qs);
2867
2868 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
2869}
2870
2871bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2872 QualType& ConvertedType,
2873 bool &IncompatibleObjC) {
2874 if (!getLangOpts().ObjC)
2875 return false;
2876
2877 // The set of qualifiers on the type we're converting from.
2878 Qualifiers FromQualifiers = FromType.getQualifiers();
2879
2880 // First, we handle all conversions on ObjC object pointer types.
2881 const ObjCObjectPointerType* ToObjCPtr =
2882 ToType->getAs<ObjCObjectPointerType>();
2883 const ObjCObjectPointerType *FromObjCPtr =
2884 FromType->getAs<ObjCObjectPointerType>();
2885
2886 if (ToObjCPtr && FromObjCPtr) {
2887 // If the pointee types are the same (ignoring qualifications),
2888 // then this is not a pointer conversion.
2889 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
2890 T2: FromObjCPtr->getPointeeType()))
2891 return false;
2892
2893 // Conversion between Objective-C pointers.
2894 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
2895 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2896 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2897 if (getLangOpts().CPlusPlus && LHS && RHS &&
2898 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2899 other: FromObjCPtr->getPointeeType()))
2900 return false;
2901 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
2902 ToPointee: ToObjCPtr->getPointeeType(),
2903 ToType, Context);
2904 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
2905 return true;
2906 }
2907
2908 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
2909 // Okay: this is some kind of implicit downcast of Objective-C
2910 // interfaces, which is permitted. However, we're going to
2911 // complain about it.
2912 IncompatibleObjC = true;
2913 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
2914 ToPointee: ToObjCPtr->getPointeeType(),
2915 ToType, Context);
2916 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
2917 return true;
2918 }
2919 }
2920 // Beyond this point, both types need to be C pointers or block pointers.
2921 QualType ToPointeeType;
2922 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2923 ToPointeeType = ToCPtr->getPointeeType();
2924 else if (const BlockPointerType *ToBlockPtr =
2925 ToType->getAs<BlockPointerType>()) {
2926 // Objective C++: We're able to convert from a pointer to any object
2927 // to a block pointer type.
2928 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2929 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
2930 return true;
2931 }
2932 ToPointeeType = ToBlockPtr->getPointeeType();
2933 }
2934 else if (FromType->getAs<BlockPointerType>() &&
2935 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2936 // Objective C++: We're able to convert from a block pointer type to a
2937 // pointer to any object.
2938 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
2939 return true;
2940 }
2941 else
2942 return false;
2943
2944 QualType FromPointeeType;
2945 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2946 FromPointeeType = FromCPtr->getPointeeType();
2947 else if (const BlockPointerType *FromBlockPtr =
2948 FromType->getAs<BlockPointerType>())
2949 FromPointeeType = FromBlockPtr->getPointeeType();
2950 else
2951 return false;
2952
2953 // If we have pointers to pointers, recursively check whether this
2954 // is an Objective-C conversion.
2955 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2956 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
2957 IncompatibleObjC)) {
2958 // We always complain about this conversion.
2959 IncompatibleObjC = true;
2960 ConvertedType = Context.getPointerType(T: ConvertedType);
2961 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
2962 return true;
2963 }
2964 // Allow conversion of pointee being objective-c pointer to another one;
2965 // as in I* to id.
2966 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2967 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2968 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
2969 IncompatibleObjC)) {
2970
2971 ConvertedType = Context.getPointerType(T: ConvertedType);
2972 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
2973 return true;
2974 }
2975
2976 // If we have pointers to functions or blocks, check whether the only
2977 // differences in the argument and result types are in Objective-C
2978 // pointer conversions. If so, we permit the conversion (but
2979 // complain about it).
2980 const FunctionProtoType *FromFunctionType
2981 = FromPointeeType->getAs<FunctionProtoType>();
2982 const FunctionProtoType *ToFunctionType
2983 = ToPointeeType->getAs<FunctionProtoType>();
2984 if (FromFunctionType && ToFunctionType) {
2985 // If the function types are exactly the same, this isn't an
2986 // Objective-C pointer conversion.
2987 if (Context.getCanonicalType(T: FromPointeeType)
2988 == Context.getCanonicalType(T: ToPointeeType))
2989 return false;
2990
2991 // Perform the quick checks that will tell us whether these
2992 // function types are obviously different.
2993 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2994 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2995 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2996 return false;
2997
2998 bool HasObjCConversion = false;
2999 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3000 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3001 // Okay, the types match exactly. Nothing to do.
3002 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3003 ToType: ToFunctionType->getReturnType(),
3004 ConvertedType, IncompatibleObjC)) {
3005 // Okay, we have an Objective-C pointer conversion.
3006 HasObjCConversion = true;
3007 } else {
3008 // Function types are too different. Abort.
3009 return false;
3010 }
3011
3012 // Check argument types.
3013 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3014 ArgIdx != NumArgs; ++ArgIdx) {
3015 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3016 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3017 if (Context.getCanonicalType(T: FromArgType)
3018 == Context.getCanonicalType(T: ToArgType)) {
3019 // Okay, the types match exactly. Nothing to do.
3020 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3021 ConvertedType, IncompatibleObjC)) {
3022 // Okay, we have an Objective-C pointer conversion.
3023 HasObjCConversion = true;
3024 } else {
3025 // Argument types are too different. Abort.
3026 return false;
3027 }
3028 }
3029
3030 if (HasObjCConversion) {
3031 // We had an Objective-C conversion. Allow this pointer
3032 // conversion, but complain about it.
3033 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3034 IncompatibleObjC = true;
3035 return true;
3036 }
3037 }
3038
3039 return false;
3040}
3041
3042bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3043 QualType& ConvertedType) {
3044 QualType ToPointeeType;
3045 if (const BlockPointerType *ToBlockPtr =
3046 ToType->getAs<BlockPointerType>())
3047 ToPointeeType = ToBlockPtr->getPointeeType();
3048 else
3049 return false;
3050
3051 QualType FromPointeeType;
3052 if (const BlockPointerType *FromBlockPtr =
3053 FromType->getAs<BlockPointerType>())
3054 FromPointeeType = FromBlockPtr->getPointeeType();
3055 else
3056 return false;
3057 // We have pointer to blocks, check whether the only
3058 // differences in the argument and result types are in Objective-C
3059 // pointer conversions. If so, we permit the conversion.
3060
3061 const FunctionProtoType *FromFunctionType
3062 = FromPointeeType->getAs<FunctionProtoType>();
3063 const FunctionProtoType *ToFunctionType
3064 = ToPointeeType->getAs<FunctionProtoType>();
3065
3066 if (!FromFunctionType || !ToFunctionType)
3067 return false;
3068
3069 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3070 return true;
3071
3072 // Perform the quick checks that will tell us whether these
3073 // function types are obviously different.
3074 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3075 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3076 return false;
3077
3078 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3079 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3080 if (FromEInfo != ToEInfo)
3081 return false;
3082
3083 bool IncompatibleObjC = false;
3084 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3085 T2: ToFunctionType->getReturnType())) {
3086 // Okay, the types match exactly. Nothing to do.
3087 } else {
3088 QualType RHS = FromFunctionType->getReturnType();
3089 QualType LHS = ToFunctionType->getReturnType();
3090 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3091 !RHS.hasQualifiers() && LHS.hasQualifiers())
3092 LHS = LHS.getUnqualifiedType();
3093
3094 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3095 // OK exact match.
3096 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3097 ConvertedType, IncompatibleObjC)) {
3098 if (IncompatibleObjC)
3099 return false;
3100 // Okay, we have an Objective-C pointer conversion.
3101 }
3102 else
3103 return false;
3104 }
3105
3106 // Check argument types.
3107 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3108 ArgIdx != NumArgs; ++ArgIdx) {
3109 IncompatibleObjC = false;
3110 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3111 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3112 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3113 // Okay, the types match exactly. Nothing to do.
3114 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3115 ConvertedType, IncompatibleObjC)) {
3116 if (IncompatibleObjC)
3117 return false;
3118 // Okay, we have an Objective-C pointer conversion.
3119 } else
3120 // Argument types are too different. Abort.
3121 return false;
3122 }
3123
3124 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3125 bool CanUseToFPT, CanUseFromFPT;
3126 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3127 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3128 NewParamInfos))
3129 return false;
3130
3131 ConvertedType = ToType;
3132 return true;
3133}
3134
3135enum {
3136 ft_default,
3137 ft_different_class,
3138 ft_parameter_arity,
3139 ft_parameter_mismatch,
3140 ft_return_type,
3141 ft_qualifer_mismatch,
3142 ft_noexcept
3143};
3144
3145/// Attempts to get the FunctionProtoType from a Type. Handles
3146/// MemberFunctionPointers properly.
3147static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3148 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3149 return FPT;
3150
3151 if (auto *MPT = FromType->getAs<MemberPointerType>())
3152 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3153
3154 return nullptr;
3155}
3156
3157void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3158 QualType FromType, QualType ToType) {
3159 // If either type is not valid, include no extra info.
3160 if (FromType.isNull() || ToType.isNull()) {
3161 PDiag << ft_default;
3162 return;
3163 }
3164
3165 // Get the function type from the pointers.
3166 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3167 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3168 *ToMember = ToType->castAs<MemberPointerType>();
3169 if (!Context.hasSameType(T1: FromMember->getClass(), T2: ToMember->getClass())) {
3170 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3171 << QualType(FromMember->getClass(), 0);
3172 return;
3173 }
3174 FromType = FromMember->getPointeeType();
3175 ToType = ToMember->getPointeeType();
3176 }
3177
3178 if (FromType->isPointerType())
3179 FromType = FromType->getPointeeType();
3180 if (ToType->isPointerType())
3181 ToType = ToType->getPointeeType();
3182
3183 // Remove references.
3184 FromType = FromType.getNonReferenceType();
3185 ToType = ToType.getNonReferenceType();
3186
3187 // Don't print extra info for non-specialized template functions.
3188 if (FromType->isInstantiationDependentType() &&
3189 !FromType->getAs<TemplateSpecializationType>()) {
3190 PDiag << ft_default;
3191 return;
3192 }
3193
3194 // No extra info for same types.
3195 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3196 PDiag << ft_default;
3197 return;
3198 }
3199
3200 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3201 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3202
3203 // Both types need to be function types.
3204 if (!FromFunction || !ToFunction) {
3205 PDiag << ft_default;
3206 return;
3207 }
3208
3209 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3210 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3211 << FromFunction->getNumParams();
3212 return;
3213 }
3214
3215 // Handle different parameter types.
3216 unsigned ArgPos;
3217 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3218 PDiag << ft_parameter_mismatch << ArgPos + 1
3219 << ToFunction->getParamType(i: ArgPos)
3220 << FromFunction->getParamType(i: ArgPos);
3221 return;
3222 }
3223
3224 // Handle different return type.
3225 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3226 T2: ToFunction->getReturnType())) {
3227 PDiag << ft_return_type << ToFunction->getReturnType()
3228 << FromFunction->getReturnType();
3229 return;
3230 }
3231
3232 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3233 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3234 << FromFunction->getMethodQuals();
3235 return;
3236 }
3237
3238 // Handle exception specification differences on canonical type (in C++17
3239 // onwards).
3240 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3241 ->isNothrow() !=
3242 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3243 ->isNothrow()) {
3244 PDiag << ft_noexcept;
3245 return;
3246 }
3247
3248 // Unable to find a difference, so add no extra info.
3249 PDiag << ft_default;
3250}
3251
3252bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3253 ArrayRef<QualType> New, unsigned *ArgPos,
3254 bool Reversed) {
3255 assert(llvm::size(Old) == llvm::size(New) &&
3256 "Can't compare parameters of functions with different number of "
3257 "parameters!");
3258
3259 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3260 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3261 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3262
3263 // Ignore address spaces in pointee type. This is to disallow overloading
3264 // on __ptr32/__ptr64 address spaces.
3265 QualType OldType =
3266 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3267 QualType NewType =
3268 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3269
3270 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3271 if (ArgPos)
3272 *ArgPos = Idx;
3273 return false;
3274 }
3275 }
3276 return true;
3277}
3278
3279bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3280 const FunctionProtoType *NewType,
3281 unsigned *ArgPos, bool Reversed) {
3282 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3283 New: NewType->param_types(), ArgPos, Reversed);
3284}
3285
3286bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3287 const FunctionDecl *NewFunction,
3288 unsigned *ArgPos,
3289 bool Reversed) {
3290
3291 if (OldFunction->getNumNonObjectParams() !=
3292 NewFunction->getNumNonObjectParams())
3293 return false;
3294
3295 unsigned OldIgnore =
3296 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3297 unsigned NewIgnore =
3298 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3299
3300 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3301 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3302
3303 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3304 New: NewPT->param_types().slice(N: NewIgnore),
3305 ArgPos, Reversed);
3306}
3307
3308bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3309 CastKind &Kind,
3310 CXXCastPath& BasePath,
3311 bool IgnoreBaseAccess,
3312 bool Diagnose) {
3313 QualType FromType = From->getType();
3314 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3315
3316 Kind = CK_BitCast;
3317
3318 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3319 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3320 Expr::NPCK_ZeroExpression) {
3321 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3322 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3323 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3324 << ToType << From->getSourceRange());
3325 else if (!isUnevaluatedContext())
3326 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3327 << ToType << From->getSourceRange();
3328 }
3329 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3330 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3331 QualType FromPointeeType = FromPtrType->getPointeeType(),
3332 ToPointeeType = ToPtrType->getPointeeType();
3333
3334 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3335 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3336 // We must have a derived-to-base conversion. Check an
3337 // ambiguous or inaccessible conversion.
3338 unsigned InaccessibleID = 0;
3339 unsigned AmbiguousID = 0;
3340 if (Diagnose) {
3341 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3342 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3343 }
3344 if (CheckDerivedToBaseConversion(
3345 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3346 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3347 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3348 return true;
3349
3350 // The conversion was successful.
3351 Kind = CK_DerivedToBase;
3352 }
3353
3354 if (Diagnose && !IsCStyleOrFunctionalCast &&
3355 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3356 assert(getLangOpts().MSVCCompat &&
3357 "this should only be possible with MSVCCompat!");
3358 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3359 << From->getSourceRange();
3360 }
3361 }
3362 } else if (const ObjCObjectPointerType *ToPtrType =
3363 ToType->getAs<ObjCObjectPointerType>()) {
3364 if (const ObjCObjectPointerType *FromPtrType =
3365 FromType->getAs<ObjCObjectPointerType>()) {
3366 // Objective-C++ conversions are always okay.
3367 // FIXME: We should have a different class of conversions for the
3368 // Objective-C++ implicit conversions.
3369 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3370 return false;
3371 } else if (FromType->isBlockPointerType()) {
3372 Kind = CK_BlockPointerToObjCPointerCast;
3373 } else {
3374 Kind = CK_CPointerToObjCPointerCast;
3375 }
3376 } else if (ToType->isBlockPointerType()) {
3377 if (!FromType->isBlockPointerType())
3378 Kind = CK_AnyPointerToBlockPointerCast;
3379 }
3380
3381 // We shouldn't fall into this case unless it's valid for other
3382 // reasons.
3383 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3384 Kind = CK_NullToPointer;
3385
3386 return false;
3387}
3388
3389bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3390 QualType ToType,
3391 bool InOverloadResolution,
3392 QualType &ConvertedType) {
3393 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3394 if (!ToTypePtr)
3395 return false;
3396
3397 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3398 if (From->isNullPointerConstant(Ctx&: Context,
3399 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3400 : Expr::NPC_ValueDependentIsNull)) {
3401 ConvertedType = ToType;
3402 return true;
3403 }
3404
3405 // Otherwise, both types have to be member pointers.
3406 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3407 if (!FromTypePtr)
3408 return false;
3409
3410 // A pointer to member of B can be converted to a pointer to member of D,
3411 // where D is derived from B (C++ 4.11p2).
3412 QualType FromClass(FromTypePtr->getClass(), 0);
3413 QualType ToClass(ToTypePtr->getClass(), 0);
3414
3415 if (!Context.hasSameUnqualifiedType(T1: FromClass, T2: ToClass) &&
3416 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3417 ConvertedType = Context.getMemberPointerType(T: FromTypePtr->getPointeeType(),
3418 Cls: ToClass.getTypePtr());
3419 return true;
3420 }
3421
3422 return false;
3423}
3424
3425bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3426 CastKind &Kind,
3427 CXXCastPath &BasePath,
3428 bool IgnoreBaseAccess) {
3429 QualType FromType = From->getType();
3430 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3431 if (!FromPtrType) {
3432 // This must be a null pointer to member pointer conversion
3433 assert(From->isNullPointerConstant(Context,
3434 Expr::NPC_ValueDependentIsNull) &&
3435 "Expr must be null pointer constant!");
3436 Kind = CK_NullToMemberPointer;
3437 return false;
3438 }
3439
3440 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3441 assert(ToPtrType && "No member pointer cast has a target type "
3442 "that is not a member pointer.");
3443
3444 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3445 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3446
3447 // FIXME: What about dependent types?
3448 assert(FromClass->isRecordType() && "Pointer into non-class.");
3449 assert(ToClass->isRecordType() && "Pointer into non-class.");
3450
3451 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3452 /*DetectVirtual=*/true);
3453 bool DerivationOkay =
3454 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass, Paths);
3455 assert(DerivationOkay &&
3456 "Should not have been called if derivation isn't OK.");
3457 (void)DerivationOkay;
3458
3459 if (Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: FromClass).
3460 getUnqualifiedType())) {
3461 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3462 Diag(Loc: From->getExprLoc(), DiagID: diag::err_ambiguous_memptr_conv)
3463 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3464 return true;
3465 }
3466
3467 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3468 Diag(Loc: From->getExprLoc(), DiagID: diag::err_memptr_conv_via_virtual)
3469 << FromClass << ToClass << QualType(VBase, 0)
3470 << From->getSourceRange();
3471 return true;
3472 }
3473
3474 if (!IgnoreBaseAccess)
3475 CheckBaseClassAccess(AccessLoc: From->getExprLoc(), Base: FromClass, Derived: ToClass,
3476 Path: Paths.front(),
3477 DiagID: diag::err_downcast_from_inaccessible_base);
3478
3479 // Must be a base to derived member conversion.
3480 BuildBasePathArray(Paths, BasePath);
3481 Kind = CK_BaseToDerivedMemberPointer;
3482 return false;
3483}
3484
3485/// Determine whether the lifetime conversion between the two given
3486/// qualifiers sets is nontrivial.
3487static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3488 Qualifiers ToQuals) {
3489 // Converting anything to const __unsafe_unretained is trivial.
3490 if (ToQuals.hasConst() &&
3491 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3492 return false;
3493
3494 return true;
3495}
3496
3497/// Perform a single iteration of the loop for checking if a qualification
3498/// conversion is valid.
3499///
3500/// Specifically, check whether any change between the qualifiers of \p
3501/// FromType and \p ToType is permissible, given knowledge about whether every
3502/// outer layer is const-qualified.
3503static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3504 bool CStyle, bool IsTopLevel,
3505 bool &PreviousToQualsIncludeConst,
3506 bool &ObjCLifetimeConversion) {
3507 Qualifiers FromQuals = FromType.getQualifiers();
3508 Qualifiers ToQuals = ToType.getQualifiers();
3509
3510 // Ignore __unaligned qualifier.
3511 FromQuals.removeUnaligned();
3512
3513 // Objective-C ARC:
3514 // Check Objective-C lifetime conversions.
3515 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3516 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3517 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3518 ObjCLifetimeConversion = true;
3519 FromQuals.removeObjCLifetime();
3520 ToQuals.removeObjCLifetime();
3521 } else {
3522 // Qualification conversions cannot cast between different
3523 // Objective-C lifetime qualifiers.
3524 return false;
3525 }
3526 }
3527
3528 // Allow addition/removal of GC attributes but not changing GC attributes.
3529 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3530 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3531 FromQuals.removeObjCGCAttr();
3532 ToQuals.removeObjCGCAttr();
3533 }
3534
3535 // -- for every j > 0, if const is in cv 1,j then const is in cv
3536 // 2,j, and similarly for volatile.
3537 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals))
3538 return false;
3539
3540 // If address spaces mismatch:
3541 // - in top level it is only valid to convert to addr space that is a
3542 // superset in all cases apart from C-style casts where we allow
3543 // conversions between overlapping address spaces.
3544 // - in non-top levels it is not a valid conversion.
3545 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3546 (!IsTopLevel ||
3547 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals) ||
3548 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals)))))
3549 return false;
3550
3551 // -- if the cv 1,j and cv 2,j are different, then const is in
3552 // every cv for 0 < k < j.
3553 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3554 !PreviousToQualsIncludeConst)
3555 return false;
3556
3557 // The following wording is from C++20, where the result of the conversion
3558 // is T3, not T2.
3559 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3560 // "array of unknown bound of"
3561 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3562 return false;
3563
3564 // -- if the resulting P3,i is different from P1,i [...], then const is
3565 // added to every cv 3_k for 0 < k < i.
3566 if (!CStyle && FromType->isConstantArrayType() &&
3567 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3568 return false;
3569
3570 // Keep track of whether all prior cv-qualifiers in the "to" type
3571 // include const.
3572 PreviousToQualsIncludeConst =
3573 PreviousToQualsIncludeConst && ToQuals.hasConst();
3574 return true;
3575}
3576
3577bool
3578Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3579 bool CStyle, bool &ObjCLifetimeConversion) {
3580 FromType = Context.getCanonicalType(T: FromType);
3581 ToType = Context.getCanonicalType(T: ToType);
3582 ObjCLifetimeConversion = false;
3583
3584 // If FromType and ToType are the same type, this is not a
3585 // qualification conversion.
3586 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3587 return false;
3588
3589 // (C++ 4.4p4):
3590 // A conversion can add cv-qualifiers at levels other than the first
3591 // in multi-level pointers, subject to the following rules: [...]
3592 bool PreviousToQualsIncludeConst = true;
3593 bool UnwrappedAnyPointer = false;
3594 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3595 if (!isQualificationConversionStep(
3596 FromType, ToType, CStyle, IsTopLevel: !UnwrappedAnyPointer,
3597 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3598 return false;
3599 UnwrappedAnyPointer = true;
3600 }
3601
3602 // We are left with FromType and ToType being the pointee types
3603 // after unwrapping the original FromType and ToType the same number
3604 // of times. If we unwrapped any pointers, and if FromType and
3605 // ToType have the same unqualified type (since we checked
3606 // qualifiers above), then this is a qualification conversion.
3607 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3608}
3609
3610/// - Determine whether this is a conversion from a scalar type to an
3611/// atomic type.
3612///
3613/// If successful, updates \c SCS's second and third steps in the conversion
3614/// sequence to finish the conversion.
3615static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3616 bool InOverloadResolution,
3617 StandardConversionSequence &SCS,
3618 bool CStyle) {
3619 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3620 if (!ToAtomic)
3621 return false;
3622
3623 StandardConversionSequence InnerSCS;
3624 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
3625 InOverloadResolution, SCS&: InnerSCS,
3626 CStyle, /*AllowObjCWritebackConversion=*/false))
3627 return false;
3628
3629 SCS.Second = InnerSCS.Second;
3630 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
3631 SCS.Third = InnerSCS.Third;
3632 SCS.QualificationIncludesObjCLifetime
3633 = InnerSCS.QualificationIncludesObjCLifetime;
3634 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
3635 return true;
3636}
3637
3638static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3639 CXXConstructorDecl *Constructor,
3640 QualType Type) {
3641 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3642 if (CtorType->getNumParams() > 0) {
3643 QualType FirstArg = CtorType->getParamType(i: 0);
3644 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
3645 return true;
3646 }
3647 return false;
3648}
3649
3650static OverloadingResult
3651IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3652 CXXRecordDecl *To,
3653 UserDefinedConversionSequence &User,
3654 OverloadCandidateSet &CandidateSet,
3655 bool AllowExplicit) {
3656 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3657 for (auto *D : S.LookupConstructors(Class: To)) {
3658 auto Info = getConstructorInfo(ND: D);
3659 if (!Info)
3660 continue;
3661
3662 bool Usable = !Info.Constructor->isInvalidDecl() &&
3663 S.isInitListConstructor(Ctor: Info.Constructor);
3664 if (Usable) {
3665 bool SuppressUserConversions = false;
3666 if (Info.ConstructorTmpl)
3667 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
3668 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
3669 CandidateSet, SuppressUserConversions,
3670 /*PartialOverloading*/ false,
3671 AllowExplicit);
3672 else
3673 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
3674 CandidateSet, SuppressUserConversions,
3675 /*PartialOverloading*/ false, AllowExplicit);
3676 }
3677 }
3678
3679 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3680
3681 OverloadCandidateSet::iterator Best;
3682 switch (auto Result =
3683 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
3684 case OR_Deleted:
3685 case OR_Success: {
3686 // Record the standard conversion we used and the conversion function.
3687 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
3688 QualType ThisType = Constructor->getFunctionObjectParameterType();
3689 // Initializer lists don't have conversions as such.
3690 User.Before.setAsIdentityConversion();
3691 User.HadMultipleCandidates = HadMultipleCandidates;
3692 User.ConversionFunction = Constructor;
3693 User.FoundConversionFunction = Best->FoundDecl;
3694 User.After.setAsIdentityConversion();
3695 User.After.setFromType(ThisType);
3696 User.After.setAllToTypes(ToType);
3697 return Result;
3698 }
3699
3700 case OR_No_Viable_Function:
3701 return OR_No_Viable_Function;
3702 case OR_Ambiguous:
3703 return OR_Ambiguous;
3704 }
3705
3706 llvm_unreachable("Invalid OverloadResult!");
3707}
3708
3709/// Determines whether there is a user-defined conversion sequence
3710/// (C++ [over.ics.user]) that converts expression From to the type
3711/// ToType. If such a conversion exists, User will contain the
3712/// user-defined conversion sequence that performs such a conversion
3713/// and this routine will return true. Otherwise, this routine returns
3714/// false and User is unspecified.
3715///
3716/// \param AllowExplicit true if the conversion should consider C++0x
3717/// "explicit" conversion functions as well as non-explicit conversion
3718/// functions (C++0x [class.conv.fct]p2).
3719///
3720/// \param AllowObjCConversionOnExplicit true if the conversion should
3721/// allow an extra Objective-C pointer conversion on uses of explicit
3722/// constructors. Requires \c AllowExplicit to also be set.
3723static OverloadingResult
3724IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3725 UserDefinedConversionSequence &User,
3726 OverloadCandidateSet &CandidateSet,
3727 AllowedExplicit AllowExplicit,
3728 bool AllowObjCConversionOnExplicit) {
3729 assert(AllowExplicit != AllowedExplicit::None ||
3730 !AllowObjCConversionOnExplicit);
3731 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3732
3733 // Whether we will only visit constructors.
3734 bool ConstructorsOnly = false;
3735
3736 // If the type we are conversion to is a class type, enumerate its
3737 // constructors.
3738 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3739 // C++ [over.match.ctor]p1:
3740 // When objects of class type are direct-initialized (8.5), or
3741 // copy-initialized from an expression of the same or a
3742 // derived class type (8.5), overload resolution selects the
3743 // constructor. [...] For copy-initialization, the candidate
3744 // functions are all the converting constructors (12.3.1) of
3745 // that class. The argument list is the expression-list within
3746 // the parentheses of the initializer.
3747 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
3748 (From->getType()->getAs<RecordType>() &&
3749 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
3750 ConstructorsOnly = true;
3751
3752 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
3753 // We're not going to find any constructors.
3754 } else if (CXXRecordDecl *ToRecordDecl
3755 = dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
3756
3757 Expr **Args = &From;
3758 unsigned NumArgs = 1;
3759 bool ListInitializing = false;
3760 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
3761 // But first, see if there is an init-list-constructor that will work.
3762 OverloadingResult Result = IsInitializerListConstructorConversion(
3763 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
3764 AllowExplicit: AllowExplicit == AllowedExplicit::All);
3765 if (Result != OR_No_Viable_Function)
3766 return Result;
3767 // Never mind.
3768 CandidateSet.clear(
3769 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3770
3771 // If we're list-initializing, we pass the individual elements as
3772 // arguments, not the entire list.
3773 Args = InitList->getInits();
3774 NumArgs = InitList->getNumInits();
3775 ListInitializing = true;
3776 }
3777
3778 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
3779 auto Info = getConstructorInfo(ND: D);
3780 if (!Info)
3781 continue;
3782
3783 bool Usable = !Info.Constructor->isInvalidDecl();
3784 if (!ListInitializing)
3785 Usable = Usable && Info.Constructor->isConvertingConstructor(
3786 /*AllowExplicit*/ true);
3787 if (Usable) {
3788 bool SuppressUserConversions = !ConstructorsOnly;
3789 // C++20 [over.best.ics.general]/4.5:
3790 // if the target is the first parameter of a constructor [of class
3791 // X] and the constructor [...] is a candidate by [...] the second
3792 // phase of [over.match.list] when the initializer list has exactly
3793 // one element that is itself an initializer list, [...] and the
3794 // conversion is to X or reference to cv X, user-defined conversion
3795 // sequences are not cnosidered.
3796 if (SuppressUserConversions && ListInitializing) {
3797 SuppressUserConversions =
3798 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
3799 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
3800 Type: ToType);
3801 }
3802 if (Info.ConstructorTmpl)
3803 S.AddTemplateOverloadCandidate(
3804 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
3805 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
3806 CandidateSet, SuppressUserConversions,
3807 /*PartialOverloading*/ false,
3808 AllowExplicit: AllowExplicit == AllowedExplicit::All);
3809 else
3810 // Allow one user-defined conversion when user specifies a
3811 // From->ToType conversion via an static cast (c-style, etc).
3812 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
3813 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
3814 SuppressUserConversions,
3815 /*PartialOverloading*/ false,
3816 AllowExplicit: AllowExplicit == AllowedExplicit::All);
3817 }
3818 }
3819 }
3820 }
3821
3822 // Enumerate conversion functions, if we're allowed to.
3823 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
3824 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
3825 // No conversion functions from incomplete types.
3826 } else if (const RecordType *FromRecordType =
3827 From->getType()->getAs<RecordType>()) {
3828 if (CXXRecordDecl *FromRecordDecl
3829 = dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
3830 // Add all of the conversion functions as candidates.
3831 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3832 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3833 DeclAccessPair FoundDecl = I.getPair();
3834 NamedDecl *D = FoundDecl.getDecl();
3835 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
3836 if (isa<UsingShadowDecl>(Val: D))
3837 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3838
3839 CXXConversionDecl *Conv;
3840 FunctionTemplateDecl *ConvTemplate;
3841 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
3842 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
3843 else
3844 Conv = cast<CXXConversionDecl>(Val: D);
3845
3846 if (ConvTemplate)
3847 S.AddTemplateConversionCandidate(
3848 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
3849 CandidateSet, AllowObjCConversionOnExplicit,
3850 AllowExplicit: AllowExplicit != AllowedExplicit::None);
3851 else
3852 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
3853 CandidateSet, AllowObjCConversionOnExplicit,
3854 AllowExplicit: AllowExplicit != AllowedExplicit::None);
3855 }
3856 }
3857 }
3858
3859 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3860
3861 OverloadCandidateSet::iterator Best;
3862 switch (auto Result =
3863 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
3864 case OR_Success:
3865 case OR_Deleted:
3866 // Record the standard conversion we used and the conversion function.
3867 if (CXXConstructorDecl *Constructor
3868 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
3869 // C++ [over.ics.user]p1:
3870 // If the user-defined conversion is specified by a
3871 // constructor (12.3.1), the initial standard conversion
3872 // sequence converts the source type to the type required by
3873 // the argument of the constructor.
3874 //
3875 if (isa<InitListExpr>(Val: From)) {
3876 // Initializer lists don't have conversions as such.
3877 User.Before.setAsIdentityConversion();
3878 } else {
3879 if (Best->Conversions[0].isEllipsis())
3880 User.EllipsisConversion = true;
3881 else {
3882 User.Before = Best->Conversions[0].Standard;
3883 User.EllipsisConversion = false;
3884 }
3885 }
3886 User.HadMultipleCandidates = HadMultipleCandidates;
3887 User.ConversionFunction = Constructor;
3888 User.FoundConversionFunction = Best->FoundDecl;
3889 User.After.setAsIdentityConversion();
3890 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3891 User.After.setAllToTypes(ToType);
3892 return Result;
3893 }
3894 if (CXXConversionDecl *Conversion
3895 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
3896 // C++ [over.ics.user]p1:
3897 //
3898 // [...] If the user-defined conversion is specified by a
3899 // conversion function (12.3.2), the initial standard
3900 // conversion sequence converts the source type to the
3901 // implicit object parameter of the conversion function.
3902 User.Before = Best->Conversions[0].Standard;
3903 User.HadMultipleCandidates = HadMultipleCandidates;
3904 User.ConversionFunction = Conversion;
3905 User.FoundConversionFunction = Best->FoundDecl;
3906 User.EllipsisConversion = false;
3907
3908 // C++ [over.ics.user]p2:
3909 // The second standard conversion sequence converts the
3910 // result of the user-defined conversion to the target type
3911 // for the sequence. Since an implicit conversion sequence
3912 // is an initialization, the special rules for
3913 // initialization by user-defined conversion apply when
3914 // selecting the best user-defined conversion for a
3915 // user-defined conversion sequence (see 13.3.3 and
3916 // 13.3.3.1).
3917 User.After = Best->FinalConversion;
3918 return Result;
3919 }
3920 llvm_unreachable("Not a constructor or conversion function?");
3921
3922 case OR_No_Viable_Function:
3923 return OR_No_Viable_Function;
3924
3925 case OR_Ambiguous:
3926 return OR_Ambiguous;
3927 }
3928
3929 llvm_unreachable("Invalid OverloadResult!");
3930}
3931
3932bool
3933Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3934 ImplicitConversionSequence ICS;
3935 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3936 OverloadCandidateSet::CSK_Normal);
3937 OverloadingResult OvResult =
3938 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
3939 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
3940
3941 if (!(OvResult == OR_Ambiguous ||
3942 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3943 return false;
3944
3945 auto Cands = CandidateSet.CompleteCandidates(
3946 S&: *this,
3947 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3948 Args: From);
3949 if (OvResult == OR_Ambiguous)
3950 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
3951 << From->getType() << ToType << From->getSourceRange();
3952 else { // OR_No_Viable_Function && !CandidateSet.empty()
3953 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
3954 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
3955 Args: From->getType(), Args: From->getSourceRange()))
3956 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
3957 << false << From->getType() << From->getSourceRange() << ToType;
3958 }
3959
3960 CandidateSet.NoteCandidates(
3961 S&: *this, Args: From, Cands);
3962 return true;
3963}
3964
3965// Helper for compareConversionFunctions that gets the FunctionType that the
3966// conversion-operator return value 'points' to, or nullptr.
3967static const FunctionType *
3968getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3969 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3970 const PointerType *RetPtrTy =
3971 ConvFuncTy->getReturnType()->getAs<PointerType>();
3972
3973 if (!RetPtrTy)
3974 return nullptr;
3975
3976 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3977}
3978
3979/// Compare the user-defined conversion functions or constructors
3980/// of two user-defined conversion sequences to determine whether any ordering
3981/// is possible.
3982static ImplicitConversionSequence::CompareKind
3983compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3984 FunctionDecl *Function2) {
3985 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
3986 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
3987 if (!Conv1 || !Conv2)
3988 return ImplicitConversionSequence::Indistinguishable;
3989
3990 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3991 return ImplicitConversionSequence::Indistinguishable;
3992
3993 // Objective-C++:
3994 // If both conversion functions are implicitly-declared conversions from
3995 // a lambda closure type to a function pointer and a block pointer,
3996 // respectively, always prefer the conversion to a function pointer,
3997 // because the function pointer is more lightweight and is more likely
3998 // to keep code working.
3999 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4000 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4001 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4002 if (Block1 != Block2)
4003 return Block1 ? ImplicitConversionSequence::Worse
4004 : ImplicitConversionSequence::Better;
4005 }
4006
4007 // In order to support multiple calling conventions for the lambda conversion
4008 // operator (such as when the free and member function calling convention is
4009 // different), prefer the 'free' mechanism, followed by the calling-convention
4010 // of operator(). The latter is in place to support the MSVC-like solution of
4011 // defining ALL of the possible conversions in regards to calling-convention.
4012 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4013 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4014
4015 if (Conv1FuncRet && Conv2FuncRet &&
4016 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4017 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4018 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4019
4020 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4021 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4022
4023 CallingConv CallOpCC =
4024 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4025 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4026 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4027 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4028 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4029
4030 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4031 for (CallingConv CC : PrefOrder) {
4032 if (Conv1CC == CC)
4033 return ImplicitConversionSequence::Better;
4034 if (Conv2CC == CC)
4035 return ImplicitConversionSequence::Worse;
4036 }
4037 }
4038
4039 return ImplicitConversionSequence::Indistinguishable;
4040}
4041
4042static bool hasDeprecatedStringLiteralToCharPtrConversion(
4043 const ImplicitConversionSequence &ICS) {
4044 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4045 (ICS.isUserDefined() &&
4046 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4047}
4048
4049/// CompareImplicitConversionSequences - Compare two implicit
4050/// conversion sequences to determine whether one is better than the
4051/// other or if they are indistinguishable (C++ 13.3.3.2).
4052static ImplicitConversionSequence::CompareKind
4053CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4054 const ImplicitConversionSequence& ICS1,
4055 const ImplicitConversionSequence& ICS2)
4056{
4057 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4058 // conversion sequences (as defined in 13.3.3.1)
4059 // -- a standard conversion sequence (13.3.3.1.1) is a better
4060 // conversion sequence than a user-defined conversion sequence or
4061 // an ellipsis conversion sequence, and
4062 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4063 // conversion sequence than an ellipsis conversion sequence
4064 // (13.3.3.1.3).
4065 //
4066 // C++0x [over.best.ics]p10:
4067 // For the purpose of ranking implicit conversion sequences as
4068 // described in 13.3.3.2, the ambiguous conversion sequence is
4069 // treated as a user-defined sequence that is indistinguishable
4070 // from any other user-defined conversion sequence.
4071
4072 // String literal to 'char *' conversion has been deprecated in C++03. It has
4073 // been removed from C++11. We still accept this conversion, if it happens at
4074 // the best viable function. Otherwise, this conversion is considered worse
4075 // than ellipsis conversion. Consider this as an extension; this is not in the
4076 // standard. For example:
4077 //
4078 // int &f(...); // #1
4079 // void f(char*); // #2
4080 // void g() { int &r = f("foo"); }
4081 //
4082 // In C++03, we pick #2 as the best viable function.
4083 // In C++11, we pick #1 as the best viable function, because ellipsis
4084 // conversion is better than string-literal to char* conversion (since there
4085 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4086 // convert arguments, #2 would be the best viable function in C++11.
4087 // If the best viable function has this conversion, a warning will be issued
4088 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4089
4090 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4091 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4092 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4093 // Ill-formedness must not differ
4094 ICS1.isBad() == ICS2.isBad())
4095 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4096 ? ImplicitConversionSequence::Worse
4097 : ImplicitConversionSequence::Better;
4098
4099 if (ICS1.getKindRank() < ICS2.getKindRank())
4100 return ImplicitConversionSequence::Better;
4101 if (ICS2.getKindRank() < ICS1.getKindRank())
4102 return ImplicitConversionSequence::Worse;
4103
4104 // The following checks require both conversion sequences to be of
4105 // the same kind.
4106 if (ICS1.getKind() != ICS2.getKind())
4107 return ImplicitConversionSequence::Indistinguishable;
4108
4109 ImplicitConversionSequence::CompareKind Result =
4110 ImplicitConversionSequence::Indistinguishable;
4111
4112 // Two implicit conversion sequences of the same form are
4113 // indistinguishable conversion sequences unless one of the
4114 // following rules apply: (C++ 13.3.3.2p3):
4115
4116 // List-initialization sequence L1 is a better conversion sequence than
4117 // list-initialization sequence L2 if:
4118 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4119 // if not that,
4120 // — L1 and L2 convert to arrays of the same element type, and either the
4121 // number of elements n_1 initialized by L1 is less than the number of
4122 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4123 // an array of unknown bound and L1 does not,
4124 // even if one of the other rules in this paragraph would otherwise apply.
4125 if (!ICS1.isBad()) {
4126 bool StdInit1 = false, StdInit2 = false;
4127 if (ICS1.hasInitializerListContainerType())
4128 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4129 Element: nullptr);
4130 if (ICS2.hasInitializerListContainerType())
4131 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4132 Element: nullptr);
4133 if (StdInit1 != StdInit2)
4134 return StdInit1 ? ImplicitConversionSequence::Better
4135 : ImplicitConversionSequence::Worse;
4136
4137 if (ICS1.hasInitializerListContainerType() &&
4138 ICS2.hasInitializerListContainerType())
4139 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4140 T: ICS1.getInitializerListContainerType()))
4141 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4142 T: ICS2.getInitializerListContainerType())) {
4143 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4144 T2: CAT2->getElementType())) {
4145 // Both to arrays of the same element type
4146 if (CAT1->getSize() != CAT2->getSize())
4147 // Different sized, the smaller wins
4148 return CAT1->getSize().ult(RHS: CAT2->getSize())
4149 ? ImplicitConversionSequence::Better
4150 : ImplicitConversionSequence::Worse;
4151 if (ICS1.isInitializerListOfIncompleteArray() !=
4152 ICS2.isInitializerListOfIncompleteArray())
4153 // One is incomplete, it loses
4154 return ICS2.isInitializerListOfIncompleteArray()
4155 ? ImplicitConversionSequence::Better
4156 : ImplicitConversionSequence::Worse;
4157 }
4158 }
4159 }
4160
4161 if (ICS1.isStandard())
4162 // Standard conversion sequence S1 is a better conversion sequence than
4163 // standard conversion sequence S2 if [...]
4164 Result = CompareStandardConversionSequences(S, Loc,
4165 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4166 else if (ICS1.isUserDefined()) {
4167 // User-defined conversion sequence U1 is a better conversion
4168 // sequence than another user-defined conversion sequence U2 if
4169 // they contain the same user-defined conversion function or
4170 // constructor and if the second standard conversion sequence of
4171 // U1 is better than the second standard conversion sequence of
4172 // U2 (C++ 13.3.3.2p3).
4173 if (ICS1.UserDefined.ConversionFunction ==
4174 ICS2.UserDefined.ConversionFunction)
4175 Result = CompareStandardConversionSequences(S, Loc,
4176 SCS1: ICS1.UserDefined.After,
4177 SCS2: ICS2.UserDefined.After);
4178 else
4179 Result = compareConversionFunctions(S,
4180 Function1: ICS1.UserDefined.ConversionFunction,
4181 Function2: ICS2.UserDefined.ConversionFunction);
4182 }
4183
4184 return Result;
4185}
4186
4187// Per 13.3.3.2p3, compare the given standard conversion sequences to
4188// determine if one is a proper subset of the other.
4189static ImplicitConversionSequence::CompareKind
4190compareStandardConversionSubsets(ASTContext &Context,
4191 const StandardConversionSequence& SCS1,
4192 const StandardConversionSequence& SCS2) {
4193 ImplicitConversionSequence::CompareKind Result
4194 = ImplicitConversionSequence::Indistinguishable;
4195
4196 // the identity conversion sequence is considered to be a subsequence of
4197 // any non-identity conversion sequence
4198 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4199 return ImplicitConversionSequence::Better;
4200 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4201 return ImplicitConversionSequence::Worse;
4202
4203 if (SCS1.Second != SCS2.Second) {
4204 if (SCS1.Second == ICK_Identity)
4205 Result = ImplicitConversionSequence::Better;
4206 else if (SCS2.Second == ICK_Identity)
4207 Result = ImplicitConversionSequence::Worse;
4208 else
4209 return ImplicitConversionSequence::Indistinguishable;
4210 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4211 return ImplicitConversionSequence::Indistinguishable;
4212
4213 if (SCS1.Third == SCS2.Third) {
4214 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4215 : ImplicitConversionSequence::Indistinguishable;
4216 }
4217
4218 if (SCS1.Third == ICK_Identity)
4219 return Result == ImplicitConversionSequence::Worse
4220 ? ImplicitConversionSequence::Indistinguishable
4221 : ImplicitConversionSequence::Better;
4222
4223 if (SCS2.Third == ICK_Identity)
4224 return Result == ImplicitConversionSequence::Better
4225 ? ImplicitConversionSequence::Indistinguishable
4226 : ImplicitConversionSequence::Worse;
4227
4228 return ImplicitConversionSequence::Indistinguishable;
4229}
4230
4231/// Determine whether one of the given reference bindings is better
4232/// than the other based on what kind of bindings they are.
4233static bool
4234isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4235 const StandardConversionSequence &SCS2) {
4236 // C++0x [over.ics.rank]p3b4:
4237 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4238 // implicit object parameter of a non-static member function declared
4239 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4240 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4241 // lvalue reference to a function lvalue and S2 binds an rvalue
4242 // reference*.
4243 //
4244 // FIXME: Rvalue references. We're going rogue with the above edits,
4245 // because the semantics in the current C++0x working paper (N3225 at the
4246 // time of this writing) break the standard definition of std::forward
4247 // and std::reference_wrapper when dealing with references to functions.
4248 // Proposed wording changes submitted to CWG for consideration.
4249 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4250 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4251 return false;
4252
4253 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4254 SCS2.IsLvalueReference) ||
4255 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4256 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4257}
4258
4259enum class FixedEnumPromotion {
4260 None,
4261 ToUnderlyingType,
4262 ToPromotedUnderlyingType
4263};
4264
4265/// Returns kind of fixed enum promotion the \a SCS uses.
4266static FixedEnumPromotion
4267getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4268
4269 if (SCS.Second != ICK_Integral_Promotion)
4270 return FixedEnumPromotion::None;
4271
4272 QualType FromType = SCS.getFromType();
4273 if (!FromType->isEnumeralType())
4274 return FixedEnumPromotion::None;
4275
4276 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4277 if (!Enum->isFixed())
4278 return FixedEnumPromotion::None;
4279
4280 QualType UnderlyingType = Enum->getIntegerType();
4281 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4282 return FixedEnumPromotion::ToUnderlyingType;
4283
4284 return FixedEnumPromotion::ToPromotedUnderlyingType;
4285}
4286
4287/// CompareStandardConversionSequences - Compare two standard
4288/// conversion sequences to determine whether one is better than the
4289/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4290static ImplicitConversionSequence::CompareKind
4291CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4292 const StandardConversionSequence& SCS1,
4293 const StandardConversionSequence& SCS2)
4294{
4295 // Standard conversion sequence S1 is a better conversion sequence
4296 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4297
4298 // -- S1 is a proper subsequence of S2 (comparing the conversion
4299 // sequences in the canonical form defined by 13.3.3.1.1,
4300 // excluding any Lvalue Transformation; the identity conversion
4301 // sequence is considered to be a subsequence of any
4302 // non-identity conversion sequence) or, if not that,
4303 if (ImplicitConversionSequence::CompareKind CK
4304 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4305 return CK;
4306
4307 // -- the rank of S1 is better than the rank of S2 (by the rules
4308 // defined below), or, if not that,
4309 ImplicitConversionRank Rank1 = SCS1.getRank();
4310 ImplicitConversionRank Rank2 = SCS2.getRank();
4311 if (Rank1 < Rank2)
4312 return ImplicitConversionSequence::Better;
4313 else if (Rank2 < Rank1)
4314 return ImplicitConversionSequence::Worse;
4315
4316 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4317 // are indistinguishable unless one of the following rules
4318 // applies:
4319
4320 // A conversion that is not a conversion of a pointer, or
4321 // pointer to member, to bool is better than another conversion
4322 // that is such a conversion.
4323 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4324 return SCS2.isPointerConversionToBool()
4325 ? ImplicitConversionSequence::Better
4326 : ImplicitConversionSequence::Worse;
4327
4328 // C++14 [over.ics.rank]p4b2:
4329 // This is retroactively applied to C++11 by CWG 1601.
4330 //
4331 // A conversion that promotes an enumeration whose underlying type is fixed
4332 // to its underlying type is better than one that promotes to the promoted
4333 // underlying type, if the two are different.
4334 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4335 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4336 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4337 FEP1 != FEP2)
4338 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4339 ? ImplicitConversionSequence::Better
4340 : ImplicitConversionSequence::Worse;
4341
4342 // C++ [over.ics.rank]p4b2:
4343 //
4344 // If class B is derived directly or indirectly from class A,
4345 // conversion of B* to A* is better than conversion of B* to
4346 // void*, and conversion of A* to void* is better than conversion
4347 // of B* to void*.
4348 bool SCS1ConvertsToVoid
4349 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4350 bool SCS2ConvertsToVoid
4351 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4352 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4353 // Exactly one of the conversion sequences is a conversion to
4354 // a void pointer; it's the worse conversion.
4355 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4356 : ImplicitConversionSequence::Worse;
4357 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4358 // Neither conversion sequence converts to a void pointer; compare
4359 // their derived-to-base conversions.
4360 if (ImplicitConversionSequence::CompareKind DerivedCK
4361 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4362 return DerivedCK;
4363 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4364 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4365 // Both conversion sequences are conversions to void
4366 // pointers. Compare the source types to determine if there's an
4367 // inheritance relationship in their sources.
4368 QualType FromType1 = SCS1.getFromType();
4369 QualType FromType2 = SCS2.getFromType();
4370
4371 // Adjust the types we're converting from via the array-to-pointer
4372 // conversion, if we need to.
4373 if (SCS1.First == ICK_Array_To_Pointer)
4374 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4375 if (SCS2.First == ICK_Array_To_Pointer)
4376 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4377
4378 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4379 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4380
4381 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4382 return ImplicitConversionSequence::Better;
4383 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4384 return ImplicitConversionSequence::Worse;
4385
4386 // Objective-C++: If one interface is more specific than the
4387 // other, it is the better one.
4388 const ObjCObjectPointerType* FromObjCPtr1
4389 = FromType1->getAs<ObjCObjectPointerType>();
4390 const ObjCObjectPointerType* FromObjCPtr2
4391 = FromType2->getAs<ObjCObjectPointerType>();
4392 if (FromObjCPtr1 && FromObjCPtr2) {
4393 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4394 RHSOPT: FromObjCPtr2);
4395 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4396 RHSOPT: FromObjCPtr1);
4397 if (AssignLeft != AssignRight) {
4398 return AssignLeft? ImplicitConversionSequence::Better
4399 : ImplicitConversionSequence::Worse;
4400 }
4401 }
4402 }
4403
4404 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4405 // Check for a better reference binding based on the kind of bindings.
4406 if (isBetterReferenceBindingKind(SCS1, SCS2))
4407 return ImplicitConversionSequence::Better;
4408 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4409 return ImplicitConversionSequence::Worse;
4410 }
4411
4412 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4413 // bullet 3).
4414 if (ImplicitConversionSequence::CompareKind QualCK
4415 = CompareQualificationConversions(S, SCS1, SCS2))
4416 return QualCK;
4417
4418 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4419 // C++ [over.ics.rank]p3b4:
4420 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4421 // which the references refer are the same type except for
4422 // top-level cv-qualifiers, and the type to which the reference
4423 // initialized by S2 refers is more cv-qualified than the type
4424 // to which the reference initialized by S1 refers.
4425 QualType T1 = SCS1.getToType(Idx: 2);
4426 QualType T2 = SCS2.getToType(Idx: 2);
4427 T1 = S.Context.getCanonicalType(T: T1);
4428 T2 = S.Context.getCanonicalType(T: T2);
4429 Qualifiers T1Quals, T2Quals;
4430 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4431 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4432 if (UnqualT1 == UnqualT2) {
4433 // Objective-C++ ARC: If the references refer to objects with different
4434 // lifetimes, prefer bindings that don't change lifetime.
4435 if (SCS1.ObjCLifetimeConversionBinding !=
4436 SCS2.ObjCLifetimeConversionBinding) {
4437 return SCS1.ObjCLifetimeConversionBinding
4438 ? ImplicitConversionSequence::Worse
4439 : ImplicitConversionSequence::Better;
4440 }
4441
4442 // If the type is an array type, promote the element qualifiers to the
4443 // type for comparison.
4444 if (isa<ArrayType>(Val: T1) && T1Quals)
4445 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4446 if (isa<ArrayType>(Val: T2) && T2Quals)
4447 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4448 if (T2.isMoreQualifiedThan(other: T1))
4449 return ImplicitConversionSequence::Better;
4450 if (T1.isMoreQualifiedThan(other: T2))
4451 return ImplicitConversionSequence::Worse;
4452 }
4453 }
4454
4455 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4456 // floating-to-integral conversion if the integral conversion
4457 // is between types of the same size.
4458 // For example:
4459 // void f(float);
4460 // void f(int);
4461 // int main {
4462 // long a;
4463 // f(a);
4464 // }
4465 // Here, MSVC will call f(int) instead of generating a compile error
4466 // as clang will do in standard mode.
4467 if (S.getLangOpts().MSVCCompat &&
4468 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4469 SCS1.Second == ICK_Integral_Conversion &&
4470 SCS2.Second == ICK_Floating_Integral &&
4471 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4472 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4473 return ImplicitConversionSequence::Better;
4474
4475 // Prefer a compatible vector conversion over a lax vector conversion
4476 // For example:
4477 //
4478 // typedef float __v4sf __attribute__((__vector_size__(16)));
4479 // void f(vector float);
4480 // void f(vector signed int);
4481 // int main() {
4482 // __v4sf a;
4483 // f(a);
4484 // }
4485 // Here, we'd like to choose f(vector float) and not
4486 // report an ambiguous call error
4487 if (SCS1.Second == ICK_Vector_Conversion &&
4488 SCS2.Second == ICK_Vector_Conversion) {
4489 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4490 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4491 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4492 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4493
4494 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4495 return SCS1IsCompatibleVectorConversion
4496 ? ImplicitConversionSequence::Better
4497 : ImplicitConversionSequence::Worse;
4498 }
4499
4500 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4501 SCS2.Second == ICK_SVE_Vector_Conversion) {
4502 bool SCS1IsCompatibleSVEVectorConversion =
4503 S.Context.areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4504 bool SCS2IsCompatibleSVEVectorConversion =
4505 S.Context.areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4506
4507 if (SCS1IsCompatibleSVEVectorConversion !=
4508 SCS2IsCompatibleSVEVectorConversion)
4509 return SCS1IsCompatibleSVEVectorConversion
4510 ? ImplicitConversionSequence::Better
4511 : ImplicitConversionSequence::Worse;
4512 }
4513
4514 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4515 SCS2.Second == ICK_RVV_Vector_Conversion) {
4516 bool SCS1IsCompatibleRVVVectorConversion =
4517 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4518 bool SCS2IsCompatibleRVVVectorConversion =
4519 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4520
4521 if (SCS1IsCompatibleRVVVectorConversion !=
4522 SCS2IsCompatibleRVVVectorConversion)
4523 return SCS1IsCompatibleRVVVectorConversion
4524 ? ImplicitConversionSequence::Better
4525 : ImplicitConversionSequence::Worse;
4526 }
4527 return ImplicitConversionSequence::Indistinguishable;
4528}
4529
4530/// CompareQualificationConversions - Compares two standard conversion
4531/// sequences to determine whether they can be ranked based on their
4532/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4533static ImplicitConversionSequence::CompareKind
4534CompareQualificationConversions(Sema &S,
4535 const StandardConversionSequence& SCS1,
4536 const StandardConversionSequence& SCS2) {
4537 // C++ [over.ics.rank]p3:
4538 // -- S1 and S2 differ only in their qualification conversion and
4539 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4540 // [C++98]
4541 // [...] and the cv-qualification signature of type T1 is a proper subset
4542 // of the cv-qualification signature of type T2, and S1 is not the
4543 // deprecated string literal array-to-pointer conversion (4.2).
4544 // [C++2a]
4545 // [...] where T1 can be converted to T2 by a qualification conversion.
4546 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4547 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4548 return ImplicitConversionSequence::Indistinguishable;
4549
4550 // FIXME: the example in the standard doesn't use a qualification
4551 // conversion (!)
4552 QualType T1 = SCS1.getToType(Idx: 2);
4553 QualType T2 = SCS2.getToType(Idx: 2);
4554 T1 = S.Context.getCanonicalType(T: T1);
4555 T2 = S.Context.getCanonicalType(T: T2);
4556 assert(!T1->isReferenceType() && !T2->isReferenceType());
4557 Qualifiers T1Quals, T2Quals;
4558 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4559 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4560
4561 // If the types are the same, we won't learn anything by unwrapping
4562 // them.
4563 if (UnqualT1 == UnqualT2)
4564 return ImplicitConversionSequence::Indistinguishable;
4565
4566 // Don't ever prefer a standard conversion sequence that uses the deprecated
4567 // string literal array to pointer conversion.
4568 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4569 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4570
4571 // Objective-C++ ARC:
4572 // Prefer qualification conversions not involving a change in lifetime
4573 // to qualification conversions that do change lifetime.
4574 if (SCS1.QualificationIncludesObjCLifetime &&
4575 !SCS2.QualificationIncludesObjCLifetime)
4576 CanPick1 = false;
4577 if (SCS2.QualificationIncludesObjCLifetime &&
4578 !SCS1.QualificationIncludesObjCLifetime)
4579 CanPick2 = false;
4580
4581 bool ObjCLifetimeConversion;
4582 if (CanPick1 &&
4583 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
4584 CanPick1 = false;
4585 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4586 // directions, so we can't short-cut this second check in general.
4587 if (CanPick2 &&
4588 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
4589 CanPick2 = false;
4590
4591 if (CanPick1 != CanPick2)
4592 return CanPick1 ? ImplicitConversionSequence::Better
4593 : ImplicitConversionSequence::Worse;
4594 return ImplicitConversionSequence::Indistinguishable;
4595}
4596
4597/// CompareDerivedToBaseConversions - Compares two standard conversion
4598/// sequences to determine whether they can be ranked based on their
4599/// various kinds of derived-to-base conversions (C++
4600/// [over.ics.rank]p4b3). As part of these checks, we also look at
4601/// conversions between Objective-C interface types.
4602static ImplicitConversionSequence::CompareKind
4603CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4604 const StandardConversionSequence& SCS1,
4605 const StandardConversionSequence& SCS2) {
4606 QualType FromType1 = SCS1.getFromType();
4607 QualType ToType1 = SCS1.getToType(Idx: 1);
4608 QualType FromType2 = SCS2.getFromType();
4609 QualType ToType2 = SCS2.getToType(Idx: 1);
4610
4611 // Adjust the types we're converting from via the array-to-pointer
4612 // conversion, if we need to.
4613 if (SCS1.First == ICK_Array_To_Pointer)
4614 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4615 if (SCS2.First == ICK_Array_To_Pointer)
4616 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4617
4618 // Canonicalize all of the types.
4619 FromType1 = S.Context.getCanonicalType(T: FromType1);
4620 ToType1 = S.Context.getCanonicalType(T: ToType1);
4621 FromType2 = S.Context.getCanonicalType(T: FromType2);
4622 ToType2 = S.Context.getCanonicalType(T: ToType2);
4623
4624 // C++ [over.ics.rank]p4b3:
4625 //
4626 // If class B is derived directly or indirectly from class A and
4627 // class C is derived directly or indirectly from B,
4628 //
4629 // Compare based on pointer conversions.
4630 if (SCS1.Second == ICK_Pointer_Conversion &&
4631 SCS2.Second == ICK_Pointer_Conversion &&
4632 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4633 FromType1->isPointerType() && FromType2->isPointerType() &&
4634 ToType1->isPointerType() && ToType2->isPointerType()) {
4635 QualType FromPointee1 =
4636 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4637 QualType ToPointee1 =
4638 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4639 QualType FromPointee2 =
4640 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4641 QualType ToPointee2 =
4642 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4643
4644 // -- conversion of C* to B* is better than conversion of C* to A*,
4645 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4646 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4647 return ImplicitConversionSequence::Better;
4648 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4649 return ImplicitConversionSequence::Worse;
4650 }
4651
4652 // -- conversion of B* to A* is better than conversion of C* to A*,
4653 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4654 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4655 return ImplicitConversionSequence::Better;
4656 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4657 return ImplicitConversionSequence::Worse;
4658 }
4659 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4660 SCS2.Second == ICK_Pointer_Conversion) {
4661 const ObjCObjectPointerType *FromPtr1
4662 = FromType1->getAs<ObjCObjectPointerType>();
4663 const ObjCObjectPointerType *FromPtr2
4664 = FromType2->getAs<ObjCObjectPointerType>();
4665 const ObjCObjectPointerType *ToPtr1
4666 = ToType1->getAs<ObjCObjectPointerType>();
4667 const ObjCObjectPointerType *ToPtr2
4668 = ToType2->getAs<ObjCObjectPointerType>();
4669
4670 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4671 // Apply the same conversion ranking rules for Objective-C pointer types
4672 // that we do for C++ pointers to class types. However, we employ the
4673 // Objective-C pseudo-subtyping relationship used for assignment of
4674 // Objective-C pointer types.
4675 bool FromAssignLeft
4676 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
4677 bool FromAssignRight
4678 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
4679 bool ToAssignLeft
4680 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
4681 bool ToAssignRight
4682 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
4683
4684 // A conversion to an a non-id object pointer type or qualified 'id'
4685 // type is better than a conversion to 'id'.
4686 if (ToPtr1->isObjCIdType() &&
4687 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4688 return ImplicitConversionSequence::Worse;
4689 if (ToPtr2->isObjCIdType() &&
4690 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4691 return ImplicitConversionSequence::Better;
4692
4693 // A conversion to a non-id object pointer type is better than a
4694 // conversion to a qualified 'id' type
4695 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4696 return ImplicitConversionSequence::Worse;
4697 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4698 return ImplicitConversionSequence::Better;
4699
4700 // A conversion to an a non-Class object pointer type or qualified 'Class'
4701 // type is better than a conversion to 'Class'.
4702 if (ToPtr1->isObjCClassType() &&
4703 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4704 return ImplicitConversionSequence::Worse;
4705 if (ToPtr2->isObjCClassType() &&
4706 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4707 return ImplicitConversionSequence::Better;
4708
4709 // A conversion to a non-Class object pointer type is better than a
4710 // conversion to a qualified 'Class' type.
4711 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4712 return ImplicitConversionSequence::Worse;
4713 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4714 return ImplicitConversionSequence::Better;
4715
4716 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4717 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
4718 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4719 (ToAssignLeft != ToAssignRight)) {
4720 if (FromPtr1->isSpecialized()) {
4721 // "conversion of B<A> * to B * is better than conversion of B * to
4722 // C *.
4723 bool IsFirstSame =
4724 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4725 bool IsSecondSame =
4726 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4727 if (IsFirstSame) {
4728 if (!IsSecondSame)
4729 return ImplicitConversionSequence::Better;
4730 } else if (IsSecondSame)
4731 return ImplicitConversionSequence::Worse;
4732 }
4733 return ToAssignLeft? ImplicitConversionSequence::Worse
4734 : ImplicitConversionSequence::Better;
4735 }
4736
4737 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4738 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
4739 (FromAssignLeft != FromAssignRight))
4740 return FromAssignLeft? ImplicitConversionSequence::Better
4741 : ImplicitConversionSequence::Worse;
4742 }
4743 }
4744
4745 // Ranking of member-pointer types.
4746 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4747 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4748 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4749 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4750 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4751 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4752 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4753 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4754 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4755 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4756 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4757 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4758 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4759 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4760 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4761 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4762 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4763 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4764 return ImplicitConversionSequence::Worse;
4765 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4766 return ImplicitConversionSequence::Better;
4767 }
4768 // conversion of B::* to C::* is better than conversion of A::* to C::*
4769 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4770 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4771 return ImplicitConversionSequence::Better;
4772 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4773 return ImplicitConversionSequence::Worse;
4774 }
4775 }
4776
4777 if (SCS1.Second == ICK_Derived_To_Base) {
4778 // -- conversion of C to B is better than conversion of C to A,
4779 // -- binding of an expression of type C to a reference of type
4780 // B& is better than binding an expression of type C to a
4781 // reference of type A&,
4782 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
4783 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
4784 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
4785 return ImplicitConversionSequence::Better;
4786 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
4787 return ImplicitConversionSequence::Worse;
4788 }
4789
4790 // -- conversion of B to A is better than conversion of C to A.
4791 // -- binding of an expression of type B to a reference of type
4792 // A& is better than binding an expression of type C to a
4793 // reference of type A&,
4794 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
4795 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
4796 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
4797 return ImplicitConversionSequence::Better;
4798 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
4799 return ImplicitConversionSequence::Worse;
4800 }
4801 }
4802
4803 return ImplicitConversionSequence::Indistinguishable;
4804}
4805
4806static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4807 if (!T.getQualifiers().hasUnaligned())
4808 return T;
4809
4810 Qualifiers Q;
4811 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
4812 Q.removeUnaligned();
4813 return Ctx.getQualifiedType(T, Qs: Q);
4814}
4815
4816Sema::ReferenceCompareResult
4817Sema::CompareReferenceRelationship(SourceLocation Loc,
4818 QualType OrigT1, QualType OrigT2,
4819 ReferenceConversions *ConvOut) {
4820 assert(!OrigT1->isReferenceType() &&
4821 "T1 must be the pointee type of the reference type");
4822 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4823
4824 QualType T1 = Context.getCanonicalType(T: OrigT1);
4825 QualType T2 = Context.getCanonicalType(T: OrigT2);
4826 Qualifiers T1Quals, T2Quals;
4827 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4828 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4829
4830 ReferenceConversions ConvTmp;
4831 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4832 Conv = ReferenceConversions();
4833
4834 // C++2a [dcl.init.ref]p4:
4835 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4836 // reference-related to "cv2 T2" if T1 is similar to T2, or
4837 // T1 is a base class of T2.
4838 // "cv1 T1" is reference-compatible with "cv2 T2" if
4839 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4840 // "pointer to cv1 T1" via a standard conversion sequence.
4841
4842 // Check for standard conversions we can apply to pointers: derived-to-base
4843 // conversions, ObjC pointer conversions, and function pointer conversions.
4844 // (Qualification conversions are checked last.)
4845 QualType ConvertedT2;
4846 if (UnqualT1 == UnqualT2) {
4847 // Nothing to do.
4848 } else if (isCompleteType(Loc, T: OrigT2) &&
4849 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
4850 Conv |= ReferenceConversions::DerivedToBase;
4851 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4852 UnqualT2->isObjCObjectOrInterfaceType() &&
4853 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
4854 Conv |= ReferenceConversions::ObjC;
4855 else if (UnqualT2->isFunctionType() &&
4856 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1, ResultTy&: ConvertedT2)) {
4857 Conv |= ReferenceConversions::Function;
4858 // No need to check qualifiers; function types don't have them.
4859 return Ref_Compatible;
4860 }
4861 bool ConvertedReferent = Conv != 0;
4862
4863 // We can have a qualification conversion. Compute whether the types are
4864 // similar at the same time.
4865 bool PreviousToQualsIncludeConst = true;
4866 bool TopLevel = true;
4867 do {
4868 if (T1 == T2)
4869 break;
4870
4871 // We will need a qualification conversion.
4872 Conv |= ReferenceConversions::Qualification;
4873
4874 // Track whether we performed a qualification conversion anywhere other
4875 // than the top level. This matters for ranking reference bindings in
4876 // overload resolution.
4877 if (!TopLevel)
4878 Conv |= ReferenceConversions::NestedQualification;
4879
4880 // MS compiler ignores __unaligned qualifier for references; do the same.
4881 T1 = withoutUnaligned(Ctx&: Context, T: T1);
4882 T2 = withoutUnaligned(Ctx&: Context, T: T2);
4883
4884 // If we find a qualifier mismatch, the types are not reference-compatible,
4885 // but are still be reference-related if they're similar.
4886 bool ObjCLifetimeConversion = false;
4887 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
4888 PreviousToQualsIncludeConst,
4889 ObjCLifetimeConversion))
4890 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4891 ? Ref_Related
4892 : Ref_Incompatible;
4893
4894 // FIXME: Should we track this for any level other than the first?
4895 if (ObjCLifetimeConversion)
4896 Conv |= ReferenceConversions::ObjCLifetime;
4897
4898 TopLevel = false;
4899 } while (Context.UnwrapSimilarTypes(T1, T2));
4900
4901 // At this point, if the types are reference-related, we must either have the
4902 // same inner type (ignoring qualifiers), or must have already worked out how
4903 // to convert the referent.
4904 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4905 ? Ref_Compatible
4906 : Ref_Incompatible;
4907}
4908
4909/// Look for a user-defined conversion to a value reference-compatible
4910/// with DeclType. Return true if something definite is found.
4911static bool
4912FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4913 QualType DeclType, SourceLocation DeclLoc,
4914 Expr *Init, QualType T2, bool AllowRvalues,
4915 bool AllowExplicit) {
4916 assert(T2->isRecordType() && "Can only find conversions of record types.");
4917 auto *T2RecordDecl = cast<CXXRecordDecl>(Val: T2->castAs<RecordType>()->getDecl());
4918
4919 OverloadCandidateSet CandidateSet(
4920 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4921 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4922 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4923 NamedDecl *D = *I;
4924 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
4925 if (isa<UsingShadowDecl>(Val: D))
4926 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4927
4928 FunctionTemplateDecl *ConvTemplate
4929 = dyn_cast<FunctionTemplateDecl>(Val: D);
4930 CXXConversionDecl *Conv;
4931 if (ConvTemplate)
4932 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4933 else
4934 Conv = cast<CXXConversionDecl>(Val: D);
4935
4936 if (AllowRvalues) {
4937 // If we are initializing an rvalue reference, don't permit conversion
4938 // functions that return lvalues.
4939 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4940 const ReferenceType *RefType
4941 = Conv->getConversionType()->getAs<LValueReferenceType>();
4942 if (RefType && !RefType->getPointeeType()->isFunctionType())
4943 continue;
4944 }
4945
4946 if (!ConvTemplate &&
4947 S.CompareReferenceRelationship(
4948 Loc: DeclLoc,
4949 OrigT1: Conv->getConversionType()
4950 .getNonReferenceType()
4951 .getUnqualifiedType(),
4952 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
4953 Sema::Ref_Incompatible)
4954 continue;
4955 } else {
4956 // If the conversion function doesn't return a reference type,
4957 // it can't be considered for this conversion. An rvalue reference
4958 // is only acceptable if its referencee is a function type.
4959
4960 const ReferenceType *RefType =
4961 Conv->getConversionType()->getAs<ReferenceType>();
4962 if (!RefType ||
4963 (!RefType->isLValueReferenceType() &&
4964 !RefType->getPointeeType()->isFunctionType()))
4965 continue;
4966 }
4967
4968 if (ConvTemplate)
4969 S.AddTemplateConversionCandidate(
4970 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
4971 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4972 else
4973 S.AddConversionCandidate(
4974 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
4975 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4976 }
4977
4978 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4979
4980 OverloadCandidateSet::iterator Best;
4981 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
4982 case OR_Success:
4983 // C++ [over.ics.ref]p1:
4984 //
4985 // [...] If the parameter binds directly to the result of
4986 // applying a conversion function to the argument
4987 // expression, the implicit conversion sequence is a
4988 // user-defined conversion sequence (13.3.3.1.2), with the
4989 // second standard conversion sequence either an identity
4990 // conversion or, if the conversion function returns an
4991 // entity of a type that is a derived class of the parameter
4992 // type, a derived-to-base Conversion.
4993 if (!Best->FinalConversion.DirectBinding)
4994 return false;
4995
4996 ICS.setUserDefined();
4997 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4998 ICS.UserDefined.After = Best->FinalConversion;
4999 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5000 ICS.UserDefined.ConversionFunction = Best->Function;
5001 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5002 ICS.UserDefined.EllipsisConversion = false;
5003 assert(ICS.UserDefined.After.ReferenceBinding &&
5004 ICS.UserDefined.After.DirectBinding &&
5005 "Expected a direct reference binding!");
5006 return true;
5007
5008 case OR_Ambiguous:
5009 ICS.setAmbiguous();
5010 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5011 Cand != CandidateSet.end(); ++Cand)
5012 if (Cand->Best)
5013 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5014 return true;
5015
5016 case OR_No_Viable_Function:
5017 case OR_Deleted:
5018 // There was no suitable conversion, or we found a deleted
5019 // conversion; continue with other checks.
5020 return false;
5021 }
5022
5023 llvm_unreachable("Invalid OverloadResult!");
5024}
5025
5026/// Compute an implicit conversion sequence for reference
5027/// initialization.
5028static ImplicitConversionSequence
5029TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5030 SourceLocation DeclLoc,
5031 bool SuppressUserConversions,
5032 bool AllowExplicit) {
5033 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5034
5035 // Most paths end in a failed conversion.
5036 ImplicitConversionSequence ICS;
5037 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5038
5039 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5040 QualType T2 = Init->getType();
5041
5042 // If the initializer is the address of an overloaded function, try
5043 // to resolve the overloaded function. If all goes well, T2 is the
5044 // type of the resulting function.
5045 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5046 DeclAccessPair Found;
5047 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5048 Complain: false, Found))
5049 T2 = Fn->getType();
5050 }
5051
5052 // Compute some basic properties of the types and the initializer.
5053 bool isRValRef = DeclType->isRValueReferenceType();
5054 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5055
5056 Sema::ReferenceConversions RefConv;
5057 Sema::ReferenceCompareResult RefRelationship =
5058 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5059
5060 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5061 ICS.setStandard();
5062 ICS.Standard.First = ICK_Identity;
5063 // FIXME: A reference binding can be a function conversion too. We should
5064 // consider that when ordering reference-to-function bindings.
5065 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5066 ? ICK_Derived_To_Base
5067 : (RefConv & Sema::ReferenceConversions::ObjC)
5068 ? ICK_Compatible_Conversion
5069 : ICK_Identity;
5070 ICS.Standard.Dimension = ICK_Identity;
5071 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5072 // a reference binding that performs a non-top-level qualification
5073 // conversion as a qualification conversion, not as an identity conversion.
5074 ICS.Standard.Third = (RefConv &
5075 Sema::ReferenceConversions::NestedQualification)
5076 ? ICK_Qualification
5077 : ICK_Identity;
5078 ICS.Standard.setFromType(T2);
5079 ICS.Standard.setToType(Idx: 0, T: T2);
5080 ICS.Standard.setToType(Idx: 1, T: T1);
5081 ICS.Standard.setToType(Idx: 2, T: T1);
5082 ICS.Standard.ReferenceBinding = true;
5083 ICS.Standard.DirectBinding = BindsDirectly;
5084 ICS.Standard.IsLvalueReference = !isRValRef;
5085 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5086 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5087 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5088 ICS.Standard.ObjCLifetimeConversionBinding =
5089 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5090 ICS.Standard.CopyConstructor = nullptr;
5091 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5092 };
5093
5094 // C++0x [dcl.init.ref]p5:
5095 // A reference to type "cv1 T1" is initialized by an expression
5096 // of type "cv2 T2" as follows:
5097
5098 // -- If reference is an lvalue reference and the initializer expression
5099 if (!isRValRef) {
5100 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5101 // reference-compatible with "cv2 T2," or
5102 //
5103 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5104 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5105 // C++ [over.ics.ref]p1:
5106 // When a parameter of reference type binds directly (8.5.3)
5107 // to an argument expression, the implicit conversion sequence
5108 // is the identity conversion, unless the argument expression
5109 // has a type that is a derived class of the parameter type,
5110 // in which case the implicit conversion sequence is a
5111 // derived-to-base Conversion (13.3.3.1).
5112 SetAsReferenceBinding(/*BindsDirectly=*/true);
5113
5114 // Nothing more to do: the inaccessibility/ambiguity check for
5115 // derived-to-base conversions is suppressed when we're
5116 // computing the implicit conversion sequence (C++
5117 // [over.best.ics]p2).
5118 return ICS;
5119 }
5120
5121 // -- has a class type (i.e., T2 is a class type), where T1 is
5122 // not reference-related to T2, and can be implicitly
5123 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5124 // is reference-compatible with "cv3 T3" 92) (this
5125 // conversion is selected by enumerating the applicable
5126 // conversion functions (13.3.1.6) and choosing the best
5127 // one through overload resolution (13.3)),
5128 if (!SuppressUserConversions && T2->isRecordType() &&
5129 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5130 RefRelationship == Sema::Ref_Incompatible) {
5131 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5132 Init, T2, /*AllowRvalues=*/false,
5133 AllowExplicit))
5134 return ICS;
5135 }
5136 }
5137
5138 // -- Otherwise, the reference shall be an lvalue reference to a
5139 // non-volatile const type (i.e., cv1 shall be const), or the reference
5140 // shall be an rvalue reference.
5141 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5142 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5143 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5144 return ICS;
5145 }
5146
5147 // -- If the initializer expression
5148 //
5149 // -- is an xvalue, class prvalue, array prvalue or function
5150 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5151 if (RefRelationship == Sema::Ref_Compatible &&
5152 (InitCategory.isXValue() ||
5153 (InitCategory.isPRValue() &&
5154 (T2->isRecordType() || T2->isArrayType())) ||
5155 (InitCategory.isLValue() && T2->isFunctionType()))) {
5156 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5157 // binding unless we're binding to a class prvalue.
5158 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5159 // allow the use of rvalue references in C++98/03 for the benefit of
5160 // standard library implementors; therefore, we need the xvalue check here.
5161 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5162 !(InitCategory.isPRValue() || T2->isRecordType()));
5163 return ICS;
5164 }
5165
5166 // -- has a class type (i.e., T2 is a class type), where T1 is not
5167 // reference-related to T2, and can be implicitly converted to
5168 // an xvalue, class prvalue, or function lvalue of type
5169 // "cv3 T3", where "cv1 T1" is reference-compatible with
5170 // "cv3 T3",
5171 //
5172 // then the reference is bound to the value of the initializer
5173 // expression in the first case and to the result of the conversion
5174 // in the second case (or, in either case, to an appropriate base
5175 // class subobject).
5176 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5177 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5178 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5179 Init, T2, /*AllowRvalues=*/true,
5180 AllowExplicit)) {
5181 // In the second case, if the reference is an rvalue reference
5182 // and the second standard conversion sequence of the
5183 // user-defined conversion sequence includes an lvalue-to-rvalue
5184 // conversion, the program is ill-formed.
5185 if (ICS.isUserDefined() && isRValRef &&
5186 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5187 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5188
5189 return ICS;
5190 }
5191
5192 // A temporary of function type cannot be created; don't even try.
5193 if (T1->isFunctionType())
5194 return ICS;
5195
5196 // -- Otherwise, a temporary of type "cv1 T1" is created and
5197 // initialized from the initializer expression using the
5198 // rules for a non-reference copy initialization (8.5). The
5199 // reference is then bound to the temporary. If T1 is
5200 // reference-related to T2, cv1 must be the same
5201 // cv-qualification as, or greater cv-qualification than,
5202 // cv2; otherwise, the program is ill-formed.
5203 if (RefRelationship == Sema::Ref_Related) {
5204 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5205 // we would be reference-compatible or reference-compatible with
5206 // added qualification. But that wasn't the case, so the reference
5207 // initialization fails.
5208 //
5209 // Note that we only want to check address spaces and cvr-qualifiers here.
5210 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5211 Qualifiers T1Quals = T1.getQualifiers();
5212 Qualifiers T2Quals = T2.getQualifiers();
5213 T1Quals.removeObjCGCAttr();
5214 T1Quals.removeObjCLifetime();
5215 T2Quals.removeObjCGCAttr();
5216 T2Quals.removeObjCLifetime();
5217 // MS compiler ignores __unaligned qualifier for references; do the same.
5218 T1Quals.removeUnaligned();
5219 T2Quals.removeUnaligned();
5220 if (!T1Quals.compatiblyIncludes(other: T2Quals))
5221 return ICS;
5222 }
5223
5224 // If at least one of the types is a class type, the types are not
5225 // related, and we aren't allowed any user conversions, the
5226 // reference binding fails. This case is important for breaking
5227 // recursion, since TryImplicitConversion below will attempt to
5228 // create a temporary through the use of a copy constructor.
5229 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5230 (T1->isRecordType() || T2->isRecordType()))
5231 return ICS;
5232
5233 // If T1 is reference-related to T2 and the reference is an rvalue
5234 // reference, the initializer expression shall not be an lvalue.
5235 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5236 Init->Classify(Ctx&: S.Context).isLValue()) {
5237 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5238 return ICS;
5239 }
5240
5241 // C++ [over.ics.ref]p2:
5242 // When a parameter of reference type is not bound directly to
5243 // an argument expression, the conversion sequence is the one
5244 // required to convert the argument expression to the
5245 // underlying type of the reference according to
5246 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5247 // to copy-initializing a temporary of the underlying type with
5248 // the argument expression. Any difference in top-level
5249 // cv-qualification is subsumed by the initialization itself
5250 // and does not constitute a conversion.
5251 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5252 AllowExplicit: AllowedExplicit::None,
5253 /*InOverloadResolution=*/false,
5254 /*CStyle=*/false,
5255 /*AllowObjCWritebackConversion=*/false,
5256 /*AllowObjCConversionOnExplicit=*/false);
5257
5258 // Of course, that's still a reference binding.
5259 if (ICS.isStandard()) {
5260 ICS.Standard.ReferenceBinding = true;
5261 ICS.Standard.IsLvalueReference = !isRValRef;
5262 ICS.Standard.BindsToFunctionLvalue = false;
5263 ICS.Standard.BindsToRvalue = true;
5264 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5265 ICS.Standard.ObjCLifetimeConversionBinding = false;
5266 } else if (ICS.isUserDefined()) {
5267 const ReferenceType *LValRefType =
5268 ICS.UserDefined.ConversionFunction->getReturnType()
5269 ->getAs<LValueReferenceType>();
5270
5271 // C++ [over.ics.ref]p3:
5272 // Except for an implicit object parameter, for which see 13.3.1, a
5273 // standard conversion sequence cannot be formed if it requires [...]
5274 // binding an rvalue reference to an lvalue other than a function
5275 // lvalue.
5276 // Note that the function case is not possible here.
5277 if (isRValRef && LValRefType) {
5278 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5279 return ICS;
5280 }
5281
5282 ICS.UserDefined.After.ReferenceBinding = true;
5283 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5284 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5285 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5286 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5287 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5288 }
5289
5290 return ICS;
5291}
5292
5293static ImplicitConversionSequence
5294TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5295 bool SuppressUserConversions,
5296 bool InOverloadResolution,
5297 bool AllowObjCWritebackConversion,
5298 bool AllowExplicit = false);
5299
5300/// TryListConversion - Try to copy-initialize a value of type ToType from the
5301/// initializer list From.
5302static ImplicitConversionSequence
5303TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5304 bool SuppressUserConversions,
5305 bool InOverloadResolution,
5306 bool AllowObjCWritebackConversion) {
5307 // C++11 [over.ics.list]p1:
5308 // When an argument is an initializer list, it is not an expression and
5309 // special rules apply for converting it to a parameter type.
5310
5311 ImplicitConversionSequence Result;
5312 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5313
5314 // We need a complete type for what follows. With one C++20 exception,
5315 // incomplete types can never be initialized from init lists.
5316 QualType InitTy = ToType;
5317 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5318 if (AT && S.getLangOpts().CPlusPlus20)
5319 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5320 // C++20 allows list initialization of an incomplete array type.
5321 InitTy = IAT->getElementType();
5322 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5323 return Result;
5324
5325 // C++20 [over.ics.list]/2:
5326 // If the initializer list is a designated-initializer-list, a conversion
5327 // is only possible if the parameter has an aggregate type
5328 //
5329 // FIXME: The exception for reference initialization here is not part of the
5330 // language rules, but follow other compilers in adding it as a tentative DR
5331 // resolution.
5332 bool IsDesignatedInit = From->hasDesignatedInit();
5333 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5334 IsDesignatedInit)
5335 return Result;
5336
5337 // Per DR1467:
5338 // If the parameter type is a class X and the initializer list has a single
5339 // element of type cv U, where U is X or a class derived from X, the
5340 // implicit conversion sequence is the one required to convert the element
5341 // to the parameter type.
5342 //
5343 // Otherwise, if the parameter type is a character array [... ]
5344 // and the initializer list has a single element that is an
5345 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5346 // implicit conversion sequence is the identity conversion.
5347 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5348 if (ToType->isRecordType()) {
5349 QualType InitType = From->getInit(Init: 0)->getType();
5350 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5351 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5352 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5353 SuppressUserConversions,
5354 InOverloadResolution,
5355 AllowObjCWritebackConversion);
5356 }
5357
5358 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5359 InitializedEntity Entity =
5360 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5361 /*Consumed=*/false);
5362 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5363 Result.setStandard();
5364 Result.Standard.setAsIdentityConversion();
5365 Result.Standard.setFromType(ToType);
5366 Result.Standard.setAllToTypes(ToType);
5367 return Result;
5368 }
5369 }
5370 }
5371
5372 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5373 // C++11 [over.ics.list]p2:
5374 // If the parameter type is std::initializer_list<X> or "array of X" and
5375 // all the elements can be implicitly converted to X, the implicit
5376 // conversion sequence is the worst conversion necessary to convert an
5377 // element of the list to X.
5378 //
5379 // C++14 [over.ics.list]p3:
5380 // Otherwise, if the parameter type is "array of N X", if the initializer
5381 // list has exactly N elements or if it has fewer than N elements and X is
5382 // default-constructible, and if all the elements of the initializer list
5383 // can be implicitly converted to X, the implicit conversion sequence is
5384 // the worst conversion necessary to convert an element of the list to X.
5385 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5386 unsigned e = From->getNumInits();
5387 ImplicitConversionSequence DfltElt;
5388 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5389 ToType: QualType());
5390 QualType ContTy = ToType;
5391 bool IsUnbounded = false;
5392 if (AT) {
5393 InitTy = AT->getElementType();
5394 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5395 if (CT->getSize().ult(RHS: e)) {
5396 // Too many inits, fatally bad
5397 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5398 ToType);
5399 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5400 return Result;
5401 }
5402 if (CT->getSize().ugt(RHS: e)) {
5403 // Need an init from empty {}, is there one?
5404 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5405 From->getEndLoc());
5406 EmptyList.setType(S.Context.VoidTy);
5407 DfltElt = TryListConversion(
5408 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5409 InOverloadResolution, AllowObjCWritebackConversion);
5410 if (DfltElt.isBad()) {
5411 // No {} init, fatally bad
5412 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5413 ToType);
5414 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5415 return Result;
5416 }
5417 }
5418 } else {
5419 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5420 IsUnbounded = true;
5421 if (!e) {
5422 // Cannot convert to zero-sized.
5423 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5424 ToType);
5425 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5426 return Result;
5427 }
5428 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5429 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5430 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5431 }
5432 }
5433
5434 Result.setStandard();
5435 Result.Standard.setAsIdentityConversion();
5436 Result.Standard.setFromType(InitTy);
5437 Result.Standard.setAllToTypes(InitTy);
5438 for (unsigned i = 0; i < e; ++i) {
5439 Expr *Init = From->getInit(Init: i);
5440 ImplicitConversionSequence ICS = TryCopyInitialization(
5441 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5442 AllowObjCWritebackConversion);
5443
5444 // Keep the worse conversion seen so far.
5445 // FIXME: Sequences are not totally ordered, so 'worse' can be
5446 // ambiguous. CWG has been informed.
5447 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5448 ICS2: Result) ==
5449 ImplicitConversionSequence::Worse) {
5450 Result = ICS;
5451 // Bail as soon as we find something unconvertible.
5452 if (Result.isBad()) {
5453 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5454 return Result;
5455 }
5456 }
5457 }
5458
5459 // If we needed any implicit {} initialization, compare that now.
5460 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5461 // has been informed that this might not be the best thing.
5462 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5463 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5464 ImplicitConversionSequence::Worse)
5465 Result = DfltElt;
5466 // Record the type being initialized so that we may compare sequences
5467 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5468 return Result;
5469 }
5470
5471 // C++14 [over.ics.list]p4:
5472 // C++11 [over.ics.list]p3:
5473 // Otherwise, if the parameter is a non-aggregate class X and overload
5474 // resolution chooses a single best constructor [...] the implicit
5475 // conversion sequence is a user-defined conversion sequence. If multiple
5476 // constructors are viable but none is better than the others, the
5477 // implicit conversion sequence is a user-defined conversion sequence.
5478 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5479 // This function can deal with initializer lists.
5480 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5481 AllowExplicit: AllowedExplicit::None,
5482 InOverloadResolution, /*CStyle=*/false,
5483 AllowObjCWritebackConversion,
5484 /*AllowObjCConversionOnExplicit=*/false);
5485 }
5486
5487 // C++14 [over.ics.list]p5:
5488 // C++11 [over.ics.list]p4:
5489 // Otherwise, if the parameter has an aggregate type which can be
5490 // initialized from the initializer list [...] the implicit conversion
5491 // sequence is a user-defined conversion sequence.
5492 if (ToType->isAggregateType()) {
5493 // Type is an aggregate, argument is an init list. At this point it comes
5494 // down to checking whether the initialization works.
5495 // FIXME: Find out whether this parameter is consumed or not.
5496 InitializedEntity Entity =
5497 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5498 /*Consumed=*/false);
5499 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5500 From)) {
5501 Result.setUserDefined();
5502 Result.UserDefined.Before.setAsIdentityConversion();
5503 // Initializer lists don't have a type.
5504 Result.UserDefined.Before.setFromType(QualType());
5505 Result.UserDefined.Before.setAllToTypes(QualType());
5506
5507 Result.UserDefined.After.setAsIdentityConversion();
5508 Result.UserDefined.After.setFromType(ToType);
5509 Result.UserDefined.After.setAllToTypes(ToType);
5510 Result.UserDefined.ConversionFunction = nullptr;
5511 }
5512 return Result;
5513 }
5514
5515 // C++14 [over.ics.list]p6:
5516 // C++11 [over.ics.list]p5:
5517 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5518 if (ToType->isReferenceType()) {
5519 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5520 // mention initializer lists in any way. So we go by what list-
5521 // initialization would do and try to extrapolate from that.
5522
5523 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5524
5525 // If the initializer list has a single element that is reference-related
5526 // to the parameter type, we initialize the reference from that.
5527 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5528 Expr *Init = From->getInit(Init: 0);
5529
5530 QualType T2 = Init->getType();
5531
5532 // If the initializer is the address of an overloaded function, try
5533 // to resolve the overloaded function. If all goes well, T2 is the
5534 // type of the resulting function.
5535 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5536 DeclAccessPair Found;
5537 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5538 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5539 T2 = Fn->getType();
5540 }
5541
5542 // Compute some basic properties of the types and the initializer.
5543 Sema::ReferenceCompareResult RefRelationship =
5544 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5545
5546 if (RefRelationship >= Sema::Ref_Related) {
5547 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5548 SuppressUserConversions,
5549 /*AllowExplicit=*/false);
5550 }
5551 }
5552
5553 // Otherwise, we bind the reference to a temporary created from the
5554 // initializer list.
5555 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
5556 InOverloadResolution,
5557 AllowObjCWritebackConversion);
5558 if (Result.isFailure())
5559 return Result;
5560 assert(!Result.isEllipsis() &&
5561 "Sub-initialization cannot result in ellipsis conversion.");
5562
5563 // Can we even bind to a temporary?
5564 if (ToType->isRValueReferenceType() ||
5565 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5566 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5567 Result.UserDefined.After;
5568 SCS.ReferenceBinding = true;
5569 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5570 SCS.BindsToRvalue = true;
5571 SCS.BindsToFunctionLvalue = false;
5572 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5573 SCS.ObjCLifetimeConversionBinding = false;
5574 } else
5575 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
5576 FromExpr: From, ToType);
5577 return Result;
5578 }
5579
5580 // C++14 [over.ics.list]p7:
5581 // C++11 [over.ics.list]p6:
5582 // Otherwise, if the parameter type is not a class:
5583 if (!ToType->isRecordType()) {
5584 // - if the initializer list has one element that is not itself an
5585 // initializer list, the implicit conversion sequence is the one
5586 // required to convert the element to the parameter type.
5587 unsigned NumInits = From->getNumInits();
5588 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)))
5589 Result = TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5590 SuppressUserConversions,
5591 InOverloadResolution,
5592 AllowObjCWritebackConversion);
5593 // - if the initializer list has no elements, the implicit conversion
5594 // sequence is the identity conversion.
5595 else if (NumInits == 0) {
5596 Result.setStandard();
5597 Result.Standard.setAsIdentityConversion();
5598 Result.Standard.setFromType(ToType);
5599 Result.Standard.setAllToTypes(ToType);
5600 }
5601 return Result;
5602 }
5603
5604 // C++14 [over.ics.list]p8:
5605 // C++11 [over.ics.list]p7:
5606 // In all cases other than those enumerated above, no conversion is possible
5607 return Result;
5608}
5609
5610/// TryCopyInitialization - Try to copy-initialize a value of type
5611/// ToType from the expression From. Return the implicit conversion
5612/// sequence required to pass this argument, which may be a bad
5613/// conversion sequence (meaning that the argument cannot be passed to
5614/// a parameter of this type). If @p SuppressUserConversions, then we
5615/// do not permit any user-defined conversion sequences.
5616static ImplicitConversionSequence
5617TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5618 bool SuppressUserConversions,
5619 bool InOverloadResolution,
5620 bool AllowObjCWritebackConversion,
5621 bool AllowExplicit) {
5622 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
5623 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
5624 InOverloadResolution,AllowObjCWritebackConversion);
5625
5626 if (ToType->isReferenceType())
5627 return TryReferenceInit(S, Init: From, DeclType: ToType,
5628 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
5629 SuppressUserConversions, AllowExplicit);
5630
5631 return TryImplicitConversion(S, From, ToType,
5632 SuppressUserConversions,
5633 AllowExplicit: AllowedExplicit::None,
5634 InOverloadResolution,
5635 /*CStyle=*/false,
5636 AllowObjCWritebackConversion,
5637 /*AllowObjCConversionOnExplicit=*/false);
5638}
5639
5640static bool TryCopyInitialization(const CanQualType FromQTy,
5641 const CanQualType ToQTy,
5642 Sema &S,
5643 SourceLocation Loc,
5644 ExprValueKind FromVK) {
5645 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5646 ImplicitConversionSequence ICS =
5647 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
5648
5649 return !ICS.isBad();
5650}
5651
5652/// TryObjectArgumentInitialization - Try to initialize the object
5653/// parameter of the given member function (@c Method) from the
5654/// expression @p From.
5655static ImplicitConversionSequence TryObjectArgumentInitialization(
5656 Sema &S, SourceLocation Loc, QualType FromType,
5657 Expr::Classification FromClassification, CXXMethodDecl *Method,
5658 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5659 QualType ExplicitParameterType = QualType(),
5660 bool SuppressUserConversion = false) {
5661
5662 // We need to have an object of class type.
5663 if (const auto *PT = FromType->getAs<PointerType>()) {
5664 FromType = PT->getPointeeType();
5665
5666 // When we had a pointer, it's implicitly dereferenced, so we
5667 // better have an lvalue.
5668 assert(FromClassification.isLValue());
5669 }
5670
5671 auto ValueKindFromClassification = [](Expr::Classification C) {
5672 if (C.isPRValue())
5673 return clang::VK_PRValue;
5674 if (C.isXValue())
5675 return VK_XValue;
5676 return clang::VK_LValue;
5677 };
5678
5679 if (Method->isExplicitObjectMemberFunction()) {
5680 if (ExplicitParameterType.isNull())
5681 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5682 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5683 ValueKindFromClassification(FromClassification));
5684 ImplicitConversionSequence ICS = TryCopyInitialization(
5685 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
5686 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
5687 if (ICS.isBad())
5688 ICS.Bad.FromExpr = nullptr;
5689 return ICS;
5690 }
5691
5692 assert(FromType->isRecordType());
5693
5694 QualType ClassType = S.Context.getTypeDeclType(Decl: ActingContext);
5695 // C++98 [class.dtor]p2:
5696 // A destructor can be invoked for a const, volatile or const volatile
5697 // object.
5698 // C++98 [over.match.funcs]p4:
5699 // For static member functions, the implicit object parameter is considered
5700 // to match any object (since if the function is selected, the object is
5701 // discarded).
5702 Qualifiers Quals = Method->getMethodQualifiers();
5703 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
5704 Quals.addConst();
5705 Quals.addVolatile();
5706 }
5707
5708 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
5709
5710 // Set up the conversion sequence as a "bad" conversion, to allow us
5711 // to exit early.
5712 ImplicitConversionSequence ICS;
5713
5714 // C++0x [over.match.funcs]p4:
5715 // For non-static member functions, the type of the implicit object
5716 // parameter is
5717 //
5718 // - "lvalue reference to cv X" for functions declared without a
5719 // ref-qualifier or with the & ref-qualifier
5720 // - "rvalue reference to cv X" for functions declared with the &&
5721 // ref-qualifier
5722 //
5723 // where X is the class of which the function is a member and cv is the
5724 // cv-qualification on the member function declaration.
5725 //
5726 // However, when finding an implicit conversion sequence for the argument, we
5727 // are not allowed to perform user-defined conversions
5728 // (C++ [over.match.funcs]p5). We perform a simplified version of
5729 // reference binding here, that allows class rvalues to bind to
5730 // non-constant references.
5731
5732 // First check the qualifiers.
5733 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
5734 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5735 if (ImplicitParamType.getCVRQualifiers() !=
5736 FromTypeCanon.getLocalCVRQualifiers() &&
5737 !ImplicitParamType.isAtLeastAsQualifiedAs(
5738 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon))) {
5739 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
5740 FromType, ToType: ImplicitParamType);
5741 return ICS;
5742 }
5743
5744 if (FromTypeCanon.hasAddressSpace()) {
5745 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5746 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5747 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType)) {
5748 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
5749 FromType, ToType: ImplicitParamType);
5750 return ICS;
5751 }
5752 }
5753
5754 // Check that we have either the same type or a derived type. It
5755 // affects the conversion rank.
5756 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
5757 ImplicitConversionKind SecondKind;
5758 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5759 SecondKind = ICK_Identity;
5760 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
5761 SecondKind = ICK_Derived_To_Base;
5762 } else if (!Method->isExplicitObjectMemberFunction()) {
5763 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
5764 FromType, ToType: ImplicitParamType);
5765 return ICS;
5766 }
5767
5768 // Check the ref-qualifier.
5769 switch (Method->getRefQualifier()) {
5770 case RQ_None:
5771 // Do nothing; we don't care about lvalueness or rvalueness.
5772 break;
5773
5774 case RQ_LValue:
5775 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5776 // non-const lvalue reference cannot bind to an rvalue
5777 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5778 ToType: ImplicitParamType);
5779 return ICS;
5780 }
5781 break;
5782
5783 case RQ_RValue:
5784 if (!FromClassification.isRValue()) {
5785 // rvalue reference cannot bind to an lvalue
5786 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5787 ToType: ImplicitParamType);
5788 return ICS;
5789 }
5790 break;
5791 }
5792
5793 // Success. Mark this as a reference binding.
5794 ICS.setStandard();
5795 ICS.Standard.setAsIdentityConversion();
5796 ICS.Standard.Second = SecondKind;
5797 ICS.Standard.setFromType(FromType);
5798 ICS.Standard.setAllToTypes(ImplicitParamType);
5799 ICS.Standard.ReferenceBinding = true;
5800 ICS.Standard.DirectBinding = true;
5801 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5802 ICS.Standard.BindsToFunctionLvalue = false;
5803 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5804 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5805 = (Method->getRefQualifier() == RQ_None);
5806 return ICS;
5807}
5808
5809/// PerformObjectArgumentInitialization - Perform initialization of
5810/// the implicit object parameter for the given Method with the given
5811/// expression.
5812ExprResult Sema::PerformImplicitObjectArgumentInitialization(
5813 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5814 CXXMethodDecl *Method) {
5815 QualType FromRecordType, DestType;
5816 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5817
5818 Expr::Classification FromClassification;
5819 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5820 FromRecordType = PT->getPointeeType();
5821 DestType = Method->getThisType();
5822 FromClassification = Expr::Classification::makeSimpleLValue();
5823 } else {
5824 FromRecordType = From->getType();
5825 DestType = ImplicitParamRecordType;
5826 FromClassification = From->Classify(Ctx&: Context);
5827
5828 // When performing member access on a prvalue, materialize a temporary.
5829 if (From->isPRValue()) {
5830 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
5831 BoundToLvalueReference: Method->getRefQualifier() !=
5832 RefQualifierKind::RQ_RValue);
5833 }
5834 }
5835
5836 // Note that we always use the true parent context when performing
5837 // the actual argument initialization.
5838 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5839 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
5840 ActingContext: Method->getParent());
5841 if (ICS.isBad()) {
5842 switch (ICS.Bad.Kind) {
5843 case BadConversionSequence::bad_qualifiers: {
5844 Qualifiers FromQs = FromRecordType.getQualifiers();
5845 Qualifiers ToQs = DestType.getQualifiers();
5846 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5847 if (CVR) {
5848 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
5849 << Method->getDeclName() << FromRecordType << (CVR - 1)
5850 << From->getSourceRange();
5851 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
5852 << Method->getDeclName();
5853 return ExprError();
5854 }
5855 break;
5856 }
5857
5858 case BadConversionSequence::lvalue_ref_to_rvalue:
5859 case BadConversionSequence::rvalue_ref_to_lvalue: {
5860 bool IsRValueQualified =
5861 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5862 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
5863 << Method->getDeclName() << FromClassification.isRValue()
5864 << IsRValueQualified;
5865 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
5866 << Method->getDeclName();
5867 return ExprError();
5868 }
5869
5870 case BadConversionSequence::no_conversion:
5871 case BadConversionSequence::unrelated_class:
5872 break;
5873
5874 case BadConversionSequence::too_few_initializers:
5875 case BadConversionSequence::too_many_initializers:
5876 llvm_unreachable("Lists are not objects");
5877 }
5878
5879 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
5880 << ImplicitParamRecordType << FromRecordType
5881 << From->getSourceRange();
5882 }
5883
5884 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5885 ExprResult FromRes =
5886 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
5887 if (FromRes.isInvalid())
5888 return ExprError();
5889 From = FromRes.get();
5890 }
5891
5892 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
5893 CastKind CK;
5894 QualType PteeTy = DestType->getPointeeType();
5895 LangAS DestAS =
5896 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5897 if (FromRecordType.getAddressSpace() != DestAS)
5898 CK = CK_AddressSpaceConversion;
5899 else
5900 CK = CK_NoOp;
5901 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
5902 }
5903 return From;
5904}
5905
5906/// TryContextuallyConvertToBool - Attempt to contextually convert the
5907/// expression From to bool (C++0x [conv]p3).
5908static ImplicitConversionSequence
5909TryContextuallyConvertToBool(Sema &S, Expr *From) {
5910 // C++ [dcl.init]/17.8:
5911 // - Otherwise, if the initialization is direct-initialization, the source
5912 // type is std::nullptr_t, and the destination type is bool, the initial
5913 // value of the object being initialized is false.
5914 if (From->getType()->isNullPtrType())
5915 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
5916 DestType: S.Context.BoolTy,
5917 NeedLValToRVal: From->isGLValue());
5918
5919 // All other direct-initialization of bool is equivalent to an implicit
5920 // conversion to bool in which explicit conversions are permitted.
5921 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
5922 /*SuppressUserConversions=*/false,
5923 AllowExplicit: AllowedExplicit::Conversions,
5924 /*InOverloadResolution=*/false,
5925 /*CStyle=*/false,
5926 /*AllowObjCWritebackConversion=*/false,
5927 /*AllowObjCConversionOnExplicit=*/false);
5928}
5929
5930ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5931 if (checkPlaceholderForOverload(S&: *this, E&: From))
5932 return ExprError();
5933
5934 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
5935 if (!ICS.isBad())
5936 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS, Action: AA_Converting);
5937
5938 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
5939 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
5940 << From->getType() << From->getSourceRange();
5941 return ExprError();
5942}
5943
5944/// Check that the specified conversion is permitted in a converted constant
5945/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5946/// is acceptable.
5947static bool CheckConvertedConstantConversions(Sema &S,
5948 StandardConversionSequence &SCS) {
5949 // Since we know that the target type is an integral or unscoped enumeration
5950 // type, most conversion kinds are impossible. All possible First and Third
5951 // conversions are fine.
5952 switch (SCS.Second) {
5953 case ICK_Identity:
5954 case ICK_Integral_Promotion:
5955 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5956 case ICK_Zero_Queue_Conversion:
5957 return true;
5958
5959 case ICK_Boolean_Conversion:
5960 // Conversion from an integral or unscoped enumeration type to bool is
5961 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5962 // conversion, so we allow it in a converted constant expression.
5963 //
5964 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5965 // a lot of popular code. We should at least add a warning for this
5966 // (non-conforming) extension.
5967 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5968 SCS.getToType(Idx: 2)->isBooleanType();
5969
5970 case ICK_Pointer_Conversion:
5971 case ICK_Pointer_Member:
5972 // C++1z: null pointer conversions and null member pointer conversions are
5973 // only permitted if the source type is std::nullptr_t.
5974 return SCS.getFromType()->isNullPtrType();
5975
5976 case ICK_Floating_Promotion:
5977 case ICK_Complex_Promotion:
5978 case ICK_Floating_Conversion:
5979 case ICK_Complex_Conversion:
5980 case ICK_Floating_Integral:
5981 case ICK_Compatible_Conversion:
5982 case ICK_Derived_To_Base:
5983 case ICK_Vector_Conversion:
5984 case ICK_SVE_Vector_Conversion:
5985 case ICK_RVV_Vector_Conversion:
5986 case ICK_HLSL_Vector_Splat:
5987 case ICK_Vector_Splat:
5988 case ICK_Complex_Real:
5989 case ICK_Block_Pointer_Conversion:
5990 case ICK_TransparentUnionConversion:
5991 case ICK_Writeback_Conversion:
5992 case ICK_Zero_Event_Conversion:
5993 case ICK_C_Only_Conversion:
5994 case ICK_Incompatible_Pointer_Conversion:
5995 case ICK_Fixed_Point_Conversion:
5996 case ICK_HLSL_Vector_Truncation:
5997 return false;
5998
5999 case ICK_Lvalue_To_Rvalue:
6000 case ICK_Array_To_Pointer:
6001 case ICK_Function_To_Pointer:
6002 case ICK_HLSL_Array_RValue:
6003 llvm_unreachable("found a first conversion kind in Second");
6004
6005 case ICK_Function_Conversion:
6006 case ICK_Qualification:
6007 llvm_unreachable("found a third conversion kind in Second");
6008
6009 case ICK_Num_Conversion_Kinds:
6010 break;
6011 }
6012
6013 llvm_unreachable("unknown conversion kind");
6014}
6015
6016/// BuildConvertedConstantExpression - Check that the expression From is a
6017/// converted constant expression of type T, perform the conversion but
6018/// does not evaluate the expression
6019static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6020 QualType T,
6021 Sema::CCEKind CCE,
6022 NamedDecl *Dest,
6023 APValue &PreNarrowingValue) {
6024 assert(S.getLangOpts().CPlusPlus11 &&
6025 "converted constant expression outside C++11");
6026
6027 if (checkPlaceholderForOverload(S, E&: From))
6028 return ExprError();
6029
6030 // C++1z [expr.const]p3:
6031 // A converted constant expression of type T is an expression,
6032 // implicitly converted to type T, where the converted
6033 // expression is a constant expression and the implicit conversion
6034 // sequence contains only [... list of conversions ...].
6035 ImplicitConversionSequence ICS =
6036 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
6037 ? TryContextuallyConvertToBool(S, From)
6038 : TryCopyInitialization(S, From, ToType: T,
6039 /*SuppressUserConversions=*/false,
6040 /*InOverloadResolution=*/false,
6041 /*AllowObjCWritebackConversion=*/false,
6042 /*AllowExplicit=*/false);
6043 StandardConversionSequence *SCS = nullptr;
6044 switch (ICS.getKind()) {
6045 case ImplicitConversionSequence::StandardConversion:
6046 SCS = &ICS.Standard;
6047 break;
6048 case ImplicitConversionSequence::UserDefinedConversion:
6049 if (T->isRecordType())
6050 SCS = &ICS.UserDefined.Before;
6051 else
6052 SCS = &ICS.UserDefined.After;
6053 break;
6054 case ImplicitConversionSequence::AmbiguousConversion:
6055 case ImplicitConversionSequence::BadConversion:
6056 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6057 return S.Diag(Loc: From->getBeginLoc(),
6058 DiagID: diag::err_typecheck_converted_constant_expression)
6059 << From->getType() << From->getSourceRange() << T;
6060 return ExprError();
6061
6062 case ImplicitConversionSequence::EllipsisConversion:
6063 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6064 llvm_unreachable("bad conversion in converted constant expression");
6065 }
6066
6067 // Check that we would only use permitted conversions.
6068 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6069 return S.Diag(Loc: From->getBeginLoc(),
6070 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6071 << From->getType() << From->getSourceRange() << T;
6072 }
6073 // [...] and where the reference binding (if any) binds directly.
6074 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6075 return S.Diag(Loc: From->getBeginLoc(),
6076 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6077 << From->getType() << From->getSourceRange() << T;
6078 }
6079 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6080 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6081 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6082 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6083 // case explicitly.
6084 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6085 return S.Diag(Loc: From->getBeginLoc(),
6086 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6087 << From->getSourceRange();
6088 }
6089
6090 // Usually we can simply apply the ImplicitConversionSequence we formed
6091 // earlier, but that's not guaranteed to work when initializing an object of
6092 // class type.
6093 ExprResult Result;
6094 if (T->isRecordType()) {
6095 assert(CCE == Sema::CCEK_TemplateArg &&
6096 "unexpected class type converted constant expr");
6097 Result = S.PerformCopyInitialization(
6098 Entity: InitializedEntity::InitializeTemplateParameter(
6099 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6100 EqualLoc: SourceLocation(), Init: From);
6101 } else {
6102 Result = S.PerformImplicitConversion(From, ToType: T, ICS, Action: Sema::AA_Converting);
6103 }
6104 if (Result.isInvalid())
6105 return Result;
6106
6107 // C++2a [intro.execution]p5:
6108 // A full-expression is [...] a constant-expression [...]
6109 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6110 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6111 IsTemplateArgument: CCE == Sema::CCEKind::CCEK_TemplateArg);
6112 if (Result.isInvalid())
6113 return Result;
6114
6115 // Check for a narrowing implicit conversion.
6116 bool ReturnPreNarrowingValue = false;
6117 QualType PreNarrowingType;
6118 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6119 ConstantType&: PreNarrowingType)) {
6120 case NK_Dependent_Narrowing:
6121 // Implicit conversion to a narrower type, but the expression is
6122 // value-dependent so we can't tell whether it's actually narrowing.
6123 case NK_Variable_Narrowing:
6124 // Implicit conversion to a narrower type, and the value is not a constant
6125 // expression. We'll diagnose this in a moment.
6126 case NK_Not_Narrowing:
6127 break;
6128
6129 case NK_Constant_Narrowing:
6130 if (CCE == Sema::CCEK_ArrayBound &&
6131 PreNarrowingType->isIntegralOrEnumerationType() &&
6132 PreNarrowingValue.isInt()) {
6133 // Don't diagnose array bound narrowing here; we produce more precise
6134 // errors by allowing the un-narrowed value through.
6135 ReturnPreNarrowingValue = true;
6136 break;
6137 }
6138 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6139 << CCE << /*Constant*/ 1
6140 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6141 break;
6142
6143 case NK_Type_Narrowing:
6144 // FIXME: It would be better to diagnose that the expression is not a
6145 // constant expression.
6146 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6147 << CCE << /*Constant*/ 0 << From->getType() << T;
6148 break;
6149 }
6150 if (!ReturnPreNarrowingValue)
6151 PreNarrowingValue = {};
6152
6153 return Result;
6154}
6155
6156/// CheckConvertedConstantExpression - Check that the expression From is a
6157/// converted constant expression of type T, perform the conversion and produce
6158/// the converted expression, per C++11 [expr.const]p3.
6159static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6160 QualType T, APValue &Value,
6161 Sema::CCEKind CCE,
6162 bool RequireInt,
6163 NamedDecl *Dest) {
6164
6165 APValue PreNarrowingValue;
6166 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6167 PreNarrowingValue);
6168 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6169 Value = APValue();
6170 return Result;
6171 }
6172 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6173 RequireInt, PreNarrowingValue);
6174}
6175
6176ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6177 CCEKind CCE,
6178 NamedDecl *Dest) {
6179 APValue PreNarrowingValue;
6180 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6181 PreNarrowingValue);
6182}
6183
6184ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6185 APValue &Value, CCEKind CCE,
6186 NamedDecl *Dest) {
6187 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6188 Dest);
6189}
6190
6191ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6192 llvm::APSInt &Value,
6193 CCEKind CCE) {
6194 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6195
6196 APValue V;
6197 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6198 /*Dest=*/nullptr);
6199 if (!R.isInvalid() && !R.get()->isValueDependent())
6200 Value = V.getInt();
6201 return R;
6202}
6203
6204ExprResult
6205Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6206 Sema::CCEKind CCE, bool RequireInt,
6207 const APValue &PreNarrowingValue) {
6208
6209 ExprResult Result = E;
6210 // Check the expression is a constant expression.
6211 SmallVector<PartialDiagnosticAt, 8> Notes;
6212 Expr::EvalResult Eval;
6213 Eval.Diag = &Notes;
6214
6215 ConstantExprKind Kind;
6216 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6217 Kind = ConstantExprKind::ClassTemplateArgument;
6218 else if (CCE == Sema::CCEK_TemplateArg)
6219 Kind = ConstantExprKind::NonClassTemplateArgument;
6220 else
6221 Kind = ConstantExprKind::Normal;
6222
6223 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6224 (RequireInt && !Eval.Val.isInt())) {
6225 // The expression can't be folded, so we can't keep it at this position in
6226 // the AST.
6227 Result = ExprError();
6228 } else {
6229 Value = Eval.Val;
6230
6231 if (Notes.empty()) {
6232 // It's a constant expression.
6233 Expr *E = Result.get();
6234 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6235 // We expect a ConstantExpr to have a value associated with it
6236 // by this point.
6237 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6238 "ConstantExpr has no value associated with it");
6239 (void)CE;
6240 } else {
6241 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6242 }
6243 if (!PreNarrowingValue.isAbsent())
6244 Value = std::move(PreNarrowingValue);
6245 return E;
6246 }
6247 }
6248
6249 // It's not a constant expression. Produce an appropriate diagnostic.
6250 if (Notes.size() == 1 &&
6251 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6252 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6253 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6254 diag::note_constexpr_invalid_template_arg) {
6255 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6256 for (unsigned I = 0; I < Notes.size(); ++I)
6257 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6258 } else {
6259 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6260 << CCE << E->getSourceRange();
6261 for (unsigned I = 0; I < Notes.size(); ++I)
6262 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6263 }
6264 return ExprError();
6265}
6266
6267/// dropPointerConversions - If the given standard conversion sequence
6268/// involves any pointer conversions, remove them. This may change
6269/// the result type of the conversion sequence.
6270static void dropPointerConversion(StandardConversionSequence &SCS) {
6271 if (SCS.Second == ICK_Pointer_Conversion) {
6272 SCS.Second = ICK_Identity;
6273 SCS.Dimension = ICK_Identity;
6274 SCS.Third = ICK_Identity;
6275 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6276 }
6277}
6278
6279/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6280/// convert the expression From to an Objective-C pointer type.
6281static ImplicitConversionSequence
6282TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6283 // Do an implicit conversion to 'id'.
6284 QualType Ty = S.Context.getObjCIdType();
6285 ImplicitConversionSequence ICS
6286 = TryImplicitConversion(S, From, ToType: Ty,
6287 // FIXME: Are these flags correct?
6288 /*SuppressUserConversions=*/false,
6289 AllowExplicit: AllowedExplicit::Conversions,
6290 /*InOverloadResolution=*/false,
6291 /*CStyle=*/false,
6292 /*AllowObjCWritebackConversion=*/false,
6293 /*AllowObjCConversionOnExplicit=*/true);
6294
6295 // Strip off any final conversions to 'id'.
6296 switch (ICS.getKind()) {
6297 case ImplicitConversionSequence::BadConversion:
6298 case ImplicitConversionSequence::AmbiguousConversion:
6299 case ImplicitConversionSequence::EllipsisConversion:
6300 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6301 break;
6302
6303 case ImplicitConversionSequence::UserDefinedConversion:
6304 dropPointerConversion(SCS&: ICS.UserDefined.After);
6305 break;
6306
6307 case ImplicitConversionSequence::StandardConversion:
6308 dropPointerConversion(SCS&: ICS.Standard);
6309 break;
6310 }
6311
6312 return ICS;
6313}
6314
6315ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6316 if (checkPlaceholderForOverload(S&: *this, E&: From))
6317 return ExprError();
6318
6319 QualType Ty = Context.getObjCIdType();
6320 ImplicitConversionSequence ICS =
6321 TryContextuallyConvertToObjCPointer(S&: *this, From);
6322 if (!ICS.isBad())
6323 return PerformImplicitConversion(From, ToType: Ty, ICS, Action: AA_Converting);
6324 return ExprResult();
6325}
6326
6327static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6328 const Expr *Base = nullptr;
6329 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6330 "expected a member expression");
6331
6332 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6333 M && !M->isImplicitAccess())
6334 Base = M->getBase();
6335 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6336 M && !M->isImplicitAccess())
6337 Base = M->getBase();
6338
6339 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6340
6341 if (T->isPointerType())
6342 T = T->getPointeeType();
6343
6344 return T;
6345}
6346
6347static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6348 const FunctionDecl *Fun) {
6349 QualType ObjType = Obj->getType();
6350 if (ObjType->isPointerType()) {
6351 ObjType = ObjType->getPointeeType();
6352 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6353 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6354 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6355 }
6356 if (Obj->Classify(Ctx&: S.getASTContext()).isPRValue()) {
6357 Obj = S.CreateMaterializeTemporaryExpr(
6358 T: ObjType, Temporary: Obj,
6359 BoundToLvalueReference: !Fun->getParamDecl(i: 0)->getType()->isRValueReferenceType());
6360 }
6361 return Obj;
6362}
6363
6364ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6365 FunctionDecl *Fun) {
6366 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6367 return S.PerformCopyInitialization(
6368 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6369 EqualLoc: Obj->getExprLoc(), Init: Obj);
6370}
6371
6372static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6373 Expr *Object, MultiExprArg &Args,
6374 SmallVectorImpl<Expr *> &NewArgs) {
6375 assert(Method->isExplicitObjectMemberFunction() &&
6376 "Method is not an explicit member function");
6377 assert(NewArgs.empty() && "NewArgs should be empty");
6378
6379 NewArgs.reserve(N: Args.size() + 1);
6380 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6381 NewArgs.push_back(Elt: This);
6382 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6383 Args = NewArgs;
6384 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6385 Method, CallLoc: Object->getBeginLoc());
6386}
6387
6388/// Determine whether the provided type is an integral type, or an enumeration
6389/// type of a permitted flavor.
6390bool Sema::ICEConvertDiagnoser::match(QualType T) {
6391 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6392 : T->isIntegralOrUnscopedEnumerationType();
6393}
6394
6395static ExprResult
6396diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6397 Sema::ContextualImplicitConverter &Converter,
6398 QualType T, UnresolvedSetImpl &ViableConversions) {
6399
6400 if (Converter.Suppress)
6401 return ExprError();
6402
6403 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6404 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6405 CXXConversionDecl *Conv =
6406 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6407 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6408 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6409 }
6410 return From;
6411}
6412
6413static bool
6414diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6415 Sema::ContextualImplicitConverter &Converter,
6416 QualType T, bool HadMultipleCandidates,
6417 UnresolvedSetImpl &ExplicitConversions) {
6418 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6419 DeclAccessPair Found = ExplicitConversions[0];
6420 CXXConversionDecl *Conversion =
6421 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6422
6423 // The user probably meant to invoke the given explicit
6424 // conversion; use it.
6425 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6426 std::string TypeStr;
6427 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6428
6429 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6430 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6431 Code: "static_cast<" + TypeStr + ">(")
6432 << FixItHint::CreateInsertion(
6433 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6434 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6435
6436 // If we aren't in a SFINAE context, build a call to the
6437 // explicit conversion function.
6438 if (SemaRef.isSFINAEContext())
6439 return true;
6440
6441 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6442 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6443 HadMultipleCandidates);
6444 if (Result.isInvalid())
6445 return true;
6446
6447 // Replace the conversion with a RecoveryExpr, so we don't try to
6448 // instantiate it later, but can further diagnose here.
6449 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6450 SubExprs: From, T: Result.get()->getType());
6451 if (Result.isInvalid())
6452 return true;
6453 From = Result.get();
6454 }
6455 return false;
6456}
6457
6458static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6459 Sema::ContextualImplicitConverter &Converter,
6460 QualType T, bool HadMultipleCandidates,
6461 DeclAccessPair &Found) {
6462 CXXConversionDecl *Conversion =
6463 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6464 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6465
6466 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6467 if (!Converter.SuppressConversion) {
6468 if (SemaRef.isSFINAEContext())
6469 return true;
6470
6471 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6472 << From->getSourceRange();
6473 }
6474
6475 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6476 HadMultipleCandidates);
6477 if (Result.isInvalid())
6478 return true;
6479 // Record usage of conversion in an implicit cast.
6480 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6481 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6482 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6483 FPO: SemaRef.CurFPFeatureOverrides());
6484 return false;
6485}
6486
6487static ExprResult finishContextualImplicitConversion(
6488 Sema &SemaRef, SourceLocation Loc, Expr *From,
6489 Sema::ContextualImplicitConverter &Converter) {
6490 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6491 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6492 << From->getSourceRange();
6493
6494 return SemaRef.DefaultLvalueConversion(E: From);
6495}
6496
6497static void
6498collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6499 UnresolvedSetImpl &ViableConversions,
6500 OverloadCandidateSet &CandidateSet) {
6501 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6502 DeclAccessPair FoundDecl = ViableConversions[I];
6503 NamedDecl *D = FoundDecl.getDecl();
6504 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
6505 if (isa<UsingShadowDecl>(Val: D))
6506 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6507
6508 CXXConversionDecl *Conv;
6509 FunctionTemplateDecl *ConvTemplate;
6510 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
6511 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6512 else
6513 Conv = cast<CXXConversionDecl>(Val: D);
6514
6515 if (ConvTemplate)
6516 SemaRef.AddTemplateConversionCandidate(
6517 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6518 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6519 else
6520 SemaRef.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From,
6521 ToType, CandidateSet,
6522 /*AllowObjCConversionOnExplicit=*/false,
6523 /*AllowExplicit*/ true);
6524 }
6525}
6526
6527/// Attempt to convert the given expression to a type which is accepted
6528/// by the given converter.
6529///
6530/// This routine will attempt to convert an expression of class type to a
6531/// type accepted by the specified converter. In C++11 and before, the class
6532/// must have a single non-explicit conversion function converting to a matching
6533/// type. In C++1y, there can be multiple such conversion functions, but only
6534/// one target type.
6535///
6536/// \param Loc The source location of the construct that requires the
6537/// conversion.
6538///
6539/// \param From The expression we're converting from.
6540///
6541/// \param Converter Used to control and diagnose the conversion process.
6542///
6543/// \returns The expression, converted to an integral or enumeration type if
6544/// successful.
6545ExprResult Sema::PerformContextualImplicitConversion(
6546 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6547 // We can't perform any more checking for type-dependent expressions.
6548 if (From->isTypeDependent())
6549 return From;
6550
6551 // Process placeholders immediately.
6552 if (From->hasPlaceholderType()) {
6553 ExprResult result = CheckPlaceholderExpr(E: From);
6554 if (result.isInvalid())
6555 return result;
6556 From = result.get();
6557 }
6558
6559 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6560 ExprResult Converted = DefaultLvalueConversion(E: From);
6561 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6562 // If the expression already has a matching type, we're golden.
6563 if (Converter.match(T))
6564 return Converted;
6565
6566 // FIXME: Check for missing '()' if T is a function type?
6567
6568 // We can only perform contextual implicit conversions on objects of class
6569 // type.
6570 const RecordType *RecordTy = T->getAs<RecordType>();
6571 if (!RecordTy || !getLangOpts().CPlusPlus) {
6572 if (!Converter.Suppress)
6573 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
6574 return From;
6575 }
6576
6577 // We must have a complete class type.
6578 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6579 ContextualImplicitConverter &Converter;
6580 Expr *From;
6581
6582 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6583 : Converter(Converter), From(From) {}
6584
6585 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6586 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6587 }
6588 } IncompleteDiagnoser(Converter, From);
6589
6590 if (Converter.Suppress ? !isCompleteType(Loc, T)
6591 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
6592 return From;
6593
6594 // Look for a conversion to an integral or enumeration type.
6595 UnresolvedSet<4>
6596 ViableConversions; // These are *potentially* viable in C++1y.
6597 UnresolvedSet<4> ExplicitConversions;
6598 const auto &Conversions =
6599 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getVisibleConversionFunctions();
6600
6601 bool HadMultipleCandidates =
6602 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
6603
6604 // To check that there is only one target type, in C++1y:
6605 QualType ToType;
6606 bool HasUniqueTargetType = true;
6607
6608 // Collect explicit or viable (potentially in C++1y) conversions.
6609 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6610 NamedDecl *D = (*I)->getUnderlyingDecl();
6611 CXXConversionDecl *Conversion;
6612 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
6613 if (ConvTemplate) {
6614 if (getLangOpts().CPlusPlus14)
6615 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6616 else
6617 continue; // C++11 does not consider conversion operator templates(?).
6618 } else
6619 Conversion = cast<CXXConversionDecl>(Val: D);
6620
6621 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6622 "Conversion operator templates are considered potentially "
6623 "viable in C++1y");
6624
6625 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6626 if (Converter.match(T: CurToType) || ConvTemplate) {
6627
6628 if (Conversion->isExplicit()) {
6629 // FIXME: For C++1y, do we need this restriction?
6630 // cf. diagnoseNoViableConversion()
6631 if (!ConvTemplate)
6632 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6633 } else {
6634 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6635 if (ToType.isNull())
6636 ToType = CurToType.getUnqualifiedType();
6637 else if (HasUniqueTargetType &&
6638 (CurToType.getUnqualifiedType() != ToType))
6639 HasUniqueTargetType = false;
6640 }
6641 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6642 }
6643 }
6644 }
6645
6646 if (getLangOpts().CPlusPlus14) {
6647 // C++1y [conv]p6:
6648 // ... An expression e of class type E appearing in such a context
6649 // is said to be contextually implicitly converted to a specified
6650 // type T and is well-formed if and only if e can be implicitly
6651 // converted to a type T that is determined as follows: E is searched
6652 // for conversion functions whose return type is cv T or reference to
6653 // cv T such that T is allowed by the context. There shall be
6654 // exactly one such T.
6655
6656 // If no unique T is found:
6657 if (ToType.isNull()) {
6658 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6659 HadMultipleCandidates,
6660 ExplicitConversions))
6661 return ExprError();
6662 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6663 }
6664
6665 // If more than one unique Ts are found:
6666 if (!HasUniqueTargetType)
6667 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6668 ViableConversions);
6669
6670 // If one unique T is found:
6671 // First, build a candidate set from the previously recorded
6672 // potentially viable conversions.
6673 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6674 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
6675 CandidateSet);
6676
6677 // Then, perform overload resolution over the candidate set.
6678 OverloadCandidateSet::iterator Best;
6679 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
6680 case OR_Success: {
6681 // Apply this conversion.
6682 DeclAccessPair Found =
6683 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
6684 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
6685 HadMultipleCandidates, Found))
6686 return ExprError();
6687 break;
6688 }
6689 case OR_Ambiguous:
6690 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6691 ViableConversions);
6692 case OR_No_Viable_Function:
6693 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6694 HadMultipleCandidates,
6695 ExplicitConversions))
6696 return ExprError();
6697 [[fallthrough]];
6698 case OR_Deleted:
6699 // We'll complain below about a non-integral condition type.
6700 break;
6701 }
6702 } else {
6703 switch (ViableConversions.size()) {
6704 case 0: {
6705 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6706 HadMultipleCandidates,
6707 ExplicitConversions))
6708 return ExprError();
6709
6710 // We'll complain below about a non-integral condition type.
6711 break;
6712 }
6713 case 1: {
6714 // Apply this conversion.
6715 DeclAccessPair Found = ViableConversions[0];
6716 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
6717 HadMultipleCandidates, Found))
6718 return ExprError();
6719 break;
6720 }
6721 default:
6722 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6723 ViableConversions);
6724 }
6725 }
6726
6727 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6728}
6729
6730/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6731/// an acceptable non-member overloaded operator for a call whose
6732/// arguments have types T1 (and, if non-empty, T2). This routine
6733/// implements the check in C++ [over.match.oper]p3b2 concerning
6734/// enumeration types.
6735static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6736 FunctionDecl *Fn,
6737 ArrayRef<Expr *> Args) {
6738 QualType T1 = Args[0]->getType();
6739 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6740
6741 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6742 return true;
6743
6744 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6745 return true;
6746
6747 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6748 if (Proto->getNumParams() < 1)
6749 return false;
6750
6751 if (T1->isEnumeralType()) {
6752 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
6753 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
6754 return true;
6755 }
6756
6757 if (Proto->getNumParams() < 2)
6758 return false;
6759
6760 if (!T2.isNull() && T2->isEnumeralType()) {
6761 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
6762 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
6763 return true;
6764 }
6765
6766 return false;
6767}
6768
6769static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
6770 if (FD->isTargetMultiVersionDefault())
6771 return false;
6772
6773 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6774 return FD->isTargetMultiVersion();
6775
6776 if (!FD->isMultiVersion())
6777 return false;
6778
6779 // Among multiple target versions consider either the default,
6780 // or the first non-default in the absence of default version.
6781 unsigned SeenAt = 0;
6782 unsigned I = 0;
6783 bool HasDefault = false;
6784 FD->getASTContext().forEachMultiversionedFunctionVersion(
6785 FD, Pred: [&](const FunctionDecl *CurFD) {
6786 if (FD == CurFD)
6787 SeenAt = I;
6788 else if (CurFD->isTargetMultiVersionDefault())
6789 HasDefault = true;
6790 ++I;
6791 });
6792 return HasDefault || SeenAt != 0;
6793}
6794
6795void Sema::AddOverloadCandidate(
6796 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6797 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6798 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6799 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6800 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6801 const FunctionProtoType *Proto
6802 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
6803 assert(Proto && "Functions without a prototype cannot be overloaded");
6804 assert(!Function->getDescribedFunctionTemplate() &&
6805 "Use AddTemplateOverloadCandidate for function templates");
6806
6807 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
6808 if (!isa<CXXConstructorDecl>(Val: Method)) {
6809 // If we get here, it's because we're calling a member function
6810 // that is named without a member access expression (e.g.,
6811 // "this->f") that was either written explicitly or created
6812 // implicitly. This can happen with a qualified call to a member
6813 // function, e.g., X::f(). We use an empty type for the implied
6814 // object argument (C++ [over.call.func]p3), and the acting context
6815 // is irrelevant.
6816 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
6817 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
6818 CandidateSet, SuppressUserConversions,
6819 PartialOverloading, EarlyConversions, PO);
6820 return;
6821 }
6822 // We treat a constructor like a non-member function, since its object
6823 // argument doesn't participate in overload resolution.
6824 }
6825
6826 if (!CandidateSet.isNewCandidate(F: Function, PO))
6827 return;
6828
6829 // C++11 [class.copy]p11: [DR1402]
6830 // A defaulted move constructor that is defined as deleted is ignored by
6831 // overload resolution.
6832 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
6833 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6834 Constructor->isMoveConstructor())
6835 return;
6836
6837 // Overload resolution is always an unevaluated context.
6838 EnterExpressionEvaluationContext Unevaluated(
6839 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6840
6841 // C++ [over.match.oper]p3:
6842 // if no operand has a class type, only those non-member functions in the
6843 // lookup set that have a first parameter of type T1 or "reference to
6844 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6845 // is a right operand) a second parameter of type T2 or "reference to
6846 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6847 // candidate functions.
6848 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6849 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
6850 return;
6851
6852 // Add this candidate
6853 OverloadCandidate &Candidate =
6854 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
6855 Candidate.FoundDecl = FoundDecl;
6856 Candidate.Function = Function;
6857 Candidate.Viable = true;
6858 Candidate.RewriteKind =
6859 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
6860 Candidate.IsADLCandidate = IsADLCandidate;
6861 Candidate.ExplicitCallArguments = Args.size();
6862
6863 // Explicit functions are not actually candidates at all if we're not
6864 // allowing them in this context, but keep them around so we can point
6865 // to them in diagnostics.
6866 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6867 Candidate.Viable = false;
6868 Candidate.FailureKind = ovl_fail_explicit;
6869 return;
6870 }
6871
6872 // Functions with internal linkage are only viable in the same module unit.
6873 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6874 /// FIXME: Currently, the semantics of linkage in clang is slightly
6875 /// different from the semantics in C++ spec. In C++ spec, only names
6876 /// have linkage. So that all entities of the same should share one
6877 /// linkage. But in clang, different entities of the same could have
6878 /// different linkage.
6879 NamedDecl *ND = Function;
6880 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6881 ND = SpecInfo->getTemplate();
6882
6883 if (ND->getFormalLinkage() == Linkage::Internal) {
6884 Candidate.Viable = false;
6885 Candidate.FailureKind = ovl_fail_module_mismatched;
6886 return;
6887 }
6888 }
6889
6890 if (isNonViableMultiVersionOverload(FD: Function)) {
6891 Candidate.Viable = false;
6892 Candidate.FailureKind = ovl_non_default_multiversion_function;
6893 return;
6894 }
6895
6896 if (Constructor) {
6897 // C++ [class.copy]p3:
6898 // A member function template is never instantiated to perform the copy
6899 // of a class object to an object of its class type.
6900 QualType ClassType = Context.getTypeDeclType(Decl: Constructor->getParent());
6901 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6902 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
6903 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
6904 Base: ClassType))) {
6905 Candidate.Viable = false;
6906 Candidate.FailureKind = ovl_fail_illegal_constructor;
6907 return;
6908 }
6909
6910 // C++ [over.match.funcs]p8: (proposed DR resolution)
6911 // A constructor inherited from class type C that has a first parameter
6912 // of type "reference to P" (including such a constructor instantiated
6913 // from a template) is excluded from the set of candidate functions when
6914 // constructing an object of type cv D if the argument list has exactly
6915 // one argument and D is reference-related to P and P is reference-related
6916 // to C.
6917 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
6918 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6919 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
6920 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
6921 QualType C = Context.getRecordType(Decl: Constructor->getParent());
6922 QualType D = Context.getRecordType(Decl: Shadow->getParent());
6923 SourceLocation Loc = Args.front()->getExprLoc();
6924 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
6925 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
6926 Candidate.Viable = false;
6927 Candidate.FailureKind = ovl_fail_inhctor_slice;
6928 return;
6929 }
6930 }
6931
6932 // Check that the constructor is capable of constructing an object in the
6933 // destination address space.
6934 if (!Qualifiers::isAddressSpaceSupersetOf(
6935 A: Constructor->getMethodQualifiers().getAddressSpace(),
6936 B: CandidateSet.getDestAS())) {
6937 Candidate.Viable = false;
6938 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6939 }
6940 }
6941
6942 unsigned NumParams = Proto->getNumParams();
6943
6944 // (C++ 13.3.2p2): A candidate function having fewer than m
6945 // parameters is viable only if it has an ellipsis in its parameter
6946 // list (8.3.5).
6947 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
6948 !Proto->isVariadic() &&
6949 shouldEnforceArgLimit(PartialOverloading, Function)) {
6950 Candidate.Viable = false;
6951 Candidate.FailureKind = ovl_fail_too_many_arguments;
6952 return;
6953 }
6954
6955 // (C++ 13.3.2p2): A candidate function having more than m parameters
6956 // is viable only if the (m+1)st parameter has a default argument
6957 // (8.3.6). For the purposes of overload resolution, the
6958 // parameter list is truncated on the right, so that there are
6959 // exactly m parameters.
6960 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6961 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
6962 !PartialOverloading) {
6963 // Not enough arguments.
6964 Candidate.Viable = false;
6965 Candidate.FailureKind = ovl_fail_too_few_arguments;
6966 return;
6967 }
6968
6969 // (CUDA B.1): Check for invalid calls between targets.
6970 if (getLangOpts().CUDA) {
6971 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
6972 // Skip the check for callers that are implicit members, because in this
6973 // case we may not yet know what the member's target is; the target is
6974 // inferred for the member automatically, based on the bases and fields of
6975 // the class.
6976 if (!(Caller && Caller->isImplicit()) &&
6977 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
6978 Candidate.Viable = false;
6979 Candidate.FailureKind = ovl_fail_bad_target;
6980 return;
6981 }
6982 }
6983
6984 if (Function->getTrailingRequiresClause()) {
6985 ConstraintSatisfaction Satisfaction;
6986 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
6987 /*ForOverloadResolution*/ true) ||
6988 !Satisfaction.IsSatisfied) {
6989 Candidate.Viable = false;
6990 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6991 return;
6992 }
6993 }
6994
6995 // Determine the implicit conversion sequences for each of the
6996 // arguments.
6997 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6998 unsigned ConvIdx =
6999 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7000 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7001 // We already formed a conversion sequence for this parameter during
7002 // template argument deduction.
7003 } else if (ArgIdx < NumParams) {
7004 // (C++ 13.3.2p3): for F to be a viable function, there shall
7005 // exist for each argument an implicit conversion sequence
7006 // (13.3.3.1) that converts that argument to the corresponding
7007 // parameter of F.
7008 QualType ParamType = Proto->getParamType(i: ArgIdx);
7009 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7010 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7011 /*InOverloadResolution=*/true,
7012 /*AllowObjCWritebackConversion=*/
7013 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7014 if (Candidate.Conversions[ConvIdx].isBad()) {
7015 Candidate.Viable = false;
7016 Candidate.FailureKind = ovl_fail_bad_conversion;
7017 return;
7018 }
7019 } else {
7020 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7021 // argument for which there is no corresponding parameter is
7022 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7023 Candidate.Conversions[ConvIdx].setEllipsis();
7024 }
7025 }
7026
7027 if (EnableIfAttr *FailedAttr =
7028 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7029 Candidate.Viable = false;
7030 Candidate.FailureKind = ovl_fail_enable_if;
7031 Candidate.DeductionFailure.Data = FailedAttr;
7032 return;
7033 }
7034}
7035
7036ObjCMethodDecl *
7037Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7038 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7039 if (Methods.size() <= 1)
7040 return nullptr;
7041
7042 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7043 bool Match = true;
7044 ObjCMethodDecl *Method = Methods[b];
7045 unsigned NumNamedArgs = Sel.getNumArgs();
7046 // Method might have more arguments than selector indicates. This is due
7047 // to addition of c-style arguments in method.
7048 if (Method->param_size() > NumNamedArgs)
7049 NumNamedArgs = Method->param_size();
7050 if (Args.size() < NumNamedArgs)
7051 continue;
7052
7053 for (unsigned i = 0; i < NumNamedArgs; i++) {
7054 // We can't do any type-checking on a type-dependent argument.
7055 if (Args[i]->isTypeDependent()) {
7056 Match = false;
7057 break;
7058 }
7059
7060 ParmVarDecl *param = Method->parameters()[i];
7061 Expr *argExpr = Args[i];
7062 assert(argExpr && "SelectBestMethod(): missing expression");
7063
7064 // Strip the unbridged-cast placeholder expression off unless it's
7065 // a consumed argument.
7066 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7067 !param->hasAttr<CFConsumedAttr>())
7068 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7069
7070 // If the parameter is __unknown_anytype, move on to the next method.
7071 if (param->getType() == Context.UnknownAnyTy) {
7072 Match = false;
7073 break;
7074 }
7075
7076 ImplicitConversionSequence ConversionState
7077 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7078 /*SuppressUserConversions*/false,
7079 /*InOverloadResolution=*/true,
7080 /*AllowObjCWritebackConversion=*/
7081 getLangOpts().ObjCAutoRefCount,
7082 /*AllowExplicit*/false);
7083 // This function looks for a reasonably-exact match, so we consider
7084 // incompatible pointer conversions to be a failure here.
7085 if (ConversionState.isBad() ||
7086 (ConversionState.isStandard() &&
7087 ConversionState.Standard.Second ==
7088 ICK_Incompatible_Pointer_Conversion)) {
7089 Match = false;
7090 break;
7091 }
7092 }
7093 // Promote additional arguments to variadic methods.
7094 if (Match && Method->isVariadic()) {
7095 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7096 if (Args[i]->isTypeDependent()) {
7097 Match = false;
7098 break;
7099 }
7100 ExprResult Arg = DefaultVariadicArgumentPromotion(E: Args[i], CT: VariadicMethod,
7101 FDecl: nullptr);
7102 if (Arg.isInvalid()) {
7103 Match = false;
7104 break;
7105 }
7106 }
7107 } else {
7108 // Check for extra arguments to non-variadic methods.
7109 if (Args.size() != NumNamedArgs)
7110 Match = false;
7111 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7112 // Special case when selectors have no argument. In this case, select
7113 // one with the most general result type of 'id'.
7114 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7115 QualType ReturnT = Methods[b]->getReturnType();
7116 if (ReturnT->isObjCIdType())
7117 return Methods[b];
7118 }
7119 }
7120 }
7121
7122 if (Match)
7123 return Method;
7124 }
7125 return nullptr;
7126}
7127
7128static bool convertArgsForAvailabilityChecks(
7129 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7130 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7131 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7132 if (ThisArg) {
7133 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7134 assert(!isa<CXXConstructorDecl>(Method) &&
7135 "Shouldn't have `this` for ctors!");
7136 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7137 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7138 From: ThisArg, /*Qualifier=*/nullptr, FoundDecl: Method, Method);
7139 if (R.isInvalid())
7140 return false;
7141 ConvertedThis = R.get();
7142 } else {
7143 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7144 (void)MD;
7145 assert((MissingImplicitThis || MD->isStatic() ||
7146 isa<CXXConstructorDecl>(MD)) &&
7147 "Expected `this` for non-ctor instance methods");
7148 }
7149 ConvertedThis = nullptr;
7150 }
7151
7152 // Ignore any variadic arguments. Converting them is pointless, since the
7153 // user can't refer to them in the function condition.
7154 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7155
7156 // Convert the arguments.
7157 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7158 ExprResult R;
7159 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7160 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7161 EqualLoc: SourceLocation(), Init: Args[I]);
7162
7163 if (R.isInvalid())
7164 return false;
7165
7166 ConvertedArgs.push_back(Elt: R.get());
7167 }
7168
7169 if (Trap.hasErrorOccurred())
7170 return false;
7171
7172 // Push default arguments if needed.
7173 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7174 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7175 ParmVarDecl *P = Function->getParamDecl(i);
7176 if (!P->hasDefaultArg())
7177 return false;
7178 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7179 if (R.isInvalid())
7180 return false;
7181 ConvertedArgs.push_back(Elt: R.get());
7182 }
7183
7184 if (Trap.hasErrorOccurred())
7185 return false;
7186 }
7187 return true;
7188}
7189
7190EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7191 SourceLocation CallLoc,
7192 ArrayRef<Expr *> Args,
7193 bool MissingImplicitThis) {
7194 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7195 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7196 return nullptr;
7197
7198 SFINAETrap Trap(*this);
7199 SmallVector<Expr *, 16> ConvertedArgs;
7200 // FIXME: We should look into making enable_if late-parsed.
7201 Expr *DiscardedThis;
7202 if (!convertArgsForAvailabilityChecks(
7203 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7204 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7205 return *EnableIfAttrs.begin();
7206
7207 for (auto *EIA : EnableIfAttrs) {
7208 APValue Result;
7209 // FIXME: This doesn't consider value-dependent cases, because doing so is
7210 // very difficult. Ideally, we should handle them more gracefully.
7211 if (EIA->getCond()->isValueDependent() ||
7212 !EIA->getCond()->EvaluateWithSubstitution(
7213 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7214 return EIA;
7215
7216 if (!Result.isInt() || !Result.getInt().getBoolValue())
7217 return EIA;
7218 }
7219 return nullptr;
7220}
7221
7222template <typename CheckFn>
7223static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7224 bool ArgDependent, SourceLocation Loc,
7225 CheckFn &&IsSuccessful) {
7226 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7227 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7228 if (ArgDependent == DIA->getArgDependent())
7229 Attrs.push_back(Elt: DIA);
7230 }
7231
7232 // Common case: No diagnose_if attributes, so we can quit early.
7233 if (Attrs.empty())
7234 return false;
7235
7236 auto WarningBegin = std::stable_partition(
7237 Attrs.begin(), Attrs.end(),
7238 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7239
7240 // Note that diagnose_if attributes are late-parsed, so they appear in the
7241 // correct order (unlike enable_if attributes).
7242 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7243 IsSuccessful);
7244 if (ErrAttr != WarningBegin) {
7245 const DiagnoseIfAttr *DIA = *ErrAttr;
7246 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7247 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7248 << DIA->getParent() << DIA->getCond()->getSourceRange();
7249 return true;
7250 }
7251
7252 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7253 if (IsSuccessful(DIA)) {
7254 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7255 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7256 << DIA->getParent() << DIA->getCond()->getSourceRange();
7257 }
7258
7259 return false;
7260}
7261
7262bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7263 const Expr *ThisArg,
7264 ArrayRef<const Expr *> Args,
7265 SourceLocation Loc) {
7266 return diagnoseDiagnoseIfAttrsWith(
7267 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7268 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7269 APValue Result;
7270 // It's sane to use the same Args for any redecl of this function, since
7271 // EvaluateWithSubstitution only cares about the position of each
7272 // argument in the arg list, not the ParmVarDecl* it maps to.
7273 if (!DIA->getCond()->EvaluateWithSubstitution(
7274 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7275 return false;
7276 return Result.isInt() && Result.getInt().getBoolValue();
7277 });
7278}
7279
7280bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7281 SourceLocation Loc) {
7282 return diagnoseDiagnoseIfAttrsWith(
7283 S&: *this, ND, /*ArgDependent=*/false, Loc,
7284 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7285 bool Result;
7286 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7287 Result;
7288 });
7289}
7290
7291void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7292 ArrayRef<Expr *> Args,
7293 OverloadCandidateSet &CandidateSet,
7294 TemplateArgumentListInfo *ExplicitTemplateArgs,
7295 bool SuppressUserConversions,
7296 bool PartialOverloading,
7297 bool FirstArgumentIsBase) {
7298 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7299 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7300 ArrayRef<Expr *> FunctionArgs = Args;
7301
7302 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7303 FunctionDecl *FD =
7304 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7305
7306 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7307 QualType ObjectType;
7308 Expr::Classification ObjectClassification;
7309 if (Args.size() > 0) {
7310 if (Expr *E = Args[0]) {
7311 // Use the explicit base to restrict the lookup:
7312 ObjectType = E->getType();
7313 // Pointers in the object arguments are implicitly dereferenced, so we
7314 // always classify them as l-values.
7315 if (!ObjectType.isNull() && ObjectType->isPointerType())
7316 ObjectClassification = Expr::Classification::makeSimpleLValue();
7317 else
7318 ObjectClassification = E->Classify(Ctx&: Context);
7319 } // .. else there is an implicit base.
7320 FunctionArgs = Args.slice(N: 1);
7321 }
7322 if (FunTmpl) {
7323 AddMethodTemplateCandidate(
7324 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7325 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7326 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7327 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7328 PartialOverloading);
7329 } else {
7330 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7331 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7332 ObjectClassification, Args: FunctionArgs, CandidateSet,
7333 SuppressUserConversions, PartialOverloading);
7334 }
7335 } else {
7336 // This branch handles both standalone functions and static methods.
7337
7338 // Slice the first argument (which is the base) when we access
7339 // static method as non-static.
7340 if (Args.size() > 0 &&
7341 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7342 !isa<CXXConstructorDecl>(Val: FD)))) {
7343 assert(cast<CXXMethodDecl>(FD)->isStatic());
7344 FunctionArgs = Args.slice(N: 1);
7345 }
7346 if (FunTmpl) {
7347 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7348 ExplicitTemplateArgs, Args: FunctionArgs,
7349 CandidateSet, SuppressUserConversions,
7350 PartialOverloading);
7351 } else {
7352 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7353 SuppressUserConversions, PartialOverloading);
7354 }
7355 }
7356 }
7357}
7358
7359void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7360 Expr::Classification ObjectClassification,
7361 ArrayRef<Expr *> Args,
7362 OverloadCandidateSet &CandidateSet,
7363 bool SuppressUserConversions,
7364 OverloadCandidateParamOrder PO) {
7365 NamedDecl *Decl = FoundDecl.getDecl();
7366 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7367
7368 if (isa<UsingShadowDecl>(Val: Decl))
7369 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7370
7371 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7372 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7373 "Expected a member function template");
7374 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7375 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7376 ObjectClassification, Args, CandidateSet,
7377 SuppressUserConversions, PartialOverloading: false, PO);
7378 } else {
7379 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7380 ObjectType, ObjectClassification, Args, CandidateSet,
7381 SuppressUserConversions, PartialOverloading: false, EarlyConversions: std::nullopt, PO);
7382 }
7383}
7384
7385void
7386Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7387 CXXRecordDecl *ActingContext, QualType ObjectType,
7388 Expr::Classification ObjectClassification,
7389 ArrayRef<Expr *> Args,
7390 OverloadCandidateSet &CandidateSet,
7391 bool SuppressUserConversions,
7392 bool PartialOverloading,
7393 ConversionSequenceList EarlyConversions,
7394 OverloadCandidateParamOrder PO) {
7395 const FunctionProtoType *Proto
7396 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7397 assert(Proto && "Methods without a prototype cannot be overloaded");
7398 assert(!isa<CXXConstructorDecl>(Method) &&
7399 "Use AddOverloadCandidate for constructors");
7400
7401 if (!CandidateSet.isNewCandidate(F: Method, PO))
7402 return;
7403
7404 // C++11 [class.copy]p23: [DR1402]
7405 // A defaulted move assignment operator that is defined as deleted is
7406 // ignored by overload resolution.
7407 if (Method->isDefaulted() && Method->isDeleted() &&
7408 Method->isMoveAssignmentOperator())
7409 return;
7410
7411 // Overload resolution is always an unevaluated context.
7412 EnterExpressionEvaluationContext Unevaluated(
7413 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7414
7415 // Add this candidate
7416 OverloadCandidate &Candidate =
7417 CandidateSet.addCandidate(NumConversions: Args.size() + 1, Conversions: EarlyConversions);
7418 Candidate.FoundDecl = FoundDecl;
7419 Candidate.Function = Method;
7420 Candidate.RewriteKind =
7421 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
7422 Candidate.TookAddressOfOverload =
7423 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7424 Candidate.ExplicitCallArguments = Args.size();
7425
7426 bool IgnoreExplicitObject =
7427 (Method->isExplicitObjectMemberFunction() &&
7428 CandidateSet.getKind() ==
7429 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7430 bool ImplicitObjectMethodTreatedAsStatic =
7431 CandidateSet.getKind() ==
7432 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7433 Method->isImplicitObjectMemberFunction();
7434
7435 unsigned ExplicitOffset =
7436 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7437
7438 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7439 int(ImplicitObjectMethodTreatedAsStatic);
7440
7441 // (C++ 13.3.2p2): A candidate function having fewer than m
7442 // parameters is viable only if it has an ellipsis in its parameter
7443 // list (8.3.5).
7444 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7445 !Proto->isVariadic() &&
7446 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
7447 Candidate.Viable = false;
7448 Candidate.FailureKind = ovl_fail_too_many_arguments;
7449 return;
7450 }
7451
7452 // (C++ 13.3.2p2): A candidate function having more than m parameters
7453 // is viable only if the (m+1)st parameter has a default argument
7454 // (8.3.6). For the purposes of overload resolution, the
7455 // parameter list is truncated on the right, so that there are
7456 // exactly m parameters.
7457 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7458 ExplicitOffset +
7459 int(ImplicitObjectMethodTreatedAsStatic);
7460
7461 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7462 // Not enough arguments.
7463 Candidate.Viable = false;
7464 Candidate.FailureKind = ovl_fail_too_few_arguments;
7465 return;
7466 }
7467
7468 Candidate.Viable = true;
7469
7470 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7471 if (ObjectType.isNull())
7472 Candidate.IgnoreObjectArgument = true;
7473 else if (Method->isStatic()) {
7474 // [over.best.ics.general]p8
7475 // When the parameter is the implicit object parameter of a static member
7476 // function, the implicit conversion sequence is a standard conversion
7477 // sequence that is neither better nor worse than any other standard
7478 // conversion sequence.
7479 //
7480 // This is a rule that was introduced in C++23 to support static lambdas. We
7481 // apply it retroactively because we want to support static lambdas as an
7482 // extension and it doesn't hurt previous code.
7483 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7484 } else {
7485 // Determine the implicit conversion sequence for the object
7486 // parameter.
7487 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7488 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
7489 Method, ActingContext, /*InOverloadResolution=*/true);
7490 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7491 Candidate.Viable = false;
7492 Candidate.FailureKind = ovl_fail_bad_conversion;
7493 return;
7494 }
7495 }
7496
7497 // (CUDA B.1): Check for invalid calls between targets.
7498 if (getLangOpts().CUDA)
7499 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
7500 Callee: Method)) {
7501 Candidate.Viable = false;
7502 Candidate.FailureKind = ovl_fail_bad_target;
7503 return;
7504 }
7505
7506 if (Method->getTrailingRequiresClause()) {
7507 ConstraintSatisfaction Satisfaction;
7508 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
7509 /*ForOverloadResolution*/ true) ||
7510 !Satisfaction.IsSatisfied) {
7511 Candidate.Viable = false;
7512 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7513 return;
7514 }
7515 }
7516
7517 // Determine the implicit conversion sequences for each of the
7518 // arguments.
7519 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7520 unsigned ConvIdx =
7521 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7522 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7523 // We already formed a conversion sequence for this parameter during
7524 // template argument deduction.
7525 } else if (ArgIdx < NumParams) {
7526 // (C++ 13.3.2p3): for F to be a viable function, there shall
7527 // exist for each argument an implicit conversion sequence
7528 // (13.3.3.1) that converts that argument to the corresponding
7529 // parameter of F.
7530 QualType ParamType;
7531 if (ImplicitObjectMethodTreatedAsStatic) {
7532 ParamType = ArgIdx == 0
7533 ? Method->getFunctionObjectParameterReferenceType()
7534 : Proto->getParamType(i: ArgIdx - 1);
7535 } else {
7536 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
7537 }
7538 Candidate.Conversions[ConvIdx]
7539 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
7540 SuppressUserConversions,
7541 /*InOverloadResolution=*/true,
7542 /*AllowObjCWritebackConversion=*/
7543 getLangOpts().ObjCAutoRefCount);
7544 if (Candidate.Conversions[ConvIdx].isBad()) {
7545 Candidate.Viable = false;
7546 Candidate.FailureKind = ovl_fail_bad_conversion;
7547 return;
7548 }
7549 } else {
7550 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7551 // argument for which there is no corresponding parameter is
7552 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7553 Candidate.Conversions[ConvIdx].setEllipsis();
7554 }
7555 }
7556
7557 if (EnableIfAttr *FailedAttr =
7558 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
7559 Candidate.Viable = false;
7560 Candidate.FailureKind = ovl_fail_enable_if;
7561 Candidate.DeductionFailure.Data = FailedAttr;
7562 return;
7563 }
7564
7565 if (isNonViableMultiVersionOverload(FD: Method)) {
7566 Candidate.Viable = false;
7567 Candidate.FailureKind = ovl_non_default_multiversion_function;
7568 }
7569}
7570
7571void Sema::AddMethodTemplateCandidate(
7572 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7573 CXXRecordDecl *ActingContext,
7574 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7575 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7576 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7577 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7578 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
7579 return;
7580
7581 // C++ [over.match.funcs]p7:
7582 // In each case where a candidate is a function template, candidate
7583 // function template specializations are generated using template argument
7584 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7585 // candidate functions in the usual way.113) A given name can refer to one
7586 // or more function templates and also to a set of overloaded non-template
7587 // functions. In such a case, the candidate functions generated from each
7588 // function template are combined with the set of non-template candidate
7589 // functions.
7590 TemplateDeductionInfo Info(CandidateSet.getLocation());
7591 FunctionDecl *Specialization = nullptr;
7592 ConversionSequenceList Conversions;
7593 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7594 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7595 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7596 ObjectClassification,
7597 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes) {
7598 return CheckNonDependentConversions(
7599 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7600 SuppressUserConversions, ActingContext, ObjectType,
7601 ObjectClassification, PO);
7602 });
7603 Result != TemplateDeductionResult::Success) {
7604 OverloadCandidate &Candidate =
7605 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
7606 Candidate.FoundDecl = FoundDecl;
7607 Candidate.Function = MethodTmpl->getTemplatedDecl();
7608 Candidate.Viable = false;
7609 Candidate.RewriteKind =
7610 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
7611 Candidate.IsSurrogate = false;
7612 Candidate.IgnoreObjectArgument =
7613 cast<CXXMethodDecl>(Val: Candidate.Function)->isStatic() ||
7614 ObjectType.isNull();
7615 Candidate.ExplicitCallArguments = Args.size();
7616 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7617 Candidate.FailureKind = ovl_fail_bad_conversion;
7618 else {
7619 Candidate.FailureKind = ovl_fail_bad_deduction;
7620 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result,
7621 Info);
7622 }
7623 return;
7624 }
7625
7626 // Add the function template specialization produced by template argument
7627 // deduction as a candidate.
7628 assert(Specialization && "Missing member function template specialization?");
7629 assert(isa<CXXMethodDecl>(Specialization) &&
7630 "Specialization is not a member function?");
7631 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl,
7632 ActingContext, ObjectType, ObjectClassification, Args,
7633 CandidateSet, SuppressUserConversions, PartialOverloading,
7634 EarlyConversions: Conversions, PO);
7635}
7636
7637/// Determine whether a given function template has a simple explicit specifier
7638/// or a non-value-dependent explicit-specification that evaluates to true.
7639static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7640 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
7641}
7642
7643void Sema::AddTemplateOverloadCandidate(
7644 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7645 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7646 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7647 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7648 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7649 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
7650 return;
7651
7652 // If the function template has a non-dependent explicit specification,
7653 // exclude it now if appropriate; we are not permitted to perform deduction
7654 // and substitution in this case.
7655 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
7656 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7657 Candidate.FoundDecl = FoundDecl;
7658 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7659 Candidate.Viable = false;
7660 Candidate.FailureKind = ovl_fail_explicit;
7661 return;
7662 }
7663
7664 // C++ [over.match.funcs]p7:
7665 // In each case where a candidate is a function template, candidate
7666 // function template specializations are generated using template argument
7667 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7668 // candidate functions in the usual way.113) A given name can refer to one
7669 // or more function templates and also to a set of overloaded non-template
7670 // functions. In such a case, the candidate functions generated from each
7671 // function template are combined with the set of non-template candidate
7672 // functions.
7673 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7674 FunctionTemplate->getTemplateDepth());
7675 FunctionDecl *Specialization = nullptr;
7676 ConversionSequenceList Conversions;
7677 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7678 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7679 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
7680 /*ObjectType=*/QualType(),
7681 /*ObjectClassification=*/Expr::Classification(),
7682 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes) {
7683 return CheckNonDependentConversions(
7684 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7685 SuppressUserConversions, ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
7686 });
7687 Result != TemplateDeductionResult::Success) {
7688 OverloadCandidate &Candidate =
7689 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
7690 Candidate.FoundDecl = FoundDecl;
7691 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7692 Candidate.Viable = false;
7693 Candidate.RewriteKind =
7694 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
7695 Candidate.IsSurrogate = false;
7696 Candidate.IsADLCandidate = IsADLCandidate;
7697 // Ignore the object argument if there is one, since we don't have an object
7698 // type.
7699 Candidate.IgnoreObjectArgument =
7700 isa<CXXMethodDecl>(Val: Candidate.Function) &&
7701 !isa<CXXConstructorDecl>(Val: Candidate.Function);
7702 Candidate.ExplicitCallArguments = Args.size();
7703 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7704 Candidate.FailureKind = ovl_fail_bad_conversion;
7705 else {
7706 Candidate.FailureKind = ovl_fail_bad_deduction;
7707 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result,
7708 Info);
7709 }
7710 return;
7711 }
7712
7713 // Add the function template specialization produced by template argument
7714 // deduction as a candidate.
7715 assert(Specialization && "Missing function template specialization?");
7716 AddOverloadCandidate(
7717 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7718 PartialOverloading, AllowExplicit,
7719 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
7720 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity);
7721}
7722
7723bool Sema::CheckNonDependentConversions(
7724 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7725 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7726 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7727 CXXRecordDecl *ActingContext, QualType ObjectType,
7728 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7729 // FIXME: The cases in which we allow explicit conversions for constructor
7730 // arguments never consider calling a constructor template. It's not clear
7731 // that is correct.
7732 const bool AllowExplicit = false;
7733
7734 auto *FD = FunctionTemplate->getTemplatedDecl();
7735 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
7736 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Val: Method);
7737 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7738
7739 Conversions =
7740 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
7741
7742 // Overload resolution is always an unevaluated context.
7743 EnterExpressionEvaluationContext Unevaluated(
7744 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7745
7746 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7747 // require that, but this check should never result in a hard error, and
7748 // overload resolution is permitted to sidestep instantiations.
7749 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
7750 !ObjectType.isNull()) {
7751 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7752 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7753 !ParamTypes[0]->isDependentType()) {
7754 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7755 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
7756 Method, ActingContext, /*InOverloadResolution=*/true,
7757 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7758 : QualType());
7759 if (Conversions[ConvIdx].isBad())
7760 return true;
7761 }
7762 }
7763
7764 unsigned Offset =
7765 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7766
7767 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
7768 I != N; ++I) {
7769 QualType ParamType = ParamTypes[I + Offset];
7770 if (!ParamType->isDependentType()) {
7771 unsigned ConvIdx;
7772 if (PO == OverloadCandidateParamOrder::Reversed) {
7773 ConvIdx = Args.size() - 1 - I;
7774 assert(Args.size() + ThisConversions == 2 &&
7775 "number of args (including 'this') must be exactly 2 for "
7776 "reversed order");
7777 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7778 // would also be 0. 'this' got ConvIdx = 1 previously.
7779 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7780 } else {
7781 // For members, 'this' got ConvIdx = 0 previously.
7782 ConvIdx = ThisConversions + I;
7783 }
7784 Conversions[ConvIdx]
7785 = TryCopyInitialization(S&: *this, From: Args[I], ToType: ParamType,
7786 SuppressUserConversions,
7787 /*InOverloadResolution=*/true,
7788 /*AllowObjCWritebackConversion=*/
7789 getLangOpts().ObjCAutoRefCount,
7790 AllowExplicit);
7791 if (Conversions[ConvIdx].isBad())
7792 return true;
7793 }
7794 }
7795
7796 return false;
7797}
7798
7799/// Determine whether this is an allowable conversion from the result
7800/// of an explicit conversion operator to the expected type, per C++
7801/// [over.match.conv]p1 and [over.match.ref]p1.
7802///
7803/// \param ConvType The return type of the conversion function.
7804///
7805/// \param ToType The type we are converting to.
7806///
7807/// \param AllowObjCPointerConversion Allow a conversion from one
7808/// Objective-C pointer to another.
7809///
7810/// \returns true if the conversion is allowable, false otherwise.
7811static bool isAllowableExplicitConversion(Sema &S,
7812 QualType ConvType, QualType ToType,
7813 bool AllowObjCPointerConversion) {
7814 QualType ToNonRefType = ToType.getNonReferenceType();
7815
7816 // Easy case: the types are the same.
7817 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
7818 return true;
7819
7820 // Allow qualification conversions.
7821 bool ObjCLifetimeConversion;
7822 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
7823 ObjCLifetimeConversion))
7824 return true;
7825
7826 // If we're not allowed to consider Objective-C pointer conversions,
7827 // we're done.
7828 if (!AllowObjCPointerConversion)
7829 return false;
7830
7831 // Is this an Objective-C pointer conversion?
7832 bool IncompatibleObjC = false;
7833 QualType ConvertedType;
7834 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
7835 IncompatibleObjC);
7836}
7837
7838void Sema::AddConversionCandidate(
7839 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7840 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7841 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7842 bool AllowExplicit, bool AllowResultConversion) {
7843 assert(!Conversion->getDescribedFunctionTemplate() &&
7844 "Conversion function templates use AddTemplateConversionCandidate");
7845 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7846 if (!CandidateSet.isNewCandidate(F: Conversion))
7847 return;
7848
7849 // If the conversion function has an undeduced return type, trigger its
7850 // deduction now.
7851 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7852 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
7853 return;
7854 ConvType = Conversion->getConversionType().getNonReferenceType();
7855 }
7856
7857 // If we don't allow any conversion of the result type, ignore conversion
7858 // functions that don't convert to exactly (possibly cv-qualified) T.
7859 if (!AllowResultConversion &&
7860 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
7861 return;
7862
7863 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7864 // operator is only a candidate if its return type is the target type or
7865 // can be converted to the target type with a qualification conversion.
7866 //
7867 // FIXME: Include such functions in the candidate list and explain why we
7868 // can't select them.
7869 if (Conversion->isExplicit() &&
7870 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
7871 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
7872 return;
7873
7874 // Overload resolution is always an unevaluated context.
7875 EnterExpressionEvaluationContext Unevaluated(
7876 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7877
7878 // Add this candidate
7879 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
7880 Candidate.FoundDecl = FoundDecl;
7881 Candidate.Function = Conversion;
7882 Candidate.FinalConversion.setAsIdentityConversion();
7883 Candidate.FinalConversion.setFromType(ConvType);
7884 Candidate.FinalConversion.setAllToTypes(ToType);
7885 Candidate.Viable = true;
7886 Candidate.ExplicitCallArguments = 1;
7887
7888 // Explicit functions are not actually candidates at all if we're not
7889 // allowing them in this context, but keep them around so we can point
7890 // to them in diagnostics.
7891 if (!AllowExplicit && Conversion->isExplicit()) {
7892 Candidate.Viable = false;
7893 Candidate.FailureKind = ovl_fail_explicit;
7894 return;
7895 }
7896
7897 // C++ [over.match.funcs]p4:
7898 // For conversion functions, the function is considered to be a member of
7899 // the class of the implicit implied object argument for the purpose of
7900 // defining the type of the implicit object parameter.
7901 //
7902 // Determine the implicit conversion sequence for the implicit
7903 // object parameter.
7904 QualType ObjectType = From->getType();
7905 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
7906 ObjectType = FromPtrType->getPointeeType();
7907 const auto *ConversionContext =
7908 cast<CXXRecordDecl>(Val: ObjectType->castAs<RecordType>()->getDecl());
7909
7910 // C++23 [over.best.ics.general]
7911 // However, if the target is [...]
7912 // - the object parameter of a user-defined conversion function
7913 // [...] user-defined conversion sequences are not considered.
7914 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7915 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
7916 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
7917 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
7918 /*SuppressUserConversion*/ true);
7919
7920 if (Candidate.Conversions[0].isBad()) {
7921 Candidate.Viable = false;
7922 Candidate.FailureKind = ovl_fail_bad_conversion;
7923 return;
7924 }
7925
7926 if (Conversion->getTrailingRequiresClause()) {
7927 ConstraintSatisfaction Satisfaction;
7928 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
7929 !Satisfaction.IsSatisfied) {
7930 Candidate.Viable = false;
7931 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7932 return;
7933 }
7934 }
7935
7936 // We won't go through a user-defined type conversion function to convert a
7937 // derived to base as such conversions are given Conversion Rank. They only
7938 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7939 QualType FromCanon
7940 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
7941 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
7942 if (FromCanon == ToCanon ||
7943 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
7944 Candidate.Viable = false;
7945 Candidate.FailureKind = ovl_fail_trivial_conversion;
7946 return;
7947 }
7948
7949 // To determine what the conversion from the result of calling the
7950 // conversion function to the type we're eventually trying to
7951 // convert to (ToType), we need to synthesize a call to the
7952 // conversion function and attempt copy initialization from it. This
7953 // makes sure that we get the right semantics with respect to
7954 // lvalues/rvalues and the type. Fortunately, we can allocate this
7955 // call on the stack and we don't need its arguments to be
7956 // well-formed.
7957 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7958 VK_LValue, From->getBeginLoc());
7959 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7960 Context.getPointerType(T: Conversion->getType()),
7961 CK_FunctionToPointerDecay, &ConversionRef,
7962 VK_PRValue, FPOptionsOverride());
7963
7964 QualType ConversionType = Conversion->getConversionType();
7965 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
7966 Candidate.Viable = false;
7967 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7968 return;
7969 }
7970
7971 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
7972
7973 // Note that it is safe to allocate CallExpr on the stack here because
7974 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7975 // allocator).
7976 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7977
7978 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7979 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7980 Mem: Buffer, Fn: &ConversionFn, Ty: CallResultType, VK, RParenLoc: From->getBeginLoc());
7981
7982 ImplicitConversionSequence ICS =
7983 TryCopyInitialization(S&: *this, From: TheTemporaryCall, ToType,
7984 /*SuppressUserConversions=*/true,
7985 /*InOverloadResolution=*/false,
7986 /*AllowObjCWritebackConversion=*/false);
7987
7988 switch (ICS.getKind()) {
7989 case ImplicitConversionSequence::StandardConversion:
7990 Candidate.FinalConversion = ICS.Standard;
7991
7992 // C++ [over.ics.user]p3:
7993 // If the user-defined conversion is specified by a specialization of a
7994 // conversion function template, the second standard conversion sequence
7995 // shall have exact match rank.
7996 if (Conversion->getPrimaryTemplate() &&
7997 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
7998 Candidate.Viable = false;
7999 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8000 return;
8001 }
8002
8003 // C++0x [dcl.init.ref]p5:
8004 // In the second case, if the reference is an rvalue reference and
8005 // the second standard conversion sequence of the user-defined
8006 // conversion sequence includes an lvalue-to-rvalue conversion, the
8007 // program is ill-formed.
8008 if (ToType->isRValueReferenceType() &&
8009 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8010 Candidate.Viable = false;
8011 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8012 return;
8013 }
8014 break;
8015
8016 case ImplicitConversionSequence::BadConversion:
8017 Candidate.Viable = false;
8018 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8019 return;
8020
8021 default:
8022 llvm_unreachable(
8023 "Can only end up with a standard conversion sequence or failure");
8024 }
8025
8026 if (EnableIfAttr *FailedAttr =
8027 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: std::nullopt)) {
8028 Candidate.Viable = false;
8029 Candidate.FailureKind = ovl_fail_enable_if;
8030 Candidate.DeductionFailure.Data = FailedAttr;
8031 return;
8032 }
8033
8034 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8035 Candidate.Viable = false;
8036 Candidate.FailureKind = ovl_non_default_multiversion_function;
8037 }
8038}
8039
8040void Sema::AddTemplateConversionCandidate(
8041 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8042 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8043 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8044 bool AllowExplicit, bool AllowResultConversion) {
8045 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8046 "Only conversion function templates permitted here");
8047
8048 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8049 return;
8050
8051 // If the function template has a non-dependent explicit specification,
8052 // exclude it now if appropriate; we are not permitted to perform deduction
8053 // and substitution in this case.
8054 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8055 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8056 Candidate.FoundDecl = FoundDecl;
8057 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8058 Candidate.Viable = false;
8059 Candidate.FailureKind = ovl_fail_explicit;
8060 return;
8061 }
8062
8063 QualType ObjectType = From->getType();
8064 Expr::Classification ObjectClassification = From->Classify(Ctx&: getASTContext());
8065
8066 TemplateDeductionInfo Info(CandidateSet.getLocation());
8067 CXXConversionDecl *Specialization = nullptr;
8068 if (TemplateDeductionResult Result = DeduceTemplateArguments(
8069 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8070 Specialization, Info);
8071 Result != TemplateDeductionResult::Success) {
8072 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8073 Candidate.FoundDecl = FoundDecl;
8074 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8075 Candidate.Viable = false;
8076 Candidate.FailureKind = ovl_fail_bad_deduction;
8077 Candidate.ExplicitCallArguments = 1;
8078 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result,
8079 Info);
8080 return;
8081 }
8082
8083 // Add the conversion function template specialization produced by
8084 // template argument deduction as a candidate.
8085 assert(Specialization && "Missing function template specialization?");
8086 AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext: ActingDC, From, ToType,
8087 CandidateSet, AllowObjCConversionOnExplicit,
8088 AllowExplicit, AllowResultConversion);
8089}
8090
8091void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8092 DeclAccessPair FoundDecl,
8093 CXXRecordDecl *ActingContext,
8094 const FunctionProtoType *Proto,
8095 Expr *Object,
8096 ArrayRef<Expr *> Args,
8097 OverloadCandidateSet& CandidateSet) {
8098 if (!CandidateSet.isNewCandidate(F: Conversion))
8099 return;
8100
8101 // Overload resolution is always an unevaluated context.
8102 EnterExpressionEvaluationContext Unevaluated(
8103 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8104
8105 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8106 Candidate.FoundDecl = FoundDecl;
8107 Candidate.Function = nullptr;
8108 Candidate.Surrogate = Conversion;
8109 Candidate.IsSurrogate = true;
8110 Candidate.Viable = true;
8111 Candidate.ExplicitCallArguments = Args.size();
8112
8113 // Determine the implicit conversion sequence for the implicit
8114 // object parameter.
8115 ImplicitConversionSequence ObjectInit;
8116 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8117 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8118 ToType: Conversion->getParamDecl(i: 0)->getType(),
8119 /*SuppressUserConversions=*/false,
8120 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8121 } else {
8122 ObjectInit = TryObjectArgumentInitialization(
8123 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8124 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8125 }
8126
8127 if (ObjectInit.isBad()) {
8128 Candidate.Viable = false;
8129 Candidate.FailureKind = ovl_fail_bad_conversion;
8130 Candidate.Conversions[0] = ObjectInit;
8131 return;
8132 }
8133
8134 // The first conversion is actually a user-defined conversion whose
8135 // first conversion is ObjectInit's standard conversion (which is
8136 // effectively a reference binding). Record it as such.
8137 Candidate.Conversions[0].setUserDefined();
8138 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8139 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8140 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8141 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8142 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8143 Candidate.Conversions[0].UserDefined.After
8144 = Candidate.Conversions[0].UserDefined.Before;
8145 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8146
8147 // Find the
8148 unsigned NumParams = Proto->getNumParams();
8149
8150 // (C++ 13.3.2p2): A candidate function having fewer than m
8151 // parameters is viable only if it has an ellipsis in its parameter
8152 // list (8.3.5).
8153 if (Args.size() > NumParams && !Proto->isVariadic()) {
8154 Candidate.Viable = false;
8155 Candidate.FailureKind = ovl_fail_too_many_arguments;
8156 return;
8157 }
8158
8159 // Function types don't have any default arguments, so just check if
8160 // we have enough arguments.
8161 if (Args.size() < NumParams) {
8162 // Not enough arguments.
8163 Candidate.Viable = false;
8164 Candidate.FailureKind = ovl_fail_too_few_arguments;
8165 return;
8166 }
8167
8168 // Determine the implicit conversion sequences for each of the
8169 // arguments.
8170 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8171 if (ArgIdx < NumParams) {
8172 // (C++ 13.3.2p3): for F to be a viable function, there shall
8173 // exist for each argument an implicit conversion sequence
8174 // (13.3.3.1) that converts that argument to the corresponding
8175 // parameter of F.
8176 QualType ParamType = Proto->getParamType(i: ArgIdx);
8177 Candidate.Conversions[ArgIdx + 1]
8178 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8179 /*SuppressUserConversions=*/false,
8180 /*InOverloadResolution=*/false,
8181 /*AllowObjCWritebackConversion=*/
8182 getLangOpts().ObjCAutoRefCount);
8183 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8184 Candidate.Viable = false;
8185 Candidate.FailureKind = ovl_fail_bad_conversion;
8186 return;
8187 }
8188 } else {
8189 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8190 // argument for which there is no corresponding parameter is
8191 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8192 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8193 }
8194 }
8195
8196 if (Conversion->getTrailingRequiresClause()) {
8197 ConstraintSatisfaction Satisfaction;
8198 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8199 /*ForOverloadResolution*/ true) ||
8200 !Satisfaction.IsSatisfied) {
8201 Candidate.Viable = false;
8202 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8203 return;
8204 }
8205 }
8206
8207 if (EnableIfAttr *FailedAttr =
8208 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: std::nullopt)) {
8209 Candidate.Viable = false;
8210 Candidate.FailureKind = ovl_fail_enable_if;
8211 Candidate.DeductionFailure.Data = FailedAttr;
8212 return;
8213 }
8214}
8215
8216void Sema::AddNonMemberOperatorCandidates(
8217 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8218 OverloadCandidateSet &CandidateSet,
8219 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8220 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8221 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8222 ArrayRef<Expr *> FunctionArgs = Args;
8223
8224 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8225 FunctionDecl *FD =
8226 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8227
8228 // Don't consider rewritten functions if we're not rewriting.
8229 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8230 continue;
8231
8232 assert(!isa<CXXMethodDecl>(FD) &&
8233 "unqualified operator lookup found a member function");
8234
8235 if (FunTmpl) {
8236 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8237 Args: FunctionArgs, CandidateSet);
8238 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8239 AddTemplateOverloadCandidate(
8240 FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8241 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, SuppressUserConversions: false, PartialOverloading: false,
8242 AllowExplicit: true, IsADLCandidate: ADLCallKind::NotADL, PO: OverloadCandidateParamOrder::Reversed);
8243 } else {
8244 if (ExplicitTemplateArgs)
8245 continue;
8246 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8247 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8248 AddOverloadCandidate(
8249 Function: FD, FoundDecl: F.getPair(), Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8250 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: std::nullopt,
8251 PO: OverloadCandidateParamOrder::Reversed);
8252 }
8253 }
8254}
8255
8256void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8257 SourceLocation OpLoc,
8258 ArrayRef<Expr *> Args,
8259 OverloadCandidateSet &CandidateSet,
8260 OverloadCandidateParamOrder PO) {
8261 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8262
8263 // C++ [over.match.oper]p3:
8264 // For a unary operator @ with an operand of a type whose
8265 // cv-unqualified version is T1, and for a binary operator @ with
8266 // a left operand of a type whose cv-unqualified version is T1 and
8267 // a right operand of a type whose cv-unqualified version is T2,
8268 // three sets of candidate functions, designated member
8269 // candidates, non-member candidates and built-in candidates, are
8270 // constructed as follows:
8271 QualType T1 = Args[0]->getType();
8272
8273 // -- If T1 is a complete class type or a class currently being
8274 // defined, the set of member candidates is the result of the
8275 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8276 // the set of member candidates is empty.
8277 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8278 // Complete the type if it can be completed.
8279 if (!isCompleteType(Loc: OpLoc, T: T1) && !T1Rec->isBeingDefined())
8280 return;
8281 // If the type is neither complete nor being defined, bail out now.
8282 if (!T1Rec->getDecl()->getDefinition())
8283 return;
8284
8285 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8286 LookupQualifiedName(R&: Operators, LookupCtx: T1Rec->getDecl());
8287 Operators.suppressAccessDiagnostics();
8288
8289 for (LookupResult::iterator Oper = Operators.begin(),
8290 OperEnd = Operators.end();
8291 Oper != OperEnd; ++Oper) {
8292 if (Oper->getAsFunction() &&
8293 PO == OverloadCandidateParamOrder::Reversed &&
8294 !CandidateSet.getRewriteInfo().shouldAddReversed(
8295 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8296 continue;
8297 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8298 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8299 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
8300 }
8301 }
8302}
8303
8304void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8305 OverloadCandidateSet& CandidateSet,
8306 bool IsAssignmentOperator,
8307 unsigned NumContextualBoolArguments) {
8308 // Overload resolution is always an unevaluated context.
8309 EnterExpressionEvaluationContext Unevaluated(
8310 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8311
8312 // Add this candidate
8313 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
8314 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
8315 Candidate.Function = nullptr;
8316 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8317
8318 // Determine the implicit conversion sequences for each of the
8319 // arguments.
8320 Candidate.Viable = true;
8321 Candidate.ExplicitCallArguments = Args.size();
8322 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8323 // C++ [over.match.oper]p4:
8324 // For the built-in assignment operators, conversions of the
8325 // left operand are restricted as follows:
8326 // -- no temporaries are introduced to hold the left operand, and
8327 // -- no user-defined conversions are applied to the left
8328 // operand to achieve a type match with the left-most
8329 // parameter of a built-in candidate.
8330 //
8331 // We block these conversions by turning off user-defined
8332 // conversions, since that is the only way that initialization of
8333 // a reference to a non-class type can occur from something that
8334 // is not of the same type.
8335 if (ArgIdx < NumContextualBoolArguments) {
8336 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8337 "Contextual conversion to bool requires bool type");
8338 Candidate.Conversions[ArgIdx]
8339 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
8340 } else {
8341 Candidate.Conversions[ArgIdx]
8342 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
8343 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
8344 /*InOverloadResolution=*/false,
8345 /*AllowObjCWritebackConversion=*/
8346 getLangOpts().ObjCAutoRefCount);
8347 }
8348 if (Candidate.Conversions[ArgIdx].isBad()) {
8349 Candidate.Viable = false;
8350 Candidate.FailureKind = ovl_fail_bad_conversion;
8351 break;
8352 }
8353 }
8354}
8355
8356namespace {
8357
8358/// BuiltinCandidateTypeSet - A set of types that will be used for the
8359/// candidate operator functions for built-in operators (C++
8360/// [over.built]). The types are separated into pointer types and
8361/// enumeration types.
8362class BuiltinCandidateTypeSet {
8363 /// TypeSet - A set of types.
8364 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8365
8366 /// PointerTypes - The set of pointer types that will be used in the
8367 /// built-in candidates.
8368 TypeSet PointerTypes;
8369
8370 /// MemberPointerTypes - The set of member pointer types that will be
8371 /// used in the built-in candidates.
8372 TypeSet MemberPointerTypes;
8373
8374 /// EnumerationTypes - The set of enumeration types that will be
8375 /// used in the built-in candidates.
8376 TypeSet EnumerationTypes;
8377
8378 /// The set of vector types that will be used in the built-in
8379 /// candidates.
8380 TypeSet VectorTypes;
8381
8382 /// The set of matrix types that will be used in the built-in
8383 /// candidates.
8384 TypeSet MatrixTypes;
8385
8386 /// The set of _BitInt types that will be used in the built-in candidates.
8387 TypeSet BitIntTypes;
8388
8389 /// A flag indicating non-record types are viable candidates
8390 bool HasNonRecordTypes;
8391
8392 /// A flag indicating whether either arithmetic or enumeration types
8393 /// were present in the candidate set.
8394 bool HasArithmeticOrEnumeralTypes;
8395
8396 /// A flag indicating whether the nullptr type was present in the
8397 /// candidate set.
8398 bool HasNullPtrType;
8399
8400 /// Sema - The semantic analysis instance where we are building the
8401 /// candidate type set.
8402 Sema &SemaRef;
8403
8404 /// Context - The AST context in which we will build the type sets.
8405 ASTContext &Context;
8406
8407 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8408 const Qualifiers &VisibleQuals);
8409 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8410
8411public:
8412 /// iterator - Iterates through the types that are part of the set.
8413 typedef TypeSet::iterator iterator;
8414
8415 BuiltinCandidateTypeSet(Sema &SemaRef)
8416 : HasNonRecordTypes(false),
8417 HasArithmeticOrEnumeralTypes(false),
8418 HasNullPtrType(false),
8419 SemaRef(SemaRef),
8420 Context(SemaRef.Context) { }
8421
8422 void AddTypesConvertedFrom(QualType Ty,
8423 SourceLocation Loc,
8424 bool AllowUserConversions,
8425 bool AllowExplicitConversions,
8426 const Qualifiers &VisibleTypeConversionsQuals);
8427
8428 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8429 llvm::iterator_range<iterator> member_pointer_types() {
8430 return MemberPointerTypes;
8431 }
8432 llvm::iterator_range<iterator> enumeration_types() {
8433 return EnumerationTypes;
8434 }
8435 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8436 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8437 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8438
8439 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
8440 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8441 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8442 bool hasNullPtrType() const { return HasNullPtrType; }
8443};
8444
8445} // end anonymous namespace
8446
8447/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8448/// the set of pointer types along with any more-qualified variants of
8449/// that type. For example, if @p Ty is "int const *", this routine
8450/// will add "int const *", "int const volatile *", "int const
8451/// restrict *", and "int const volatile restrict *" to the set of
8452/// pointer types. Returns true if the add of @p Ty itself succeeded,
8453/// false otherwise.
8454///
8455/// FIXME: what to do about extended qualifiers?
8456bool
8457BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8458 const Qualifiers &VisibleQuals) {
8459
8460 // Insert this type.
8461 if (!PointerTypes.insert(X: Ty))
8462 return false;
8463
8464 QualType PointeeTy;
8465 const PointerType *PointerTy = Ty->getAs<PointerType>();
8466 bool buildObjCPtr = false;
8467 if (!PointerTy) {
8468 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8469 PointeeTy = PTy->getPointeeType();
8470 buildObjCPtr = true;
8471 } else {
8472 PointeeTy = PointerTy->getPointeeType();
8473 }
8474
8475 // Don't add qualified variants of arrays. For one, they're not allowed
8476 // (the qualifier would sink to the element type), and for another, the
8477 // only overload situation where it matters is subscript or pointer +- int,
8478 // and those shouldn't have qualifier variants anyway.
8479 if (PointeeTy->isArrayType())
8480 return true;
8481
8482 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8483 bool hasVolatile = VisibleQuals.hasVolatile();
8484 bool hasRestrict = VisibleQuals.hasRestrict();
8485
8486 // Iterate through all strict supersets of BaseCVR.
8487 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8488 if ((CVR | BaseCVR) != CVR) continue;
8489 // Skip over volatile if no volatile found anywhere in the types.
8490 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8491
8492 // Skip over restrict if no restrict found anywhere in the types, or if
8493 // the type cannot be restrict-qualified.
8494 if ((CVR & Qualifiers::Restrict) &&
8495 (!hasRestrict ||
8496 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8497 continue;
8498
8499 // Build qualified pointee type.
8500 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
8501
8502 // Build qualified pointer type.
8503 QualType QPointerTy;
8504 if (!buildObjCPtr)
8505 QPointerTy = Context.getPointerType(T: QPointeeTy);
8506 else
8507 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
8508
8509 // Insert qualified pointer type.
8510 PointerTypes.insert(X: QPointerTy);
8511 }
8512
8513 return true;
8514}
8515
8516/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8517/// to the set of pointer types along with any more-qualified variants of
8518/// that type. For example, if @p Ty is "int const *", this routine
8519/// will add "int const *", "int const volatile *", "int const
8520/// restrict *", and "int const volatile restrict *" to the set of
8521/// pointer types. Returns true if the add of @p Ty itself succeeded,
8522/// false otherwise.
8523///
8524/// FIXME: what to do about extended qualifiers?
8525bool
8526BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8527 QualType Ty) {
8528 // Insert this type.
8529 if (!MemberPointerTypes.insert(X: Ty))
8530 return false;
8531
8532 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8533 assert(PointerTy && "type was not a member pointer type!");
8534
8535 QualType PointeeTy = PointerTy->getPointeeType();
8536 // Don't add qualified variants of arrays. For one, they're not allowed
8537 // (the qualifier would sink to the element type), and for another, the
8538 // only overload situation where it matters is subscript or pointer +- int,
8539 // and those shouldn't have qualifier variants anyway.
8540 if (PointeeTy->isArrayType())
8541 return true;
8542 const Type *ClassTy = PointerTy->getClass();
8543
8544 // Iterate through all strict supersets of the pointee type's CVR
8545 // qualifiers.
8546 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8547 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8548 if ((CVR | BaseCVR) != CVR) continue;
8549
8550 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
8551 MemberPointerTypes.insert(
8552 X: Context.getMemberPointerType(T: QPointeeTy, Cls: ClassTy));
8553 }
8554
8555 return true;
8556}
8557
8558/// AddTypesConvertedFrom - Add each of the types to which the type @p
8559/// Ty can be implicit converted to the given set of @p Types. We're
8560/// primarily interested in pointer types and enumeration types. We also
8561/// take member pointer types, for the conditional operator.
8562/// AllowUserConversions is true if we should look at the conversion
8563/// functions of a class type, and AllowExplicitConversions if we
8564/// should also include the explicit conversion functions of a class
8565/// type.
8566void
8567BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8568 SourceLocation Loc,
8569 bool AllowUserConversions,
8570 bool AllowExplicitConversions,
8571 const Qualifiers &VisibleQuals) {
8572 // Only deal with canonical types.
8573 Ty = Context.getCanonicalType(T: Ty);
8574
8575 // Look through reference types; they aren't part of the type of an
8576 // expression for the purposes of conversions.
8577 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8578 Ty = RefTy->getPointeeType();
8579
8580 // If we're dealing with an array type, decay to the pointer.
8581 if (Ty->isArrayType())
8582 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
8583
8584 // Otherwise, we don't care about qualifiers on the type.
8585 Ty = Ty.getLocalUnqualifiedType();
8586
8587 // Flag if we ever add a non-record type.
8588 const RecordType *TyRec = Ty->getAs<RecordType>();
8589 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8590
8591 // Flag if we encounter an arithmetic type.
8592 HasArithmeticOrEnumeralTypes =
8593 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8594
8595 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8596 PointerTypes.insert(X: Ty);
8597 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8598 // Insert our type, and its more-qualified variants, into the set
8599 // of types.
8600 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8601 return;
8602 } else if (Ty->isMemberPointerType()) {
8603 // Member pointers are far easier, since the pointee can't be converted.
8604 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8605 return;
8606 } else if (Ty->isEnumeralType()) {
8607 HasArithmeticOrEnumeralTypes = true;
8608 EnumerationTypes.insert(X: Ty);
8609 } else if (Ty->isBitIntType()) {
8610 HasArithmeticOrEnumeralTypes = true;
8611 BitIntTypes.insert(X: Ty);
8612 } else if (Ty->isVectorType()) {
8613 // We treat vector types as arithmetic types in many contexts as an
8614 // extension.
8615 HasArithmeticOrEnumeralTypes = true;
8616 VectorTypes.insert(X: Ty);
8617 } else if (Ty->isMatrixType()) {
8618 // Similar to vector types, we treat vector types as arithmetic types in
8619 // many contexts as an extension.
8620 HasArithmeticOrEnumeralTypes = true;
8621 MatrixTypes.insert(X: Ty);
8622 } else if (Ty->isNullPtrType()) {
8623 HasNullPtrType = true;
8624 } else if (AllowUserConversions && TyRec) {
8625 // No conversion functions in incomplete types.
8626 if (!SemaRef.isCompleteType(Loc, T: Ty))
8627 return;
8628
8629 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: TyRec->getDecl());
8630 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8631 if (isa<UsingShadowDecl>(Val: D))
8632 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
8633
8634 // Skip conversion function templates; they don't tell us anything
8635 // about which builtin types we can convert to.
8636 if (isa<FunctionTemplateDecl>(Val: D))
8637 continue;
8638
8639 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
8640 if (AllowExplicitConversions || !Conv->isExplicit()) {
8641 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
8642 VisibleQuals);
8643 }
8644 }
8645 }
8646}
8647/// Helper function for adjusting address spaces for the pointer or reference
8648/// operands of builtin operators depending on the argument.
8649static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8650 Expr *Arg) {
8651 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
8652}
8653
8654/// Helper function for AddBuiltinOperatorCandidates() that adds
8655/// the volatile- and non-volatile-qualified assignment operators for the
8656/// given type to the candidate set.
8657static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8658 QualType T,
8659 ArrayRef<Expr *> Args,
8660 OverloadCandidateSet &CandidateSet) {
8661 QualType ParamTypes[2];
8662
8663 // T& operator=(T&, T)
8664 ParamTypes[0] = S.Context.getLValueReferenceType(
8665 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
8666 ParamTypes[1] = T;
8667 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
8668 /*IsAssignmentOperator=*/true);
8669
8670 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8671 // volatile T& operator=(volatile T&, T)
8672 ParamTypes[0] = S.Context.getLValueReferenceType(
8673 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
8674 Arg: Args[0]));
8675 ParamTypes[1] = T;
8676 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
8677 /*IsAssignmentOperator=*/true);
8678 }
8679}
8680
8681/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8682/// if any, found in visible type conversion functions found in ArgExpr's type.
8683static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8684 Qualifiers VRQuals;
8685 const RecordType *TyRec;
8686 if (const MemberPointerType *RHSMPType =
8687 ArgExpr->getType()->getAs<MemberPointerType>())
8688 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8689 else
8690 TyRec = ArgExpr->getType()->getAs<RecordType>();
8691 if (!TyRec) {
8692 // Just to be safe, assume the worst case.
8693 VRQuals.addVolatile();
8694 VRQuals.addRestrict();
8695 return VRQuals;
8696 }
8697
8698 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: TyRec->getDecl());
8699 if (!ClassDecl->hasDefinition())
8700 return VRQuals;
8701
8702 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8703 if (isa<UsingShadowDecl>(Val: D))
8704 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
8705 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
8706 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
8707 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8708 CanTy = ResTypeRef->getPointeeType();
8709 // Need to go down the pointer/mempointer chain and add qualifiers
8710 // as see them.
8711 bool done = false;
8712 while (!done) {
8713 if (CanTy.isRestrictQualified())
8714 VRQuals.addRestrict();
8715 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8716 CanTy = ResTypePtr->getPointeeType();
8717 else if (const MemberPointerType *ResTypeMPtr =
8718 CanTy->getAs<MemberPointerType>())
8719 CanTy = ResTypeMPtr->getPointeeType();
8720 else
8721 done = true;
8722 if (CanTy.isVolatileQualified())
8723 VRQuals.addVolatile();
8724 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8725 return VRQuals;
8726 }
8727 }
8728 }
8729 return VRQuals;
8730}
8731
8732// Note: We're currently only handling qualifiers that are meaningful for the
8733// LHS of compound assignment overloading.
8734static void forAllQualifierCombinationsImpl(
8735 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8736 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8737 // _Atomic
8738 if (Available.hasAtomic()) {
8739 Available.removeAtomic();
8740 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
8741 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8742 return;
8743 }
8744
8745 // volatile
8746 if (Available.hasVolatile()) {
8747 Available.removeVolatile();
8748 assert(!Applied.hasVolatile());
8749 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
8750 Callback);
8751 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8752 return;
8753 }
8754
8755 Callback(Applied);
8756}
8757
8758static void forAllQualifierCombinations(
8759 QualifiersAndAtomic Quals,
8760 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8761 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
8762 Callback);
8763}
8764
8765static QualType makeQualifiedLValueReferenceType(QualType Base,
8766 QualifiersAndAtomic Quals,
8767 Sema &S) {
8768 if (Quals.hasAtomic())
8769 Base = S.Context.getAtomicType(T: Base);
8770 if (Quals.hasVolatile())
8771 Base = S.Context.getVolatileType(T: Base);
8772 return S.Context.getLValueReferenceType(T: Base);
8773}
8774
8775namespace {
8776
8777/// Helper class to manage the addition of builtin operator overload
8778/// candidates. It provides shared state and utility methods used throughout
8779/// the process, as well as a helper method to add each group of builtin
8780/// operator overloads from the standard to a candidate set.
8781class BuiltinOperatorOverloadBuilder {
8782 // Common instance state available to all overload candidate addition methods.
8783 Sema &S;
8784 ArrayRef<Expr *> Args;
8785 QualifiersAndAtomic VisibleTypeConversionsQuals;
8786 bool HasArithmeticOrEnumeralCandidateType;
8787 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8788 OverloadCandidateSet &CandidateSet;
8789
8790 static constexpr int ArithmeticTypesCap = 26;
8791 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8792
8793 // Define some indices used to iterate over the arithmetic types in
8794 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8795 // types are that preserved by promotion (C++ [over.built]p2).
8796 unsigned FirstIntegralType,
8797 LastIntegralType;
8798 unsigned FirstPromotedIntegralType,
8799 LastPromotedIntegralType;
8800 unsigned FirstPromotedArithmeticType,
8801 LastPromotedArithmeticType;
8802 unsigned NumArithmeticTypes;
8803
8804 void InitArithmeticTypes() {
8805 // Start of promoted types.
8806 FirstPromotedArithmeticType = 0;
8807 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
8808 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
8809 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
8810 if (S.Context.getTargetInfo().hasFloat128Type())
8811 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
8812 if (S.Context.getTargetInfo().hasIbm128Type())
8813 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
8814
8815 // Start of integral types.
8816 FirstIntegralType = ArithmeticTypes.size();
8817 FirstPromotedIntegralType = ArithmeticTypes.size();
8818 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
8819 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
8820 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
8821 if (S.Context.getTargetInfo().hasInt128Type() ||
8822 (S.Context.getAuxTargetInfo() &&
8823 S.Context.getAuxTargetInfo()->hasInt128Type()))
8824 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
8825 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
8826 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
8827 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
8828 if (S.Context.getTargetInfo().hasInt128Type() ||
8829 (S.Context.getAuxTargetInfo() &&
8830 S.Context.getAuxTargetInfo()->hasInt128Type()))
8831 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
8832
8833 /// We add candidates for the unique, unqualified _BitInt types present in
8834 /// the candidate type set. The candidate set already handled ensuring the
8835 /// type is unqualified and canonical, but because we're adding from N
8836 /// different sets, we need to do some extra work to unique things. Insert
8837 /// the candidates into a unique set, then move from that set into the list
8838 /// of arithmetic types.
8839 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8840 llvm::for_each(Range&: CandidateTypes, F: [&BitIntCandidates](
8841 BuiltinCandidateTypeSet &Candidate) {
8842 for (QualType BitTy : Candidate.bitint_types())
8843 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
8844 });
8845 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
8846 LastPromotedIntegralType = ArithmeticTypes.size();
8847 LastPromotedArithmeticType = ArithmeticTypes.size();
8848 // End of promoted types.
8849
8850 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
8851 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
8852 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
8853 if (S.Context.getLangOpts().Char8)
8854 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
8855 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
8856 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
8857 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
8858 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
8859 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
8860 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
8861 LastIntegralType = ArithmeticTypes.size();
8862 NumArithmeticTypes = ArithmeticTypes.size();
8863 // End of integral types.
8864 // FIXME: What about complex? What about half?
8865
8866 // We don't know for sure how many bit-precise candidates were involved, so
8867 // we subtract those from the total when testing whether we're under the
8868 // cap or not.
8869 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
8870 ArithmeticTypesCap &&
8871 "Enough inline storage for all arithmetic types.");
8872 }
8873
8874 /// Helper method to factor out the common pattern of adding overloads
8875 /// for '++' and '--' builtin operators.
8876 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8877 bool HasVolatile,
8878 bool HasRestrict) {
8879 QualType ParamTypes[2] = {
8880 S.Context.getLValueReferenceType(T: CandidateTy),
8881 S.Context.IntTy
8882 };
8883
8884 // Non-volatile version.
8885 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
8886
8887 // Use a heuristic to reduce number of builtin candidates in the set:
8888 // add volatile version only if there are conversions to a volatile type.
8889 if (HasVolatile) {
8890 ParamTypes[0] =
8891 S.Context.getLValueReferenceType(
8892 T: S.Context.getVolatileType(T: CandidateTy));
8893 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
8894 }
8895
8896 // Add restrict version only if there are conversions to a restrict type
8897 // and our candidate type is a non-restrict-qualified pointer.
8898 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8899 !CandidateTy.isRestrictQualified()) {
8900 ParamTypes[0]
8901 = S.Context.getLValueReferenceType(
8902 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
8903 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
8904
8905 if (HasVolatile) {
8906 ParamTypes[0]
8907 = S.Context.getLValueReferenceType(
8908 T: S.Context.getCVRQualifiedType(T: CandidateTy,
8909 CVR: (Qualifiers::Volatile |
8910 Qualifiers::Restrict)));
8911 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
8912 }
8913 }
8914
8915 }
8916
8917 /// Helper to add an overload candidate for a binary builtin with types \p L
8918 /// and \p R.
8919 void AddCandidate(QualType L, QualType R) {
8920 QualType LandR[2] = {L, R};
8921 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
8922 }
8923
8924public:
8925 BuiltinOperatorOverloadBuilder(
8926 Sema &S, ArrayRef<Expr *> Args,
8927 QualifiersAndAtomic VisibleTypeConversionsQuals,
8928 bool HasArithmeticOrEnumeralCandidateType,
8929 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8930 OverloadCandidateSet &CandidateSet)
8931 : S(S), Args(Args),
8932 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8933 HasArithmeticOrEnumeralCandidateType(
8934 HasArithmeticOrEnumeralCandidateType),
8935 CandidateTypes(CandidateTypes),
8936 CandidateSet(CandidateSet) {
8937
8938 InitArithmeticTypes();
8939 }
8940
8941 // Increment is deprecated for bool since C++17.
8942 //
8943 // C++ [over.built]p3:
8944 //
8945 // For every pair (T, VQ), where T is an arithmetic type other
8946 // than bool, and VQ is either volatile or empty, there exist
8947 // candidate operator functions of the form
8948 //
8949 // VQ T& operator++(VQ T&);
8950 // T operator++(VQ T&, int);
8951 //
8952 // C++ [over.built]p4:
8953 //
8954 // For every pair (T, VQ), where T is an arithmetic type other
8955 // than bool, and VQ is either volatile or empty, there exist
8956 // candidate operator functions of the form
8957 //
8958 // VQ T& operator--(VQ T&);
8959 // T operator--(VQ T&, int);
8960 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8961 if (!HasArithmeticOrEnumeralCandidateType)
8962 return;
8963
8964 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8965 const auto TypeOfT = ArithmeticTypes[Arith];
8966 if (TypeOfT == S.Context.BoolTy) {
8967 if (Op == OO_MinusMinus)
8968 continue;
8969 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8970 continue;
8971 }
8972 addPlusPlusMinusMinusStyleOverloads(
8973 CandidateTy: TypeOfT,
8974 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
8975 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
8976 }
8977 }
8978
8979 // C++ [over.built]p5:
8980 //
8981 // For every pair (T, VQ), where T is a cv-qualified or
8982 // cv-unqualified object type, and VQ is either volatile or
8983 // empty, there exist candidate operator functions of the form
8984 //
8985 // T*VQ& operator++(T*VQ&);
8986 // T*VQ& operator--(T*VQ&);
8987 // T* operator++(T*VQ&, int);
8988 // T* operator--(T*VQ&, int);
8989 void addPlusPlusMinusMinusPointerOverloads() {
8990 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8991 // Skip pointer types that aren't pointers to object types.
8992 if (!PtrTy->getPointeeType()->isObjectType())
8993 continue;
8994
8995 addPlusPlusMinusMinusStyleOverloads(
8996 CandidateTy: PtrTy,
8997 HasVolatile: (!PtrTy.isVolatileQualified() &&
8998 VisibleTypeConversionsQuals.hasVolatile()),
8999 HasRestrict: (!PtrTy.isRestrictQualified() &&
9000 VisibleTypeConversionsQuals.hasRestrict()));
9001 }
9002 }
9003
9004 // C++ [over.built]p6:
9005 // For every cv-qualified or cv-unqualified object type T, there
9006 // exist candidate operator functions of the form
9007 //
9008 // T& operator*(T*);
9009 //
9010 // C++ [over.built]p7:
9011 // For every function type T that does not have cv-qualifiers or a
9012 // ref-qualifier, there exist candidate operator functions of the form
9013 // T& operator*(T*);
9014 void addUnaryStarPointerOverloads() {
9015 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9016 QualType PointeeTy = ParamTy->getPointeeType();
9017 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9018 continue;
9019
9020 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9021 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9022 continue;
9023
9024 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9025 }
9026 }
9027
9028 // C++ [over.built]p9:
9029 // For every promoted arithmetic type T, there exist candidate
9030 // operator functions of the form
9031 //
9032 // T operator+(T);
9033 // T operator-(T);
9034 void addUnaryPlusOrMinusArithmeticOverloads() {
9035 if (!HasArithmeticOrEnumeralCandidateType)
9036 return;
9037
9038 for (unsigned Arith = FirstPromotedArithmeticType;
9039 Arith < LastPromotedArithmeticType; ++Arith) {
9040 QualType ArithTy = ArithmeticTypes[Arith];
9041 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9042 }
9043
9044 // Extension: We also add these operators for vector types.
9045 for (QualType VecTy : CandidateTypes[0].vector_types())
9046 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9047 }
9048
9049 // C++ [over.built]p8:
9050 // For every type T, there exist candidate operator functions of
9051 // the form
9052 //
9053 // T* operator+(T*);
9054 void addUnaryPlusPointerOverloads() {
9055 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9056 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9057 }
9058
9059 // C++ [over.built]p10:
9060 // For every promoted integral type T, there exist candidate
9061 // operator functions of the form
9062 //
9063 // T operator~(T);
9064 void addUnaryTildePromotedIntegralOverloads() {
9065 if (!HasArithmeticOrEnumeralCandidateType)
9066 return;
9067
9068 for (unsigned Int = FirstPromotedIntegralType;
9069 Int < LastPromotedIntegralType; ++Int) {
9070 QualType IntTy = ArithmeticTypes[Int];
9071 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9072 }
9073
9074 // Extension: We also add this operator for vector types.
9075 for (QualType VecTy : CandidateTypes[0].vector_types())
9076 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9077 }
9078
9079 // C++ [over.match.oper]p16:
9080 // For every pointer to member type T or type std::nullptr_t, there
9081 // exist candidate operator functions of the form
9082 //
9083 // bool operator==(T,T);
9084 // bool operator!=(T,T);
9085 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9086 /// Set of (canonical) types that we've already handled.
9087 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9088
9089 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9090 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9091 // Don't add the same builtin candidate twice.
9092 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9093 continue;
9094
9095 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9096 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9097 }
9098
9099 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9100 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9101 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9102 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9103 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9104 }
9105 }
9106 }
9107 }
9108
9109 // C++ [over.built]p15:
9110 //
9111 // For every T, where T is an enumeration type or a pointer type,
9112 // there exist candidate operator functions of the form
9113 //
9114 // bool operator<(T, T);
9115 // bool operator>(T, T);
9116 // bool operator<=(T, T);
9117 // bool operator>=(T, T);
9118 // bool operator==(T, T);
9119 // bool operator!=(T, T);
9120 // R operator<=>(T, T)
9121 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9122 // C++ [over.match.oper]p3:
9123 // [...]the built-in candidates include all of the candidate operator
9124 // functions defined in 13.6 that, compared to the given operator, [...]
9125 // do not have the same parameter-type-list as any non-template non-member
9126 // candidate.
9127 //
9128 // Note that in practice, this only affects enumeration types because there
9129 // aren't any built-in candidates of record type, and a user-defined operator
9130 // must have an operand of record or enumeration type. Also, the only other
9131 // overloaded operator with enumeration arguments, operator=,
9132 // cannot be overloaded for enumeration types, so this is the only place
9133 // where we must suppress candidates like this.
9134 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9135 UserDefinedBinaryOperators;
9136
9137 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9138 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9139 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9140 CEnd = CandidateSet.end();
9141 C != CEnd; ++C) {
9142 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9143 continue;
9144
9145 if (C->Function->isFunctionTemplateSpecialization())
9146 continue;
9147
9148 // We interpret "same parameter-type-list" as applying to the
9149 // "synthesized candidate, with the order of the two parameters
9150 // reversed", not to the original function.
9151 bool Reversed = C->isReversed();
9152 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9153 ->getType()
9154 .getUnqualifiedType();
9155 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9156 ->getType()
9157 .getUnqualifiedType();
9158
9159 // Skip if either parameter isn't of enumeral type.
9160 if (!FirstParamType->isEnumeralType() ||
9161 !SecondParamType->isEnumeralType())
9162 continue;
9163
9164 // Add this operator to the set of known user-defined operators.
9165 UserDefinedBinaryOperators.insert(
9166 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9167 y: S.Context.getCanonicalType(T: SecondParamType)));
9168 }
9169 }
9170 }
9171
9172 /// Set of (canonical) types that we've already handled.
9173 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9174
9175 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9176 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9177 // Don't add the same builtin candidate twice.
9178 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9179 continue;
9180 if (IsSpaceship && PtrTy->isFunctionPointerType())
9181 continue;
9182
9183 QualType ParamTypes[2] = {PtrTy, PtrTy};
9184 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9185 }
9186 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9187 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9188
9189 // Don't add the same builtin candidate twice, or if a user defined
9190 // candidate exists.
9191 if (!AddedTypes.insert(Ptr: CanonType).second ||
9192 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9193 y&: CanonType)))
9194 continue;
9195 QualType ParamTypes[2] = {EnumTy, EnumTy};
9196 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9197 }
9198 }
9199 }
9200
9201 // C++ [over.built]p13:
9202 //
9203 // For every cv-qualified or cv-unqualified object type T
9204 // there exist candidate operator functions of the form
9205 //
9206 // T* operator+(T*, ptrdiff_t);
9207 // T& operator[](T*, ptrdiff_t); [BELOW]
9208 // T* operator-(T*, ptrdiff_t);
9209 // T* operator+(ptrdiff_t, T*);
9210 // T& operator[](ptrdiff_t, T*); [BELOW]
9211 //
9212 // C++ [over.built]p14:
9213 //
9214 // For every T, where T is a pointer to object type, there
9215 // exist candidate operator functions of the form
9216 //
9217 // ptrdiff_t operator-(T, T);
9218 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9219 /// Set of (canonical) types that we've already handled.
9220 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9221
9222 for (int Arg = 0; Arg < 2; ++Arg) {
9223 QualType AsymmetricParamTypes[2] = {
9224 S.Context.getPointerDiffType(),
9225 S.Context.getPointerDiffType(),
9226 };
9227 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9228 QualType PointeeTy = PtrTy->getPointeeType();
9229 if (!PointeeTy->isObjectType())
9230 continue;
9231
9232 AsymmetricParamTypes[Arg] = PtrTy;
9233 if (Arg == 0 || Op == OO_Plus) {
9234 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9235 // T* operator+(ptrdiff_t, T*);
9236 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9237 }
9238 if (Op == OO_Minus) {
9239 // ptrdiff_t operator-(T, T);
9240 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9241 continue;
9242
9243 QualType ParamTypes[2] = {PtrTy, PtrTy};
9244 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9245 }
9246 }
9247 }
9248 }
9249
9250 // C++ [over.built]p12:
9251 //
9252 // For every pair of promoted arithmetic types L and R, there
9253 // exist candidate operator functions of the form
9254 //
9255 // LR operator*(L, R);
9256 // LR operator/(L, R);
9257 // LR operator+(L, R);
9258 // LR operator-(L, R);
9259 // bool operator<(L, R);
9260 // bool operator>(L, R);
9261 // bool operator<=(L, R);
9262 // bool operator>=(L, R);
9263 // bool operator==(L, R);
9264 // bool operator!=(L, R);
9265 //
9266 // where LR is the result of the usual arithmetic conversions
9267 // between types L and R.
9268 //
9269 // C++ [over.built]p24:
9270 //
9271 // For every pair of promoted arithmetic types L and R, there exist
9272 // candidate operator functions of the form
9273 //
9274 // LR operator?(bool, L, R);
9275 //
9276 // where LR is the result of the usual arithmetic conversions
9277 // between types L and R.
9278 // Our candidates ignore the first parameter.
9279 void addGenericBinaryArithmeticOverloads() {
9280 if (!HasArithmeticOrEnumeralCandidateType)
9281 return;
9282
9283 for (unsigned Left = FirstPromotedArithmeticType;
9284 Left < LastPromotedArithmeticType; ++Left) {
9285 for (unsigned Right = FirstPromotedArithmeticType;
9286 Right < LastPromotedArithmeticType; ++Right) {
9287 QualType LandR[2] = { ArithmeticTypes[Left],
9288 ArithmeticTypes[Right] };
9289 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9290 }
9291 }
9292
9293 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9294 // conditional operator for vector types.
9295 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9296 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9297 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9298 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9299 }
9300 }
9301
9302 /// Add binary operator overloads for each candidate matrix type M1, M2:
9303 /// * (M1, M1) -> M1
9304 /// * (M1, M1.getElementType()) -> M1
9305 /// * (M2.getElementType(), M2) -> M2
9306 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9307 void addMatrixBinaryArithmeticOverloads() {
9308 if (!HasArithmeticOrEnumeralCandidateType)
9309 return;
9310
9311 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9312 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
9313 AddCandidate(L: M1, R: M1);
9314 }
9315
9316 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9317 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
9318 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
9319 AddCandidate(L: M2, R: M2);
9320 }
9321 }
9322
9323 // C++2a [over.built]p14:
9324 //
9325 // For every integral type T there exists a candidate operator function
9326 // of the form
9327 //
9328 // std::strong_ordering operator<=>(T, T)
9329 //
9330 // C++2a [over.built]p15:
9331 //
9332 // For every pair of floating-point types L and R, there exists a candidate
9333 // operator function of the form
9334 //
9335 // std::partial_ordering operator<=>(L, R);
9336 //
9337 // FIXME: The current specification for integral types doesn't play nice with
9338 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9339 // comparisons. Under the current spec this can lead to ambiguity during
9340 // overload resolution. For example:
9341 //
9342 // enum A : int {a};
9343 // auto x = (a <=> (long)42);
9344 //
9345 // error: call is ambiguous for arguments 'A' and 'long'.
9346 // note: candidate operator<=>(int, int)
9347 // note: candidate operator<=>(long, long)
9348 //
9349 // To avoid this error, this function deviates from the specification and adds
9350 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9351 // arithmetic types (the same as the generic relational overloads).
9352 //
9353 // For now this function acts as a placeholder.
9354 void addThreeWayArithmeticOverloads() {
9355 addGenericBinaryArithmeticOverloads();
9356 }
9357
9358 // C++ [over.built]p17:
9359 //
9360 // For every pair of promoted integral types L and R, there
9361 // exist candidate operator functions of the form
9362 //
9363 // LR operator%(L, R);
9364 // LR operator&(L, R);
9365 // LR operator^(L, R);
9366 // LR operator|(L, R);
9367 // L operator<<(L, R);
9368 // L operator>>(L, R);
9369 //
9370 // where LR is the result of the usual arithmetic conversions
9371 // between types L and R.
9372 void addBinaryBitwiseArithmeticOverloads() {
9373 if (!HasArithmeticOrEnumeralCandidateType)
9374 return;
9375
9376 for (unsigned Left = FirstPromotedIntegralType;
9377 Left < LastPromotedIntegralType; ++Left) {
9378 for (unsigned Right = FirstPromotedIntegralType;
9379 Right < LastPromotedIntegralType; ++Right) {
9380 QualType LandR[2] = { ArithmeticTypes[Left],
9381 ArithmeticTypes[Right] };
9382 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9383 }
9384 }
9385 }
9386
9387 // C++ [over.built]p20:
9388 //
9389 // For every pair (T, VQ), where T is an enumeration or
9390 // pointer to member type and VQ is either volatile or
9391 // empty, there exist candidate operator functions of the form
9392 //
9393 // VQ T& operator=(VQ T&, T);
9394 void addAssignmentMemberPointerOrEnumeralOverloads() {
9395 /// Set of (canonical) types that we've already handled.
9396 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9397
9398 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9399 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9400 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
9401 continue;
9402
9403 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
9404 }
9405
9406 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9407 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9408 continue;
9409
9410 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
9411 }
9412 }
9413 }
9414
9415 // C++ [over.built]p19:
9416 //
9417 // For every pair (T, VQ), where T is any type and VQ is either
9418 // volatile or empty, there exist candidate operator functions
9419 // of the form
9420 //
9421 // T*VQ& operator=(T*VQ&, T*);
9422 //
9423 // C++ [over.built]p21:
9424 //
9425 // For every pair (T, VQ), where T is a cv-qualified or
9426 // cv-unqualified object type and VQ is either volatile or
9427 // empty, there exist candidate operator functions of the form
9428 //
9429 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9430 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9431 void addAssignmentPointerOverloads(bool isEqualOp) {
9432 /// Set of (canonical) types that we've already handled.
9433 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9434
9435 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9436 // If this is operator=, keep track of the builtin candidates we added.
9437 if (isEqualOp)
9438 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
9439 else if (!PtrTy->getPointeeType()->isObjectType())
9440 continue;
9441
9442 // non-volatile version
9443 QualType ParamTypes[2] = {
9444 S.Context.getLValueReferenceType(T: PtrTy),
9445 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9446 };
9447 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9448 /*IsAssignmentOperator=*/ isEqualOp);
9449
9450 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9451 VisibleTypeConversionsQuals.hasVolatile();
9452 if (NeedVolatile) {
9453 // volatile version
9454 ParamTypes[0] =
9455 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
9456 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9457 /*IsAssignmentOperator=*/isEqualOp);
9458 }
9459
9460 if (!PtrTy.isRestrictQualified() &&
9461 VisibleTypeConversionsQuals.hasRestrict()) {
9462 // restrict version
9463 ParamTypes[0] =
9464 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
9465 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9466 /*IsAssignmentOperator=*/isEqualOp);
9467
9468 if (NeedVolatile) {
9469 // volatile restrict version
9470 ParamTypes[0] =
9471 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
9472 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
9473 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9474 /*IsAssignmentOperator=*/isEqualOp);
9475 }
9476 }
9477 }
9478
9479 if (isEqualOp) {
9480 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9481 // Make sure we don't add the same candidate twice.
9482 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9483 continue;
9484
9485 QualType ParamTypes[2] = {
9486 S.Context.getLValueReferenceType(T: PtrTy),
9487 PtrTy,
9488 };
9489
9490 // non-volatile version
9491 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9492 /*IsAssignmentOperator=*/true);
9493
9494 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9495 VisibleTypeConversionsQuals.hasVolatile();
9496 if (NeedVolatile) {
9497 // volatile version
9498 ParamTypes[0] = S.Context.getLValueReferenceType(
9499 T: S.Context.getVolatileType(T: PtrTy));
9500 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9501 /*IsAssignmentOperator=*/true);
9502 }
9503
9504 if (!PtrTy.isRestrictQualified() &&
9505 VisibleTypeConversionsQuals.hasRestrict()) {
9506 // restrict version
9507 ParamTypes[0] = S.Context.getLValueReferenceType(
9508 T: S.Context.getRestrictType(T: PtrTy));
9509 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9510 /*IsAssignmentOperator=*/true);
9511
9512 if (NeedVolatile) {
9513 // volatile restrict version
9514 ParamTypes[0] =
9515 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
9516 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
9517 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9518 /*IsAssignmentOperator=*/true);
9519 }
9520 }
9521 }
9522 }
9523 }
9524
9525 // C++ [over.built]p18:
9526 //
9527 // For every triple (L, VQ, R), where L is an arithmetic type,
9528 // VQ is either volatile or empty, and R is a promoted
9529 // arithmetic type, there exist candidate operator functions of
9530 // the form
9531 //
9532 // VQ L& operator=(VQ L&, R);
9533 // VQ L& operator*=(VQ L&, R);
9534 // VQ L& operator/=(VQ L&, R);
9535 // VQ L& operator+=(VQ L&, R);
9536 // VQ L& operator-=(VQ L&, R);
9537 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9538 if (!HasArithmeticOrEnumeralCandidateType)
9539 return;
9540
9541 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9542 for (unsigned Right = FirstPromotedArithmeticType;
9543 Right < LastPromotedArithmeticType; ++Right) {
9544 QualType ParamTypes[2];
9545 ParamTypes[1] = ArithmeticTypes[Right];
9546 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9547 S, T: ArithmeticTypes[Left], Arg: Args[0]);
9548
9549 forAllQualifierCombinations(
9550 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
9551 ParamTypes[0] =
9552 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
9553 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9554 /*IsAssignmentOperator=*/isEqualOp);
9555 });
9556 }
9557 }
9558
9559 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9560 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9561 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9562 QualType ParamTypes[2];
9563 ParamTypes[1] = Vec2Ty;
9564 // Add this built-in operator as a candidate (VQ is empty).
9565 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
9566 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9567 /*IsAssignmentOperator=*/isEqualOp);
9568
9569 // Add this built-in operator as a candidate (VQ is 'volatile').
9570 if (VisibleTypeConversionsQuals.hasVolatile()) {
9571 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
9572 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
9573 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9574 /*IsAssignmentOperator=*/isEqualOp);
9575 }
9576 }
9577 }
9578
9579 // C++ [over.built]p22:
9580 //
9581 // For every triple (L, VQ, R), where L is an integral type, VQ
9582 // is either volatile or empty, and R is a promoted integral
9583 // type, there exist candidate operator functions of the form
9584 //
9585 // VQ L& operator%=(VQ L&, R);
9586 // VQ L& operator<<=(VQ L&, R);
9587 // VQ L& operator>>=(VQ L&, R);
9588 // VQ L& operator&=(VQ L&, R);
9589 // VQ L& operator^=(VQ L&, R);
9590 // VQ L& operator|=(VQ L&, R);
9591 void addAssignmentIntegralOverloads() {
9592 if (!HasArithmeticOrEnumeralCandidateType)
9593 return;
9594
9595 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9596 for (unsigned Right = FirstPromotedIntegralType;
9597 Right < LastPromotedIntegralType; ++Right) {
9598 QualType ParamTypes[2];
9599 ParamTypes[1] = ArithmeticTypes[Right];
9600 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9601 S, T: ArithmeticTypes[Left], Arg: Args[0]);
9602
9603 forAllQualifierCombinations(
9604 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
9605 ParamTypes[0] =
9606 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
9607 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9608 });
9609 }
9610 }
9611 }
9612
9613 // C++ [over.operator]p23:
9614 //
9615 // There also exist candidate operator functions of the form
9616 //
9617 // bool operator!(bool);
9618 // bool operator&&(bool, bool);
9619 // bool operator||(bool, bool);
9620 void addExclaimOverload() {
9621 QualType ParamTy = S.Context.BoolTy;
9622 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
9623 /*IsAssignmentOperator=*/false,
9624 /*NumContextualBoolArguments=*/1);
9625 }
9626 void addAmpAmpOrPipePipeOverload() {
9627 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9628 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9629 /*IsAssignmentOperator=*/false,
9630 /*NumContextualBoolArguments=*/2);
9631 }
9632
9633 // C++ [over.built]p13:
9634 //
9635 // For every cv-qualified or cv-unqualified object type T there
9636 // exist candidate operator functions of the form
9637 //
9638 // T* operator+(T*, ptrdiff_t); [ABOVE]
9639 // T& operator[](T*, ptrdiff_t);
9640 // T* operator-(T*, ptrdiff_t); [ABOVE]
9641 // T* operator+(ptrdiff_t, T*); [ABOVE]
9642 // T& operator[](ptrdiff_t, T*);
9643 void addSubscriptOverloads() {
9644 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9645 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9646 QualType PointeeType = PtrTy->getPointeeType();
9647 if (!PointeeType->isObjectType())
9648 continue;
9649
9650 // T& operator[](T*, ptrdiff_t)
9651 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9652 }
9653
9654 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9655 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9656 QualType PointeeType = PtrTy->getPointeeType();
9657 if (!PointeeType->isObjectType())
9658 continue;
9659
9660 // T& operator[](ptrdiff_t, T*)
9661 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9662 }
9663 }
9664
9665 // C++ [over.built]p11:
9666 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9667 // C1 is the same type as C2 or is a derived class of C2, T is an object
9668 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9669 // there exist candidate operator functions of the form
9670 //
9671 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9672 //
9673 // where CV12 is the union of CV1 and CV2.
9674 void addArrowStarOverloads() {
9675 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9676 QualType C1Ty = PtrTy;
9677 QualType C1;
9678 QualifierCollector Q1;
9679 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
9680 if (!isa<RecordType>(Val: C1))
9681 continue;
9682 // heuristic to reduce number of builtin candidates in the set.
9683 // Add volatile/restrict version only if there are conversions to a
9684 // volatile/restrict type.
9685 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9686 continue;
9687 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9688 continue;
9689 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9690 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
9691 QualType C2 = QualType(mptr->getClass(), 0);
9692 C2 = C2.getUnqualifiedType();
9693 if (C1 != C2 && !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: C1, Base: C2))
9694 break;
9695 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9696 // build CV12 T&
9697 QualType T = mptr->getPointeeType();
9698 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9699 T.isVolatileQualified())
9700 continue;
9701 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9702 T.isRestrictQualified())
9703 continue;
9704 T = Q1.apply(Context: S.Context, QT: T);
9705 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9706 }
9707 }
9708 }
9709
9710 // Note that we don't consider the first argument, since it has been
9711 // contextually converted to bool long ago. The candidates below are
9712 // therefore added as binary.
9713 //
9714 // C++ [over.built]p25:
9715 // For every type T, where T is a pointer, pointer-to-member, or scoped
9716 // enumeration type, there exist candidate operator functions of the form
9717 //
9718 // T operator?(bool, T, T);
9719 //
9720 void addConditionalOperatorOverloads() {
9721 /// Set of (canonical) types that we've already handled.
9722 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9723
9724 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9725 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9726 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9727 continue;
9728
9729 QualType ParamTypes[2] = {PtrTy, PtrTy};
9730 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9731 }
9732
9733 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9734 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9735 continue;
9736
9737 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9738 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9739 }
9740
9741 if (S.getLangOpts().CPlusPlus11) {
9742 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9743 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9744 continue;
9745
9746 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
9747 continue;
9748
9749 QualType ParamTypes[2] = {EnumTy, EnumTy};
9750 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9751 }
9752 }
9753 }
9754 }
9755};
9756
9757} // end anonymous namespace
9758
9759void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9760 SourceLocation OpLoc,
9761 ArrayRef<Expr *> Args,
9762 OverloadCandidateSet &CandidateSet) {
9763 // Find all of the types that the arguments can convert to, but only
9764 // if the operator we're looking at has built-in operator candidates
9765 // that make use of these types. Also record whether we encounter non-record
9766 // candidate types or either arithmetic or enumeral candidate types.
9767 QualifiersAndAtomic VisibleTypeConversionsQuals;
9768 VisibleTypeConversionsQuals.addConst();
9769 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9770 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
9771 if (Args[ArgIdx]->getType()->isAtomicType())
9772 VisibleTypeConversionsQuals.addAtomic();
9773 }
9774
9775 bool HasNonRecordCandidateType = false;
9776 bool HasArithmeticOrEnumeralCandidateType = false;
9777 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9778 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9779 CandidateTypes.emplace_back(Args&: *this);
9780 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
9781 Loc: OpLoc,
9782 AllowUserConversions: true,
9783 AllowExplicitConversions: (Op == OO_Exclaim ||
9784 Op == OO_AmpAmp ||
9785 Op == OO_PipePipe),
9786 VisibleQuals: VisibleTypeConversionsQuals);
9787 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9788 CandidateTypes[ArgIdx].hasNonRecordTypes();
9789 HasArithmeticOrEnumeralCandidateType =
9790 HasArithmeticOrEnumeralCandidateType ||
9791 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9792 }
9793
9794 // Exit early when no non-record types have been added to the candidate set
9795 // for any of the arguments to the operator.
9796 //
9797 // We can't exit early for !, ||, or &&, since there we have always have
9798 // 'bool' overloads.
9799 if (!HasNonRecordCandidateType &&
9800 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9801 return;
9802
9803 // Setup an object to manage the common state for building overloads.
9804 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9805 VisibleTypeConversionsQuals,
9806 HasArithmeticOrEnumeralCandidateType,
9807 CandidateTypes, CandidateSet);
9808
9809 // Dispatch over the operation to add in only those overloads which apply.
9810 switch (Op) {
9811 case OO_None:
9812 case NUM_OVERLOADED_OPERATORS:
9813 llvm_unreachable("Expected an overloaded operator");
9814
9815 case OO_New:
9816 case OO_Delete:
9817 case OO_Array_New:
9818 case OO_Array_Delete:
9819 case OO_Call:
9820 llvm_unreachable(
9821 "Special operators don't use AddBuiltinOperatorCandidates");
9822
9823 case OO_Comma:
9824 case OO_Arrow:
9825 case OO_Coawait:
9826 // C++ [over.match.oper]p3:
9827 // -- For the operator ',', the unary operator '&', the
9828 // operator '->', or the operator 'co_await', the
9829 // built-in candidates set is empty.
9830 break;
9831
9832 case OO_Plus: // '+' is either unary or binary
9833 if (Args.size() == 1)
9834 OpBuilder.addUnaryPlusPointerOverloads();
9835 [[fallthrough]];
9836
9837 case OO_Minus: // '-' is either unary or binary
9838 if (Args.size() == 1) {
9839 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9840 } else {
9841 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9842 OpBuilder.addGenericBinaryArithmeticOverloads();
9843 OpBuilder.addMatrixBinaryArithmeticOverloads();
9844 }
9845 break;
9846
9847 case OO_Star: // '*' is either unary or binary
9848 if (Args.size() == 1)
9849 OpBuilder.addUnaryStarPointerOverloads();
9850 else {
9851 OpBuilder.addGenericBinaryArithmeticOverloads();
9852 OpBuilder.addMatrixBinaryArithmeticOverloads();
9853 }
9854 break;
9855
9856 case OO_Slash:
9857 OpBuilder.addGenericBinaryArithmeticOverloads();
9858 break;
9859
9860 case OO_PlusPlus:
9861 case OO_MinusMinus:
9862 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9863 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9864 break;
9865
9866 case OO_EqualEqual:
9867 case OO_ExclaimEqual:
9868 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9869 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9870 OpBuilder.addGenericBinaryArithmeticOverloads();
9871 break;
9872
9873 case OO_Less:
9874 case OO_Greater:
9875 case OO_LessEqual:
9876 case OO_GreaterEqual:
9877 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9878 OpBuilder.addGenericBinaryArithmeticOverloads();
9879 break;
9880
9881 case OO_Spaceship:
9882 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9883 OpBuilder.addThreeWayArithmeticOverloads();
9884 break;
9885
9886 case OO_Percent:
9887 case OO_Caret:
9888 case OO_Pipe:
9889 case OO_LessLess:
9890 case OO_GreaterGreater:
9891 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9892 break;
9893
9894 case OO_Amp: // '&' is either unary or binary
9895 if (Args.size() == 1)
9896 // C++ [over.match.oper]p3:
9897 // -- For the operator ',', the unary operator '&', or the
9898 // operator '->', the built-in candidates set is empty.
9899 break;
9900
9901 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9902 break;
9903
9904 case OO_Tilde:
9905 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9906 break;
9907
9908 case OO_Equal:
9909 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9910 [[fallthrough]];
9911
9912 case OO_PlusEqual:
9913 case OO_MinusEqual:
9914 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
9915 [[fallthrough]];
9916
9917 case OO_StarEqual:
9918 case OO_SlashEqual:
9919 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
9920 break;
9921
9922 case OO_PercentEqual:
9923 case OO_LessLessEqual:
9924 case OO_GreaterGreaterEqual:
9925 case OO_AmpEqual:
9926 case OO_CaretEqual:
9927 case OO_PipeEqual:
9928 OpBuilder.addAssignmentIntegralOverloads();
9929 break;
9930
9931 case OO_Exclaim:
9932 OpBuilder.addExclaimOverload();
9933 break;
9934
9935 case OO_AmpAmp:
9936 case OO_PipePipe:
9937 OpBuilder.addAmpAmpOrPipePipeOverload();
9938 break;
9939
9940 case OO_Subscript:
9941 if (Args.size() == 2)
9942 OpBuilder.addSubscriptOverloads();
9943 break;
9944
9945 case OO_ArrowStar:
9946 OpBuilder.addArrowStarOverloads();
9947 break;
9948
9949 case OO_Conditional:
9950 OpBuilder.addConditionalOperatorOverloads();
9951 OpBuilder.addGenericBinaryArithmeticOverloads();
9952 break;
9953 }
9954}
9955
9956void
9957Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9958 SourceLocation Loc,
9959 ArrayRef<Expr *> Args,
9960 TemplateArgumentListInfo *ExplicitTemplateArgs,
9961 OverloadCandidateSet& CandidateSet,
9962 bool PartialOverloading) {
9963 ADLResult Fns;
9964
9965 // FIXME: This approach for uniquing ADL results (and removing
9966 // redundant candidates from the set) relies on pointer-equality,
9967 // which means we need to key off the canonical decl. However,
9968 // always going back to the canonical decl might not get us the
9969 // right set of default arguments. What default arguments are
9970 // we supposed to consider on ADL candidates, anyway?
9971
9972 // FIXME: Pass in the explicit template arguments?
9973 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
9974
9975 // Erase all of the candidates we already knew about.
9976 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9977 CandEnd = CandidateSet.end();
9978 Cand != CandEnd; ++Cand)
9979 if (Cand->Function) {
9980 Fns.erase(D: Cand->Function);
9981 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9982 Fns.erase(D: FunTmpl);
9983 }
9984
9985 // For each of the ADL candidates we found, add it to the overload
9986 // set.
9987 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9988 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
9989
9990 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
9991 if (ExplicitTemplateArgs)
9992 continue;
9993
9994 AddOverloadCandidate(
9995 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9996 PartialOverloading, /*AllowExplicit=*/true,
9997 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
9998 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
9999 AddOverloadCandidate(
10000 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10001 /*SuppressUserConversions=*/false, PartialOverloading,
10002 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10003 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: std::nullopt,
10004 PO: OverloadCandidateParamOrder::Reversed);
10005 }
10006 } else {
10007 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10008 AddTemplateOverloadCandidate(
10009 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10010 /*SuppressUserConversions=*/false, PartialOverloading,
10011 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10012 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10013 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10014 AddTemplateOverloadCandidate(
10015 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: {Args[1], Args[0]},
10016 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10017 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10018 PO: OverloadCandidateParamOrder::Reversed);
10019 }
10020 }
10021 }
10022}
10023
10024namespace {
10025enum class Comparison { Equal, Better, Worse };
10026}
10027
10028/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10029/// overload resolution.
10030///
10031/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10032/// Cand1's first N enable_if attributes have precisely the same conditions as
10033/// Cand2's first N enable_if attributes (where N = the number of enable_if
10034/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10035///
10036/// Note that you can have a pair of candidates such that Cand1's enable_if
10037/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10038/// worse than Cand1's.
10039static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10040 const FunctionDecl *Cand2) {
10041 // Common case: One (or both) decls don't have enable_if attrs.
10042 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10043 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10044 if (!Cand1Attr || !Cand2Attr) {
10045 if (Cand1Attr == Cand2Attr)
10046 return Comparison::Equal;
10047 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10048 }
10049
10050 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10051 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10052
10053 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10054 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10055 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10056 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10057
10058 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10059 // has fewer enable_if attributes than Cand2, and vice versa.
10060 if (!Cand1A)
10061 return Comparison::Worse;
10062 if (!Cand2A)
10063 return Comparison::Better;
10064
10065 Cand1ID.clear();
10066 Cand2ID.clear();
10067
10068 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10069 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10070 if (Cand1ID != Cand2ID)
10071 return Comparison::Worse;
10072 }
10073
10074 return Comparison::Equal;
10075}
10076
10077static Comparison
10078isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10079 const OverloadCandidate &Cand2) {
10080 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10081 !Cand2.Function->isMultiVersion())
10082 return Comparison::Equal;
10083
10084 // If both are invalid, they are equal. If one of them is invalid, the other
10085 // is better.
10086 if (Cand1.Function->isInvalidDecl()) {
10087 if (Cand2.Function->isInvalidDecl())
10088 return Comparison::Equal;
10089 return Comparison::Worse;
10090 }
10091 if (Cand2.Function->isInvalidDecl())
10092 return Comparison::Better;
10093
10094 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10095 // cpu_dispatch, else arbitrarily based on the identifiers.
10096 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10097 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10098 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10099 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10100
10101 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10102 return Comparison::Equal;
10103
10104 if (Cand1CPUDisp && !Cand2CPUDisp)
10105 return Comparison::Better;
10106 if (Cand2CPUDisp && !Cand1CPUDisp)
10107 return Comparison::Worse;
10108
10109 if (Cand1CPUSpec && Cand2CPUSpec) {
10110 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10111 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10112 ? Comparison::Better
10113 : Comparison::Worse;
10114
10115 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10116 FirstDiff = std::mismatch(
10117 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10118 Cand2CPUSpec->cpus_begin(),
10119 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10120 return LHS->getName() == RHS->getName();
10121 });
10122
10123 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10124 "Two different cpu-specific versions should not have the same "
10125 "identifier list, otherwise they'd be the same decl!");
10126 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10127 ? Comparison::Better
10128 : Comparison::Worse;
10129 }
10130 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10131}
10132
10133/// Compute the type of the implicit object parameter for the given function,
10134/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10135/// null QualType if there is a 'matches anything' implicit object parameter.
10136static std::optional<QualType>
10137getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10138 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10139 return std::nullopt;
10140
10141 auto *M = cast<CXXMethodDecl>(Val: F);
10142 // Static member functions' object parameters match all types.
10143 if (M->isStatic())
10144 return QualType();
10145 return M->getFunctionObjectParameterReferenceType();
10146}
10147
10148// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10149// represent the same entity.
10150static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10151 const FunctionDecl *F2) {
10152 if (declaresSameEntity(D1: F1, D2: F2))
10153 return true;
10154 auto PT1 = F1->getPrimaryTemplate();
10155 auto PT2 = F2->getPrimaryTemplate();
10156 if (PT1 && PT2) {
10157 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10158 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10159 D2: PT2->getInstantiatedFromMemberTemplate()))
10160 return true;
10161 }
10162 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10163 // different functions with same params). Consider removing this (as no test
10164 // fail w/o it).
10165 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10166 if (First) {
10167 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10168 return *T;
10169 }
10170 assert(I < F->getNumParams());
10171 return F->getParamDecl(i: I++)->getType();
10172 };
10173
10174 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10175 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10176
10177 if (F1NumParams != F2NumParams)
10178 return false;
10179
10180 unsigned I1 = 0, I2 = 0;
10181 for (unsigned I = 0; I != F1NumParams; ++I) {
10182 QualType T1 = NextParam(F1, I1, I == 0);
10183 QualType T2 = NextParam(F2, I2, I == 0);
10184 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10185 if (!Context.hasSameUnqualifiedType(T1, T2))
10186 return false;
10187 }
10188 return true;
10189}
10190
10191/// We're allowed to use constraints partial ordering only if the candidates
10192/// have the same parameter types:
10193/// [over.match.best.general]p2.6
10194/// F1 and F2 are non-template functions with the same
10195/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10196static bool sameFunctionParameterTypeLists(Sema &S,
10197 const OverloadCandidate &Cand1,
10198 const OverloadCandidate &Cand2) {
10199 if (!Cand1.Function || !Cand2.Function)
10200 return false;
10201
10202 FunctionDecl *Fn1 = Cand1.Function;
10203 FunctionDecl *Fn2 = Cand2.Function;
10204
10205 if (Fn1->isVariadic() != Fn2->isVariadic())
10206 return false;
10207
10208 if (!S.FunctionNonObjectParamTypesAreEqual(
10209 OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr, Reversed: Cand1.isReversed() ^ Cand2.isReversed()))
10210 return false;
10211
10212 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10213 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10214 if (Mem1 && Mem2) {
10215 // if they are member functions, both are direct members of the same class,
10216 // and
10217 if (Mem1->getParent() != Mem2->getParent())
10218 return false;
10219 // if both are non-static member functions, they have the same types for
10220 // their object parameters
10221 if (Mem1->isInstance() && Mem2->isInstance() &&
10222 !S.getASTContext().hasSameType(
10223 T1: Mem1->getFunctionObjectParameterReferenceType(),
10224 T2: Mem1->getFunctionObjectParameterReferenceType()))
10225 return false;
10226 }
10227 return true;
10228}
10229
10230/// isBetterOverloadCandidate - Determines whether the first overload
10231/// candidate is a better candidate than the second (C++ 13.3.3p1).
10232bool clang::isBetterOverloadCandidate(
10233 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10234 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
10235 // Define viable functions to be better candidates than non-viable
10236 // functions.
10237 if (!Cand2.Viable)
10238 return Cand1.Viable;
10239 else if (!Cand1.Viable)
10240 return false;
10241
10242 // [CUDA] A function with 'never' preference is marked not viable, therefore
10243 // is never shown up here. The worst preference shown up here is 'wrong side',
10244 // e.g. an H function called by a HD function in device compilation. This is
10245 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10246 // function which is called only by an H function. A deferred diagnostic will
10247 // be triggered if it is emitted. However a wrong-sided function is still
10248 // a viable candidate here.
10249 //
10250 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10251 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10252 // can be emitted, Cand1 is not better than Cand2. This rule should have
10253 // precedence over other rules.
10254 //
10255 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10256 // other rules should be used to determine which is better. This is because
10257 // host/device based overloading resolution is mostly for determining
10258 // viability of a function. If two functions are both viable, other factors
10259 // should take precedence in preference, e.g. the standard-defined preferences
10260 // like argument conversion ranks or enable_if partial-ordering. The
10261 // preference for pass-object-size parameters is probably most similar to a
10262 // type-based-overloading decision and so should take priority.
10263 //
10264 // If other rules cannot determine which is better, CUDA preference will be
10265 // used again to determine which is better.
10266 //
10267 // TODO: Currently IdentifyPreference does not return correct values
10268 // for functions called in global variable initializers due to missing
10269 // correct context about device/host. Therefore we can only enforce this
10270 // rule when there is a caller. We should enforce this rule for functions
10271 // in global variable initializers once proper context is added.
10272 //
10273 // TODO: We can only enable the hostness based overloading resolution when
10274 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10275 // overloading resolution diagnostics.
10276 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10277 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10278 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10279 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
10280 bool IsCand1ImplicitHD =
10281 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
10282 bool IsCand2ImplicitHD =
10283 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
10284 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
10285 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10286 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10287 // The implicit HD function may be a function in a system header which
10288 // is forced by pragma. In device compilation, if we prefer HD candidates
10289 // over wrong-sided candidates, overloading resolution may change, which
10290 // may result in non-deferrable diagnostics. As a workaround, we let
10291 // implicit HD candidates take equal preference as wrong-sided candidates.
10292 // This will preserve the overloading resolution.
10293 // TODO: We still need special handling of implicit HD functions since
10294 // they may incur other diagnostics to be deferred. We should make all
10295 // host/device related diagnostics deferrable and remove special handling
10296 // of implicit HD functions.
10297 auto EmitThreshold =
10298 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10299 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10300 ? SemaCUDA::CFP_Never
10301 : SemaCUDA::CFP_WrongSide;
10302 auto Cand1Emittable = P1 > EmitThreshold;
10303 auto Cand2Emittable = P2 > EmitThreshold;
10304 if (Cand1Emittable && !Cand2Emittable)
10305 return true;
10306 if (!Cand1Emittable && Cand2Emittable)
10307 return false;
10308 }
10309 }
10310
10311 // C++ [over.match.best]p1: (Changed in C++23)
10312 //
10313 // -- if F is a static member function, ICS1(F) is defined such
10314 // that ICS1(F) is neither better nor worse than ICS1(G) for
10315 // any function G, and, symmetrically, ICS1(G) is neither
10316 // better nor worse than ICS1(F).
10317 unsigned StartArg = 0;
10318 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10319 StartArg = 1;
10320
10321 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10322 // We don't allow incompatible pointer conversions in C++.
10323 if (!S.getLangOpts().CPlusPlus)
10324 return ICS.isStandard() &&
10325 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10326
10327 // The only ill-formed conversion we allow in C++ is the string literal to
10328 // char* conversion, which is only considered ill-formed after C++11.
10329 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10330 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10331 };
10332
10333 // Define functions that don't require ill-formed conversions for a given
10334 // argument to be better candidates than functions that do.
10335 unsigned NumArgs = Cand1.Conversions.size();
10336 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10337 bool HasBetterConversion = false;
10338 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10339 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10340 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10341 if (Cand1Bad != Cand2Bad) {
10342 if (Cand1Bad)
10343 return false;
10344 HasBetterConversion = true;
10345 }
10346 }
10347
10348 if (HasBetterConversion)
10349 return true;
10350
10351 // C++ [over.match.best]p1:
10352 // A viable function F1 is defined to be a better function than another
10353 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10354 // conversion sequence than ICSi(F2), and then...
10355 bool HasWorseConversion = false;
10356 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10357 switch (CompareImplicitConversionSequences(S, Loc,
10358 ICS1: Cand1.Conversions[ArgIdx],
10359 ICS2: Cand2.Conversions[ArgIdx])) {
10360 case ImplicitConversionSequence::Better:
10361 // Cand1 has a better conversion sequence.
10362 HasBetterConversion = true;
10363 break;
10364
10365 case ImplicitConversionSequence::Worse:
10366 if (Cand1.Function && Cand2.Function &&
10367 Cand1.isReversed() != Cand2.isReversed() &&
10368 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
10369 // Work around large-scale breakage caused by considering reversed
10370 // forms of operator== in C++20:
10371 //
10372 // When comparing a function against a reversed function, if we have a
10373 // better conversion for one argument and a worse conversion for the
10374 // other, the implicit conversion sequences are treated as being equally
10375 // good.
10376 //
10377 // This prevents a comparison function from being considered ambiguous
10378 // with a reversed form that is written in the same way.
10379 //
10380 // We diagnose this as an extension from CreateOverloadedBinOp.
10381 HasWorseConversion = true;
10382 break;
10383 }
10384
10385 // Cand1 can't be better than Cand2.
10386 return false;
10387
10388 case ImplicitConversionSequence::Indistinguishable:
10389 // Do nothing.
10390 break;
10391 }
10392 }
10393
10394 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10395 // ICSj(F2), or, if not that,
10396 if (HasBetterConversion && !HasWorseConversion)
10397 return true;
10398
10399 // -- the context is an initialization by user-defined conversion
10400 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10401 // from the return type of F1 to the destination type (i.e.,
10402 // the type of the entity being initialized) is a better
10403 // conversion sequence than the standard conversion sequence
10404 // from the return type of F2 to the destination type.
10405 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10406 Cand1.Function && Cand2.Function &&
10407 isa<CXXConversionDecl>(Val: Cand1.Function) &&
10408 isa<CXXConversionDecl>(Val: Cand2.Function)) {
10409 // First check whether we prefer one of the conversion functions over the
10410 // other. This only distinguishes the results in non-standard, extension
10411 // cases such as the conversion from a lambda closure type to a function
10412 // pointer or block.
10413 ImplicitConversionSequence::CompareKind Result =
10414 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
10415 if (Result == ImplicitConversionSequence::Indistinguishable)
10416 Result = CompareStandardConversionSequences(S, Loc,
10417 SCS1: Cand1.FinalConversion,
10418 SCS2: Cand2.FinalConversion);
10419
10420 if (Result != ImplicitConversionSequence::Indistinguishable)
10421 return Result == ImplicitConversionSequence::Better;
10422
10423 // FIXME: Compare kind of reference binding if conversion functions
10424 // convert to a reference type used in direct reference binding, per
10425 // C++14 [over.match.best]p1 section 2 bullet 3.
10426 }
10427
10428 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10429 // as combined with the resolution to CWG issue 243.
10430 //
10431 // When the context is initialization by constructor ([over.match.ctor] or
10432 // either phase of [over.match.list]), a constructor is preferred over
10433 // a conversion function.
10434 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10435 Cand1.Function && Cand2.Function &&
10436 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
10437 isa<CXXConstructorDecl>(Val: Cand2.Function))
10438 return isa<CXXConstructorDecl>(Val: Cand1.Function);
10439
10440 // -- F1 is a non-template function and F2 is a function template
10441 // specialization, or, if not that,
10442 bool Cand1IsSpecialization = Cand1.Function &&
10443 Cand1.Function->getPrimaryTemplate();
10444 bool Cand2IsSpecialization = Cand2.Function &&
10445 Cand2.Function->getPrimaryTemplate();
10446 if (Cand1IsSpecialization != Cand2IsSpecialization)
10447 return Cand2IsSpecialization;
10448
10449 // -- F1 and F2 are function template specializations, and the function
10450 // template for F1 is more specialized than the template for F2
10451 // according to the partial ordering rules described in 14.5.5.2, or,
10452 // if not that,
10453 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10454 const auto *Obj1Context =
10455 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
10456 const auto *Obj2Context =
10457 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
10458 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10459 FT1: Cand1.Function->getPrimaryTemplate(),
10460 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
10461 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
10462 : TPOC_Call,
10463 NumCallArguments1: Cand1.ExplicitCallArguments,
10464 RawObj1Ty: Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10465 : QualType{},
10466 RawObj2Ty: Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10467 : QualType{},
10468 Reversed: Cand1.isReversed() ^ Cand2.isReversed())) {
10469 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10470 }
10471 }
10472
10473 // -— F1 and F2 are non-template functions with the same
10474 // parameter-type-lists, and F1 is more constrained than F2 [...],
10475 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10476 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10477 S.getMoreConstrainedFunction(FD1: Cand1.Function, FD2: Cand2.Function) ==
10478 Cand1.Function)
10479 return true;
10480
10481 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10482 // class B of D, and for all arguments the corresponding parameters of
10483 // F1 and F2 have the same type.
10484 // FIXME: Implement the "all parameters have the same type" check.
10485 bool Cand1IsInherited =
10486 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
10487 bool Cand2IsInherited =
10488 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
10489 if (Cand1IsInherited != Cand2IsInherited)
10490 return Cand2IsInherited;
10491 else if (Cand1IsInherited) {
10492 assert(Cand2IsInherited);
10493 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
10494 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
10495 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
10496 return true;
10497 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
10498 return false;
10499 // Inherited from sibling base classes: still ambiguous.
10500 }
10501
10502 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10503 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10504 // with reversed order of parameters and F1 is not
10505 //
10506 // We rank reversed + different operator as worse than just reversed, but
10507 // that comparison can never happen, because we only consider reversing for
10508 // the maximally-rewritten operator (== or <=>).
10509 if (Cand1.RewriteKind != Cand2.RewriteKind)
10510 return Cand1.RewriteKind < Cand2.RewriteKind;
10511
10512 // Check C++17 tie-breakers for deduction guides.
10513 {
10514 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
10515 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
10516 if (Guide1 && Guide2) {
10517 // -- F1 is generated from a deduction-guide and F2 is not
10518 if (Guide1->isImplicit() != Guide2->isImplicit())
10519 return Guide2->isImplicit();
10520
10521 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10522 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10523 return true;
10524 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10525 return false;
10526
10527 // --F1 is generated from a non-template constructor and F2 is generated
10528 // from a constructor template
10529 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10530 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10531 if (Constructor1 && Constructor2) {
10532 bool isC1Templated = Constructor1->getTemplatedKind() !=
10533 FunctionDecl::TemplatedKind::TK_NonTemplate;
10534 bool isC2Templated = Constructor2->getTemplatedKind() !=
10535 FunctionDecl::TemplatedKind::TK_NonTemplate;
10536 if (isC1Templated != isC2Templated)
10537 return isC2Templated;
10538 }
10539 }
10540 }
10541
10542 // Check for enable_if value-based overload resolution.
10543 if (Cand1.Function && Cand2.Function) {
10544 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
10545 if (Cmp != Comparison::Equal)
10546 return Cmp == Comparison::Better;
10547 }
10548
10549 bool HasPS1 = Cand1.Function != nullptr &&
10550 functionHasPassObjectSizeParams(FD: Cand1.Function);
10551 bool HasPS2 = Cand2.Function != nullptr &&
10552 functionHasPassObjectSizeParams(FD: Cand2.Function);
10553 if (HasPS1 != HasPS2 && HasPS1)
10554 return true;
10555
10556 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10557 if (MV == Comparison::Better)
10558 return true;
10559 if (MV == Comparison::Worse)
10560 return false;
10561
10562 // If other rules cannot determine which is better, CUDA preference is used
10563 // to determine which is better.
10564 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10565 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10566 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
10567 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10568 }
10569
10570 // General member function overloading is handled above, so this only handles
10571 // constructors with address spaces.
10572 // This only handles address spaces since C++ has no other
10573 // qualifier that can be used with constructors.
10574 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
10575 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
10576 if (CD1 && CD2) {
10577 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10578 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10579 if (AS1 != AS2) {
10580 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1))
10581 return true;
10582 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2))
10583 return false;
10584 }
10585 }
10586
10587 return false;
10588}
10589
10590/// Determine whether two declarations are "equivalent" for the purposes of
10591/// name lookup and overload resolution. This applies when the same internal/no
10592/// linkage entity is defined by two modules (probably by textually including
10593/// the same header). In such a case, we don't consider the declarations to
10594/// declare the same entity, but we also don't want lookups with both
10595/// declarations visible to be ambiguous in some cases (this happens when using
10596/// a modularized libstdc++).
10597bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10598 const NamedDecl *B) {
10599 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
10600 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
10601 if (!VA || !VB)
10602 return false;
10603
10604 // The declarations must be declaring the same name as an internal linkage
10605 // entity in different modules.
10606 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10607 DC: VB->getDeclContext()->getRedeclContext()) ||
10608 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
10609 VA->isExternallyVisible() || VB->isExternallyVisible())
10610 return false;
10611
10612 // Check that the declarations appear to be equivalent.
10613 //
10614 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10615 // For constants and functions, we should check the initializer or body is
10616 // the same. For non-constant variables, we shouldn't allow it at all.
10617 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
10618 return true;
10619
10620 // Enum constants within unnamed enumerations will have different types, but
10621 // may still be similar enough to be interchangeable for our purposes.
10622 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
10623 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
10624 // Only handle anonymous enums. If the enumerations were named and
10625 // equivalent, they would have been merged to the same type.
10626 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
10627 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
10628 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10629 !Context.hasSameType(T1: EnumA->getIntegerType(),
10630 T2: EnumB->getIntegerType()))
10631 return false;
10632 // Allow this only if the value is the same for both enumerators.
10633 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
10634 }
10635 }
10636
10637 // Nothing else is sufficiently similar.
10638 return false;
10639}
10640
10641void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10642 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10643 assert(D && "Unknown declaration");
10644 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10645
10646 Module *M = getOwningModule(Entity: D);
10647 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
10648 << !M << (M ? M->getFullModuleName() : "");
10649
10650 for (auto *E : Equiv) {
10651 Module *M = getOwningModule(Entity: E);
10652 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
10653 << !M << (M ? M->getFullModuleName() : "");
10654 }
10655}
10656
10657bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10658 return FailureKind == ovl_fail_bad_deduction &&
10659 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10660 TemplateDeductionResult::ConstraintsNotSatisfied &&
10661 static_cast<CNSInfo *>(DeductionFailure.Data)
10662 ->Satisfaction.ContainsErrors;
10663}
10664
10665/// Computes the best viable function (C++ 13.3.3)
10666/// within an overload candidate set.
10667///
10668/// \param Loc The location of the function name (or operator symbol) for
10669/// which overload resolution occurs.
10670///
10671/// \param Best If overload resolution was successful or found a deleted
10672/// function, \p Best points to the candidate function found.
10673///
10674/// \returns The result of overload resolution.
10675OverloadingResult
10676OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10677 iterator &Best) {
10678 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10679 std::transform(first: begin(), last: end(), result: std::back_inserter(x&: Candidates),
10680 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
10681
10682 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10683 // are accepted by both clang and NVCC. However, during a particular
10684 // compilation mode only one call variant is viable. We need to
10685 // exclude non-viable overload candidates from consideration based
10686 // only on their host/device attributes. Specifically, if one
10687 // candidate call is WrongSide and the other is SameSide, we ignore
10688 // the WrongSide candidate.
10689 // We only need to remove wrong-sided candidates here if
10690 // -fgpu-exclude-wrong-side-overloads is off. When
10691 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10692 // uniformly in isBetterOverloadCandidate.
10693 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10694 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10695 bool ContainsSameSideCandidate =
10696 llvm::any_of(Range&: Candidates, P: [&](OverloadCandidate *Cand) {
10697 // Check viable function only.
10698 return Cand->Viable && Cand->Function &&
10699 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
10700 SemaCUDA::CFP_SameSide;
10701 });
10702 if (ContainsSameSideCandidate) {
10703 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10704 // Check viable function only to avoid unnecessary data copying/moving.
10705 return Cand->Viable && Cand->Function &&
10706 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
10707 SemaCUDA::CFP_WrongSide;
10708 };
10709 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
10710 }
10711 }
10712
10713 // Find the best viable function.
10714 Best = end();
10715 for (auto *Cand : Candidates) {
10716 Cand->Best = false;
10717 if (Cand->Viable) {
10718 if (Best == end() ||
10719 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
10720 Best = Cand;
10721 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10722 // This candidate has constraint that we were unable to evaluate because
10723 // it referenced an expression that contained an error. Rather than fall
10724 // back onto a potentially unintended candidate (made worse by
10725 // subsuming constraints), treat this as 'no viable candidate'.
10726 Best = end();
10727 return OR_No_Viable_Function;
10728 }
10729 }
10730
10731 // If we didn't find any viable functions, abort.
10732 if (Best == end())
10733 return OR_No_Viable_Function;
10734
10735 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10736
10737 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10738 PendingBest.push_back(Elt: &*Best);
10739 Best->Best = true;
10740
10741 // Make sure that this function is better than every other viable
10742 // function. If not, we have an ambiguity.
10743 while (!PendingBest.empty()) {
10744 auto *Curr = PendingBest.pop_back_val();
10745 for (auto *Cand : Candidates) {
10746 if (Cand->Viable && !Cand->Best &&
10747 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
10748 PendingBest.push_back(Elt: Cand);
10749 Cand->Best = true;
10750
10751 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
10752 B: Curr->Function))
10753 EquivalentCands.push_back(Elt: Cand->Function);
10754 else
10755 Best = end();
10756 }
10757 }
10758 }
10759
10760 // If we found more than one best candidate, this is ambiguous.
10761 if (Best == end())
10762 return OR_Ambiguous;
10763
10764 // Best is the best viable function.
10765 if (Best->Function && Best->Function->isDeleted())
10766 return OR_Deleted;
10767
10768 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
10769 Kind == CSK_AddressOfOverloadSet && M &&
10770 M->isImplicitObjectMemberFunction()) {
10771 return OR_No_Viable_Function;
10772 }
10773
10774 if (!EquivalentCands.empty())
10775 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
10776 Equiv: EquivalentCands);
10777
10778 return OR_Success;
10779}
10780
10781namespace {
10782
10783enum OverloadCandidateKind {
10784 oc_function,
10785 oc_method,
10786 oc_reversed_binary_operator,
10787 oc_constructor,
10788 oc_implicit_default_constructor,
10789 oc_implicit_copy_constructor,
10790 oc_implicit_move_constructor,
10791 oc_implicit_copy_assignment,
10792 oc_implicit_move_assignment,
10793 oc_implicit_equality_comparison,
10794 oc_inherited_constructor
10795};
10796
10797enum OverloadCandidateSelect {
10798 ocs_non_template,
10799 ocs_template,
10800 ocs_described_template,
10801};
10802
10803static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10804ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10805 const FunctionDecl *Fn,
10806 OverloadCandidateRewriteKind CRK,
10807 std::string &Description) {
10808
10809 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10810 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10811 isTemplate = true;
10812 Description = S.getTemplateArgumentBindingsText(
10813 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
10814 }
10815
10816 OverloadCandidateSelect Select = [&]() {
10817 if (!Description.empty())
10818 return ocs_described_template;
10819 return isTemplate ? ocs_template : ocs_non_template;
10820 }();
10821
10822 OverloadCandidateKind Kind = [&]() {
10823 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10824 return oc_implicit_equality_comparison;
10825
10826 if (CRK & CRK_Reversed)
10827 return oc_reversed_binary_operator;
10828
10829 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
10830 if (!Ctor->isImplicit()) {
10831 if (isa<ConstructorUsingShadowDecl>(Val: Found))
10832 return oc_inherited_constructor;
10833 else
10834 return oc_constructor;
10835 }
10836
10837 if (Ctor->isDefaultConstructor())
10838 return oc_implicit_default_constructor;
10839
10840 if (Ctor->isMoveConstructor())
10841 return oc_implicit_move_constructor;
10842
10843 assert(Ctor->isCopyConstructor() &&
10844 "unexpected sort of implicit constructor");
10845 return oc_implicit_copy_constructor;
10846 }
10847
10848 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
10849 // This actually gets spelled 'candidate function' for now, but
10850 // it doesn't hurt to split it out.
10851 if (!Meth->isImplicit())
10852 return oc_method;
10853
10854 if (Meth->isMoveAssignmentOperator())
10855 return oc_implicit_move_assignment;
10856
10857 if (Meth->isCopyAssignmentOperator())
10858 return oc_implicit_copy_assignment;
10859
10860 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10861 return oc_method;
10862 }
10863
10864 return oc_function;
10865 }();
10866
10867 return std::make_pair(x&: Kind, y&: Select);
10868}
10869
10870void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10871 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10872 // set.
10873 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
10874 S.Diag(Loc: FoundDecl->getLocation(),
10875 DiagID: diag::note_ovl_candidate_inherited_constructor)
10876 << Shadow->getNominatedBaseClass();
10877}
10878
10879} // end anonymous namespace
10880
10881static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10882 const FunctionDecl *FD) {
10883 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10884 bool AlwaysTrue;
10885 if (EnableIf->getCond()->isValueDependent() ||
10886 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
10887 return false;
10888 if (!AlwaysTrue)
10889 return false;
10890 }
10891 return true;
10892}
10893
10894/// Returns true if we can take the address of the function.
10895///
10896/// \param Complain - If true, we'll emit a diagnostic
10897/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10898/// we in overload resolution?
10899/// \param Loc - The location of the statement we're complaining about. Ignored
10900/// if we're not complaining, or if we're in overload resolution.
10901static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10902 bool Complain,
10903 bool InOverloadResolution,
10904 SourceLocation Loc) {
10905 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
10906 if (Complain) {
10907 if (InOverloadResolution)
10908 S.Diag(Loc: FD->getBeginLoc(),
10909 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10910 else
10911 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10912 }
10913 return false;
10914 }
10915
10916 if (FD->getTrailingRequiresClause()) {
10917 ConstraintSatisfaction Satisfaction;
10918 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
10919 return false;
10920 if (!Satisfaction.IsSatisfied) {
10921 if (Complain) {
10922 if (InOverloadResolution) {
10923 SmallString<128> TemplateArgString;
10924 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10925 TemplateArgString += " ";
10926 TemplateArgString += S.getTemplateArgumentBindingsText(
10927 Params: FunTmpl->getTemplateParameters(),
10928 Args: *FD->getTemplateSpecializationArgs());
10929 }
10930
10931 S.Diag(Loc: FD->getBeginLoc(),
10932 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
10933 << TemplateArgString;
10934 } else
10935 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
10936 << FD;
10937 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10938 }
10939 return false;
10940 }
10941 }
10942
10943 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
10944 return P->hasAttr<PassObjectSizeAttr>();
10945 });
10946 if (I == FD->param_end())
10947 return true;
10948
10949 if (Complain) {
10950 // Add one to ParamNo because it's user-facing
10951 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
10952 if (InOverloadResolution)
10953 S.Diag(Loc: FD->getLocation(),
10954 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
10955 << ParamNo;
10956 else
10957 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
10958 << FD << ParamNo;
10959 }
10960 return false;
10961}
10962
10963static bool checkAddressOfCandidateIsAvailable(Sema &S,
10964 const FunctionDecl *FD) {
10965 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10966 /*InOverloadResolution=*/true,
10967 /*Loc=*/SourceLocation());
10968}
10969
10970bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10971 bool Complain,
10972 SourceLocation Loc) {
10973 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
10974 /*InOverloadResolution=*/false,
10975 Loc);
10976}
10977
10978// Don't print candidates other than the one that matches the calling
10979// convention of the call operator, since that is guaranteed to exist.
10980static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
10981 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
10982
10983 if (!ConvD)
10984 return false;
10985 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
10986 if (!RD->isLambda())
10987 return false;
10988
10989 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10990 CallingConv CallOpCC =
10991 CallOp->getType()->castAs<FunctionType>()->getCallConv();
10992 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10993 CallingConv ConvToCC =
10994 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10995
10996 return ConvToCC != CallOpCC;
10997}
10998
10999// Notes the location of an overload candidate.
11000void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11001 OverloadCandidateRewriteKind RewriteKind,
11002 QualType DestType, bool TakingAddress) {
11003 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11004 return;
11005 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11006 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11007 return;
11008 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11009 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11010 return;
11011 if (shouldSkipNotingLambdaConversionDecl(Fn))
11012 return;
11013
11014 std::string FnDesc;
11015 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11016 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11017 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11018 << (unsigned)KSPair.first << (unsigned)KSPair.second
11019 << Fn << FnDesc;
11020
11021 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11022 Diag(Loc: Fn->getLocation(), PD);
11023 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11024}
11025
11026static void
11027MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11028 // Perhaps the ambiguity was caused by two atomic constraints that are
11029 // 'identical' but not equivalent:
11030 //
11031 // void foo() requires (sizeof(T) > 4) { } // #1
11032 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11033 //
11034 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11035 // #2 to subsume #1, but these constraint are not considered equivalent
11036 // according to the subsumption rules because they are not the same
11037 // source-level construct. This behavior is quite confusing and we should try
11038 // to help the user figure out what happened.
11039
11040 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11041 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11042 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11043 if (!I->Function)
11044 continue;
11045 SmallVector<const Expr *, 3> AC;
11046 if (auto *Template = I->Function->getPrimaryTemplate())
11047 Template->getAssociatedConstraints(AC);
11048 else
11049 I->Function->getAssociatedConstraints(AC);
11050 if (AC.empty())
11051 continue;
11052 if (FirstCand == nullptr) {
11053 FirstCand = I->Function;
11054 FirstAC = AC;
11055 } else if (SecondCand == nullptr) {
11056 SecondCand = I->Function;
11057 SecondAC = AC;
11058 } else {
11059 // We have more than one pair of constrained functions - this check is
11060 // expensive and we'd rather not try to diagnose it.
11061 return;
11062 }
11063 }
11064 if (!SecondCand)
11065 return;
11066 // The diagnostic can only happen if there are associated constraints on
11067 // both sides (there needs to be some identical atomic constraint).
11068 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11069 D2: SecondCand, AC2: SecondAC))
11070 // Just show the user one diagnostic, they'll probably figure it out
11071 // from here.
11072 return;
11073}
11074
11075// Notes the location of all overload candidates designated through
11076// OverloadedExpr
11077void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11078 bool TakingAddress) {
11079 assert(OverloadedExpr->getType() == Context.OverloadTy);
11080
11081 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11082 OverloadExpr *OvlExpr = Ovl.Expression;
11083
11084 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11085 IEnd = OvlExpr->decls_end();
11086 I != IEnd; ++I) {
11087 if (FunctionTemplateDecl *FunTmpl =
11088 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11089 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11090 TakingAddress);
11091 } else if (FunctionDecl *Fun
11092 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11093 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11094 }
11095 }
11096}
11097
11098/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11099/// "lead" diagnostic; it will be given two arguments, the source and
11100/// target types of the conversion.
11101void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11102 Sema &S,
11103 SourceLocation CaretLoc,
11104 const PartialDiagnostic &PDiag) const {
11105 S.Diag(Loc: CaretLoc, PD: PDiag)
11106 << Ambiguous.getFromType() << Ambiguous.getToType();
11107 unsigned CandsShown = 0;
11108 AmbiguousConversionSequence::const_iterator I, E;
11109 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11110 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11111 break;
11112 ++CandsShown;
11113 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
11114 }
11115 S.Diags.overloadCandidatesShown(N: CandsShown);
11116 if (I != E)
11117 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
11118}
11119
11120static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11121 unsigned I, bool TakingCandidateAddress) {
11122 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11123 assert(Conv.isBad());
11124 assert(Cand->Function && "for now, candidate must be a function");
11125 FunctionDecl *Fn = Cand->Function;
11126
11127 // There's a conversion slot for the object argument if this is a
11128 // non-constructor method. Note that 'I' corresponds the
11129 // conversion-slot index.
11130 bool isObjectArgument = false;
11131 if (isa<CXXMethodDecl>(Val: Fn) && !isa<CXXConstructorDecl>(Val: Fn)) {
11132 if (I == 0)
11133 isObjectArgument = true;
11134 else
11135 I--;
11136 }
11137
11138 std::string FnDesc;
11139 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11140 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
11141 Description&: FnDesc);
11142
11143 Expr *FromExpr = Conv.Bad.FromExpr;
11144 QualType FromTy = Conv.Bad.getFromType();
11145 QualType ToTy = Conv.Bad.getToType();
11146 SourceRange ToParamRange;
11147
11148 // FIXME: In presence of parameter packs we can't determine parameter range
11149 // reliably, as we don't have access to instantiation.
11150 bool HasParamPack =
11151 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
11152 return Parm->isParameterPack();
11153 });
11154 if (!isObjectArgument && !HasParamPack)
11155 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
11156
11157 if (FromTy == S.Context.OverloadTy) {
11158 assert(FromExpr && "overload set argument came from implicit argument?");
11159 Expr *E = FromExpr->IgnoreParens();
11160 if (isa<UnaryOperator>(Val: E))
11161 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
11162 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
11163
11164 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
11165 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11166 << ToParamRange << ToTy << Name << I + 1;
11167 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11168 return;
11169 }
11170
11171 // Do some hand-waving analysis to see if the non-viability is due
11172 // to a qualifier mismatch.
11173 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
11174 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
11175 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11176 CToTy = RT->getPointeeType();
11177 else {
11178 // TODO: detect and diagnose the full richness of const mismatches.
11179 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11180 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11181 CFromTy = FromPT->getPointeeType();
11182 CToTy = ToPT->getPointeeType();
11183 }
11184 }
11185
11186 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11187 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy)) {
11188 Qualifiers FromQs = CFromTy.getQualifiers();
11189 Qualifiers ToQs = CToTy.getQualifiers();
11190
11191 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11192 if (isObjectArgument)
11193 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
11194 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11195 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11196 else
11197 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
11198 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11199 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11200 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11201 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11202 return;
11203 }
11204
11205 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11206 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
11207 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11208 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11209 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11210 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11211 return;
11212 }
11213
11214 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11215 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
11216 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11217 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11218 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11219 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11220 return;
11221 }
11222
11223 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11224 assert(CVR && "expected qualifiers mismatch");
11225
11226 if (isObjectArgument) {
11227 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
11228 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11229 << FromTy << (CVR - 1);
11230 } else {
11231 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
11232 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11233 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11234 }
11235 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11236 return;
11237 }
11238
11239 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11240 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11241 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
11242 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11243 << (unsigned)isObjectArgument << I + 1
11244 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11245 << ToParamRange;
11246 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11247 return;
11248 }
11249
11250 // Special diagnostic for failure to convert an initializer list, since
11251 // telling the user that it has type void is not useful.
11252 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
11253 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
11254 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11255 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11256 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
11257 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
11258 ? 2
11259 : 0);
11260 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11261 return;
11262 }
11263
11264 // Diagnose references or pointers to incomplete types differently,
11265 // since it's far from impossible that the incompleteness triggered
11266 // the failure.
11267 QualType TempFromTy = FromTy.getNonReferenceType();
11268 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11269 TempFromTy = PTy->getPointeeType();
11270 if (TempFromTy->isIncompleteType()) {
11271 // Emit the generic diagnostic and, optionally, add the hints to it.
11272 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
11273 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11274 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11275 << (unsigned)(Cand->Fix.Kind);
11276
11277 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11278 return;
11279 }
11280
11281 // Diagnose base -> derived pointer conversions.
11282 unsigned BaseToDerivedConversion = 0;
11283 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11284 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11285 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11286 other: FromPtrTy->getPointeeType()) &&
11287 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11288 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11289 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
11290 Base: FromPtrTy->getPointeeType()))
11291 BaseToDerivedConversion = 1;
11292 }
11293 } else if (const ObjCObjectPointerType *FromPtrTy
11294 = FromTy->getAs<ObjCObjectPointerType>()) {
11295 if (const ObjCObjectPointerType *ToPtrTy
11296 = ToTy->getAs<ObjCObjectPointerType>())
11297 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11298 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11299 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11300 other: FromPtrTy->getPointeeType()) &&
11301 FromIface->isSuperClassOf(I: ToIface))
11302 BaseToDerivedConversion = 2;
11303 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11304 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy) &&
11305 !FromTy->isIncompleteType() &&
11306 !ToRefTy->getPointeeType()->isIncompleteType() &&
11307 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
11308 BaseToDerivedConversion = 3;
11309 }
11310 }
11311
11312 if (BaseToDerivedConversion) {
11313 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
11314 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11315 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11316 << I + 1;
11317 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11318 return;
11319 }
11320
11321 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
11322 isa<PointerType>(Val: CToTy)) {
11323 Qualifiers FromQs = CFromTy.getQualifiers();
11324 Qualifiers ToQs = CToTy.getQualifiers();
11325 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11326 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
11327 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11328 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11329 << I + 1;
11330 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11331 return;
11332 }
11333 }
11334
11335 if (TakingCandidateAddress &&
11336 !checkAddressOfCandidateIsAvailable(S, FD: Cand->Function))
11337 return;
11338
11339 // Emit the generic diagnostic and, optionally, add the hints to it.
11340 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
11341 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11342 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11343 << (unsigned)(Cand->Fix.Kind);
11344
11345 // Check that location of Fn is not in system header.
11346 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
11347 // If we can fix the conversion, suggest the FixIts.
11348 for (const FixItHint &HI : Cand->Fix.Hints)
11349 FDiag << HI;
11350 }
11351
11352 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
11353
11354 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11355}
11356
11357/// Additional arity mismatch diagnosis specific to a function overload
11358/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11359/// over a candidate in any candidate set.
11360static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
11361 unsigned NumArgs, bool IsAddressOf = false) {
11362 FunctionDecl *Fn = Cand->Function;
11363 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11364 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11365
11366 // With invalid overloaded operators, it's possible that we think we
11367 // have an arity mismatch when in fact it looks like we have the
11368 // right number of arguments, because only overloaded operators have
11369 // the weird behavior of overloading member and non-member functions.
11370 // Just don't report anything.
11371 if (Fn->isInvalidDecl() &&
11372 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11373 return true;
11374
11375 if (NumArgs < MinParams) {
11376 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11377 (Cand->FailureKind == ovl_fail_bad_deduction &&
11378 Cand->DeductionFailure.getResult() ==
11379 TemplateDeductionResult::TooFewArguments));
11380 } else {
11381 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11382 (Cand->FailureKind == ovl_fail_bad_deduction &&
11383 Cand->DeductionFailure.getResult() ==
11384 TemplateDeductionResult::TooManyArguments));
11385 }
11386
11387 return false;
11388}
11389
11390/// General arity mismatch diagnosis over a candidate in a candidate set.
11391static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11392 unsigned NumFormalArgs,
11393 bool IsAddressOf = false) {
11394 assert(isa<FunctionDecl>(D) &&
11395 "The templated declaration should at least be a function"
11396 " when diagnosing bad template argument deduction due to too many"
11397 " or too few arguments");
11398
11399 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
11400
11401 // TODO: treat calls to a missing default constructor as a special case
11402 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11403 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11404 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11405
11406 // at least / at most / exactly
11407 bool HasExplicitObjectParam =
11408 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
11409
11410 unsigned ParamCount =
11411 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11412 unsigned mode, modeCount;
11413
11414 if (NumFormalArgs < MinParams) {
11415 if (MinParams != ParamCount || FnTy->isVariadic() ||
11416 FnTy->isTemplateVariadic())
11417 mode = 0; // "at least"
11418 else
11419 mode = 2; // "exactly"
11420 modeCount = MinParams;
11421 } else {
11422 if (MinParams != ParamCount)
11423 mode = 1; // "at most"
11424 else
11425 mode = 2; // "exactly"
11426 modeCount = ParamCount;
11427 }
11428
11429 std::string Description;
11430 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11431 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
11432
11433 if (modeCount == 1 && !IsAddressOf &&
11434 Fn->getParamDecl(i: HasExplicitObjectParam ? 1 : 0)->getDeclName())
11435 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
11436 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11437 << Description << mode
11438 << Fn->getParamDecl(i: HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11439 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11440 else
11441 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
11442 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11443 << Description << mode << modeCount << NumFormalArgs
11444 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11445
11446 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11447}
11448
11449/// Arity mismatch diagnosis specific to a function overload candidate.
11450static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
11451 unsigned NumFormalArgs) {
11452 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
11453 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Cand->Function, NumFormalArgs,
11454 IsAddressOf: Cand->TookAddressOfOverload);
11455}
11456
11457static TemplateDecl *getDescribedTemplate(Decl *Templated) {
11458 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11459 return TD;
11460 llvm_unreachable("Unsupported: Getting the described template declaration"
11461 " for bad deduction diagnosis");
11462}
11463
11464/// Diagnose a failed template-argument deduction.
11465static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11466 DeductionFailureInfo &DeductionFailure,
11467 unsigned NumArgs,
11468 bool TakingCandidateAddress) {
11469 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11470 NamedDecl *ParamD;
11471 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11472 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11473 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11474 switch (DeductionFailure.getResult()) {
11475 case TemplateDeductionResult::Success:
11476 llvm_unreachable(
11477 "TemplateDeductionResult::Success while diagnosing bad deduction");
11478 case TemplateDeductionResult::NonDependentConversionFailure:
11479 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11480 "while diagnosing bad deduction");
11481 case TemplateDeductionResult::Invalid:
11482 case TemplateDeductionResult::AlreadyDiagnosed:
11483 return;
11484
11485 case TemplateDeductionResult::Incomplete: {
11486 assert(ParamD && "no parameter found for incomplete deduction result");
11487 S.Diag(Loc: Templated->getLocation(),
11488 DiagID: diag::note_ovl_candidate_incomplete_deduction)
11489 << ParamD->getDeclName();
11490 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11491 return;
11492 }
11493
11494 case TemplateDeductionResult::IncompletePack: {
11495 assert(ParamD && "no parameter found for incomplete deduction result");
11496 S.Diag(Loc: Templated->getLocation(),
11497 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
11498 << ParamD->getDeclName()
11499 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11500 << *DeductionFailure.getFirstArg();
11501 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11502 return;
11503 }
11504
11505 case TemplateDeductionResult::Underqualified: {
11506 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11507 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
11508
11509 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11510
11511 // Param will have been canonicalized, but it should just be a
11512 // qualified version of ParamD, so move the qualifiers to that.
11513 QualifierCollector Qs;
11514 Qs.strip(type: Param);
11515 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
11516 assert(S.Context.hasSameType(Param, NonCanonParam));
11517
11518 // Arg has also been canonicalized, but there's nothing we can do
11519 // about that. It also doesn't matter as much, because it won't
11520 // have any template parameters in it (because deduction isn't
11521 // done on dependent types).
11522 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11523
11524 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
11525 << ParamD->getDeclName() << Arg << NonCanonParam;
11526 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11527 return;
11528 }
11529
11530 case TemplateDeductionResult::Inconsistent: {
11531 assert(ParamD && "no parameter found for inconsistent deduction result");
11532 int which = 0;
11533 if (isa<TemplateTypeParmDecl>(Val: ParamD))
11534 which = 0;
11535 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
11536 // Deduction might have failed because we deduced arguments of two
11537 // different types for a non-type template parameter.
11538 // FIXME: Use a different TDK value for this.
11539 QualType T1 =
11540 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11541 QualType T2 =
11542 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11543 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11544 S.Diag(Loc: Templated->getLocation(),
11545 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
11546 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11547 << *DeductionFailure.getSecondArg() << T2;
11548 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11549 return;
11550 }
11551
11552 which = 1;
11553 } else {
11554 which = 2;
11555 }
11556
11557 // Tweak the diagnostic if the problem is that we deduced packs of
11558 // different arities. We'll print the actual packs anyway in case that
11559 // includes additional useful information.
11560 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11561 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11562 DeductionFailure.getFirstArg()->pack_size() !=
11563 DeductionFailure.getSecondArg()->pack_size()) {
11564 which = 3;
11565 }
11566
11567 S.Diag(Loc: Templated->getLocation(),
11568 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
11569 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11570 << *DeductionFailure.getSecondArg();
11571 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11572 return;
11573 }
11574
11575 case TemplateDeductionResult::InvalidExplicitArguments:
11576 assert(ParamD && "no parameter found for invalid explicit arguments");
11577 if (ParamD->getDeclName())
11578 S.Diag(Loc: Templated->getLocation(),
11579 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_named)
11580 << ParamD->getDeclName();
11581 else {
11582 int index = 0;
11583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD))
11584 index = TTP->getIndex();
11585 else if (NonTypeTemplateParmDecl *NTTP
11586 = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD))
11587 index = NTTP->getIndex();
11588 else
11589 index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex();
11590 S.Diag(Loc: Templated->getLocation(),
11591 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11592 << (index + 1);
11593 }
11594 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11595 return;
11596
11597 case TemplateDeductionResult::ConstraintsNotSatisfied: {
11598 // Format the template argument list into the argument string.
11599 SmallString<128> TemplateArgString;
11600 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11601 TemplateArgString = " ";
11602 TemplateArgString += S.getTemplateArgumentBindingsText(
11603 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
11604 if (TemplateArgString.size() == 1)
11605 TemplateArgString.clear();
11606 S.Diag(Loc: Templated->getLocation(),
11607 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11608 << TemplateArgString;
11609
11610 S.DiagnoseUnsatisfiedConstraint(
11611 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11612 return;
11613 }
11614 case TemplateDeductionResult::TooManyArguments:
11615 case TemplateDeductionResult::TooFewArguments:
11616 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs);
11617 return;
11618
11619 case TemplateDeductionResult::InstantiationDepth:
11620 S.Diag(Loc: Templated->getLocation(),
11621 DiagID: diag::note_ovl_candidate_instantiation_depth);
11622 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11623 return;
11624
11625 case TemplateDeductionResult::SubstitutionFailure: {
11626 // Format the template argument list into the argument string.
11627 SmallString<128> TemplateArgString;
11628 if (TemplateArgumentList *Args =
11629 DeductionFailure.getTemplateArgumentList()) {
11630 TemplateArgString = " ";
11631 TemplateArgString += S.getTemplateArgumentBindingsText(
11632 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
11633 if (TemplateArgString.size() == 1)
11634 TemplateArgString.clear();
11635 }
11636
11637 // If this candidate was disabled by enable_if, say so.
11638 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11639 if (PDiag && PDiag->second.getDiagID() ==
11640 diag::err_typename_nested_not_found_enable_if) {
11641 // FIXME: Use the source range of the condition, and the fully-qualified
11642 // name of the enable_if template. These are both present in PDiag.
11643 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
11644 << "'enable_if'" << TemplateArgString;
11645 return;
11646 }
11647
11648 // We found a specific requirement that disabled the enable_if.
11649 if (PDiag && PDiag->second.getDiagID() ==
11650 diag::err_typename_nested_not_found_requirement) {
11651 S.Diag(Loc: Templated->getLocation(),
11652 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
11653 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
11654 return;
11655 }
11656
11657 // Format the SFINAE diagnostic into the argument string.
11658 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11659 // formatted message in another diagnostic.
11660 SmallString<128> SFINAEArgString;
11661 SourceRange R;
11662 if (PDiag) {
11663 SFINAEArgString = ": ";
11664 R = SourceRange(PDiag->first, PDiag->first);
11665 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
11666 }
11667
11668 S.Diag(Loc: Templated->getLocation(),
11669 DiagID: diag::note_ovl_candidate_substitution_failure)
11670 << TemplateArgString << SFINAEArgString << R;
11671 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11672 return;
11673 }
11674
11675 case TemplateDeductionResult::DeducedMismatch:
11676 case TemplateDeductionResult::DeducedMismatchNested: {
11677 // Format the template argument list into the argument string.
11678 SmallString<128> TemplateArgString;
11679 if (TemplateArgumentList *Args =
11680 DeductionFailure.getTemplateArgumentList()) {
11681 TemplateArgString = " ";
11682 TemplateArgString += S.getTemplateArgumentBindingsText(
11683 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
11684 if (TemplateArgString.size() == 1)
11685 TemplateArgString.clear();
11686 }
11687
11688 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
11689 << (*DeductionFailure.getCallArgIndex() + 1)
11690 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11691 << TemplateArgString
11692 << (DeductionFailure.getResult() ==
11693 TemplateDeductionResult::DeducedMismatchNested);
11694 break;
11695 }
11696
11697 case TemplateDeductionResult::NonDeducedMismatch: {
11698 // FIXME: Provide a source location to indicate what we couldn't match.
11699 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11700 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11701 if (FirstTA.getKind() == TemplateArgument::Template &&
11702 SecondTA.getKind() == TemplateArgument::Template) {
11703 TemplateName FirstTN = FirstTA.getAsTemplate();
11704 TemplateName SecondTN = SecondTA.getAsTemplate();
11705 if (FirstTN.getKind() == TemplateName::Template &&
11706 SecondTN.getKind() == TemplateName::Template) {
11707 if (FirstTN.getAsTemplateDecl()->getName() ==
11708 SecondTN.getAsTemplateDecl()->getName()) {
11709 // FIXME: This fixes a bad diagnostic where both templates are named
11710 // the same. This particular case is a bit difficult since:
11711 // 1) It is passed as a string to the diagnostic printer.
11712 // 2) The diagnostic printer only attempts to find a better
11713 // name for types, not decls.
11714 // Ideally, this should folded into the diagnostic printer.
11715 S.Diag(Loc: Templated->getLocation(),
11716 DiagID: diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11717 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11718 return;
11719 }
11720 }
11721 }
11722
11723 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
11724 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
11725 return;
11726
11727 // FIXME: For generic lambda parameters, check if the function is a lambda
11728 // call operator, and if so, emit a prettier and more informative
11729 // diagnostic that mentions 'auto' and lambda in addition to
11730 // (or instead of?) the canonical template type parameters.
11731 S.Diag(Loc: Templated->getLocation(),
11732 DiagID: diag::note_ovl_candidate_non_deduced_mismatch)
11733 << FirstTA << SecondTA;
11734 return;
11735 }
11736 // TODO: diagnose these individually, then kill off
11737 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11738 case TemplateDeductionResult::MiscellaneousDeductionFailure:
11739 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
11740 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
11741 return;
11742 case TemplateDeductionResult::CUDATargetMismatch:
11743 S.Diag(Loc: Templated->getLocation(),
11744 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
11745 return;
11746 }
11747}
11748
11749/// Diagnose a failed template-argument deduction, for function calls.
11750static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11751 unsigned NumArgs,
11752 bool TakingCandidateAddress) {
11753 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
11754 if (TDK == TemplateDeductionResult::TooFewArguments ||
11755 TDK == TemplateDeductionResult::TooManyArguments) {
11756 if (CheckArityMismatch(S, Cand, NumArgs))
11757 return;
11758 }
11759 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Cand->Function, // pattern
11760 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11761}
11762
11763/// CUDA: diagnose an invalid call across targets.
11764static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11765 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11766 FunctionDecl *Callee = Cand->Function;
11767
11768 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
11769 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
11770
11771 std::string FnDesc;
11772 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11773 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
11774 CRK: Cand->getRewriteKind(), Description&: FnDesc);
11775
11776 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
11777 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11778 << FnDesc /* Ignored */
11779 << llvm::to_underlying(E: CalleeTarget) << llvm::to_underlying(E: CallerTarget);
11780
11781 // This could be an implicit constructor for which we could not infer the
11782 // target due to a collsion. Diagnose that case.
11783 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
11784 if (Meth != nullptr && Meth->isImplicit()) {
11785 CXXRecordDecl *ParentClass = Meth->getParent();
11786 CXXSpecialMemberKind CSM;
11787
11788 switch (FnKindPair.first) {
11789 default:
11790 return;
11791 case oc_implicit_default_constructor:
11792 CSM = CXXSpecialMemberKind::DefaultConstructor;
11793 break;
11794 case oc_implicit_copy_constructor:
11795 CSM = CXXSpecialMemberKind::CopyConstructor;
11796 break;
11797 case oc_implicit_move_constructor:
11798 CSM = CXXSpecialMemberKind::MoveConstructor;
11799 break;
11800 case oc_implicit_copy_assignment:
11801 CSM = CXXSpecialMemberKind::CopyAssignment;
11802 break;
11803 case oc_implicit_move_assignment:
11804 CSM = CXXSpecialMemberKind::MoveAssignment;
11805 break;
11806 };
11807
11808 bool ConstRHS = false;
11809 if (Meth->getNumParams()) {
11810 if (const ReferenceType *RT =
11811 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
11812 ConstRHS = RT->getPointeeType().isConstQualified();
11813 }
11814 }
11815
11816 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
11817 /* ConstRHS */ ConstRHS,
11818 /* Diagnose */ true);
11819 }
11820}
11821
11822static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11823 FunctionDecl *Callee = Cand->Function;
11824 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11825
11826 S.Diag(Loc: Callee->getLocation(),
11827 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
11828 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11829}
11830
11831static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11832 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Cand->Function);
11833 assert(ES.isExplicit() && "not an explicit candidate");
11834
11835 unsigned Kind;
11836 switch (Cand->Function->getDeclKind()) {
11837 case Decl::Kind::CXXConstructor:
11838 Kind = 0;
11839 break;
11840 case Decl::Kind::CXXConversion:
11841 Kind = 1;
11842 break;
11843 case Decl::Kind::CXXDeductionGuide:
11844 Kind = Cand->Function->isImplicit() ? 0 : 2;
11845 break;
11846 default:
11847 llvm_unreachable("invalid Decl");
11848 }
11849
11850 // Note the location of the first (in-class) declaration; a redeclaration
11851 // (particularly an out-of-class definition) will typically lack the
11852 // 'explicit' specifier.
11853 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11854 FunctionDecl *First = Cand->Function->getFirstDecl();
11855 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11856 First = Pattern->getFirstDecl();
11857
11858 S.Diag(Loc: First->getLocation(),
11859 DiagID: diag::note_ovl_candidate_explicit)
11860 << Kind << (ES.getExpr() ? 1 : 0)
11861 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11862}
11863
11864static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
11865 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
11866 if (!DG)
11867 return;
11868 TemplateDecl *OriginTemplate =
11869 DG->getDeclName().getCXXDeductionGuideTemplate();
11870 // We want to always print synthesized deduction guides for type aliases.
11871 // They would retain the explicit bit of the corresponding constructor.
11872 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
11873 return;
11874 std::string FunctionProto;
11875 llvm::raw_string_ostream OS(FunctionProto);
11876 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
11877 if (!Template) {
11878 // This also could be an instantiation. Find out the primary template.
11879 FunctionDecl *Pattern =
11880 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
11881 if (!Pattern) {
11882 // The implicit deduction guide is built on an explicit non-template
11883 // deduction guide. Currently, this might be the case only for type
11884 // aliases.
11885 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
11886 // gets merged.
11887 assert(OriginTemplate->isTypeAlias() &&
11888 "Non-template implicit deduction guides are only possible for "
11889 "type aliases");
11890 DG->print(Out&: OS);
11891 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
11892 << FunctionProto;
11893 return;
11894 }
11895 Template = Pattern->getDescribedFunctionTemplate();
11896 assert(Template && "Cannot find the associated function template of "
11897 "CXXDeductionGuideDecl?");
11898 }
11899 Template->print(Out&: OS);
11900 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
11901 << FunctionProto;
11902}
11903
11904/// Generates a 'note' diagnostic for an overload candidate. We've
11905/// already generated a primary error at the call site.
11906///
11907/// It really does need to be a single diagnostic with its caret
11908/// pointed at the candidate declaration. Yes, this creates some
11909/// major challenges of technical writing. Yes, this makes pointing
11910/// out problems with specific arguments quite awkward. It's still
11911/// better than generating twenty screens of text for every failed
11912/// overload.
11913///
11914/// It would be great to be able to express per-candidate problems
11915/// more richly for those diagnostic clients that cared, but we'd
11916/// still have to be just as careful with the default diagnostics.
11917/// \param CtorDestAS Addr space of object being constructed (for ctor
11918/// candidates only).
11919static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11920 unsigned NumArgs,
11921 bool TakingCandidateAddress,
11922 LangAS CtorDestAS = LangAS::Default) {
11923 FunctionDecl *Fn = Cand->Function;
11924 if (shouldSkipNotingLambdaConversionDecl(Fn))
11925 return;
11926
11927 // There is no physical candidate declaration to point to for OpenCL builtins.
11928 // Except for failed conversions, the notes are identical for each candidate,
11929 // so do not generate such notes.
11930 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11931 Cand->FailureKind != ovl_fail_bad_conversion)
11932 return;
11933
11934 // Skip implicit member functions when trying to resolve
11935 // the address of a an overload set for a function pointer.
11936 if (Cand->TookAddressOfOverload &&
11937 !Cand->Function->hasCXXExplicitFunctionObjectParameter() &&
11938 !Cand->Function->isStatic())
11939 return;
11940
11941 // Note deleted candidates, but only if they're viable.
11942 if (Cand->Viable) {
11943 if (Fn->isDeleted()) {
11944 std::string FnDesc;
11945 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11946 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
11947 CRK: Cand->getRewriteKind(), Description&: FnDesc);
11948
11949 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
11950 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11951 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11952 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11953 return;
11954 }
11955
11956 // We don't really have anything else to say about viable candidates.
11957 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
11958 return;
11959 }
11960
11961 // If this is a synthesized deduction guide we're deducing against, add a note
11962 // for it. These deduction guides are not explicitly spelled in the source
11963 // code, so simply printing a deduction failure note mentioning synthesized
11964 // template parameters or pointing to the header of the surrounding RecordDecl
11965 // would be confusing.
11966 //
11967 // We prefer adding such notes at the end of the deduction failure because
11968 // duplicate code snippets appearing in the diagnostic would likely become
11969 // noisy.
11970 auto _ = llvm::make_scope_exit(F: [&] { NoteImplicitDeductionGuide(S, Fn); });
11971
11972 switch (Cand->FailureKind) {
11973 case ovl_fail_too_many_arguments:
11974 case ovl_fail_too_few_arguments:
11975 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
11976
11977 case ovl_fail_bad_deduction:
11978 return DiagnoseBadDeduction(S, Cand, NumArgs,
11979 TakingCandidateAddress);
11980
11981 case ovl_fail_illegal_constructor: {
11982 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
11983 << (Fn->getPrimaryTemplate() ? 1 : 0);
11984 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11985 return;
11986 }
11987
11988 case ovl_fail_object_addrspace_mismatch: {
11989 Qualifiers QualsForPrinting;
11990 QualsForPrinting.setAddressSpace(CtorDestAS);
11991 S.Diag(Loc: Fn->getLocation(),
11992 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11993 << QualsForPrinting;
11994 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11995 return;
11996 }
11997
11998 case ovl_fail_trivial_conversion:
11999 case ovl_fail_bad_final_conversion:
12000 case ovl_fail_final_conversion_not_exact:
12001 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12002
12003 case ovl_fail_bad_conversion: {
12004 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12005 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12006 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12007 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12008
12009 // FIXME: this currently happens when we're called from SemaInit
12010 // when user-conversion overload fails. Figure out how to handle
12011 // those conditions and diagnose them well.
12012 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12013 }
12014
12015 case ovl_fail_bad_target:
12016 return DiagnoseBadTarget(S, Cand);
12017
12018 case ovl_fail_enable_if:
12019 return DiagnoseFailedEnableIfAttr(S, Cand);
12020
12021 case ovl_fail_explicit:
12022 return DiagnoseFailedExplicitSpec(S, Cand);
12023
12024 case ovl_fail_inhctor_slice:
12025 // It's generally not interesting to note copy/move constructors here.
12026 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12027 return;
12028 S.Diag(Loc: Fn->getLocation(),
12029 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
12030 << (Fn->getPrimaryTemplate() ? 1 : 0)
12031 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
12032 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12033 return;
12034
12035 case ovl_fail_addr_not_available: {
12036 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Cand->Function);
12037 (void)Available;
12038 assert(!Available);
12039 break;
12040 }
12041 case ovl_non_default_multiversion_function:
12042 // Do nothing, these should simply be ignored.
12043 break;
12044
12045 case ovl_fail_constraints_not_satisfied: {
12046 std::string FnDesc;
12047 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12048 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12049 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12050
12051 S.Diag(Loc: Fn->getLocation(),
12052 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
12053 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12054 << FnDesc /* Ignored */;
12055 ConstraintSatisfaction Satisfaction;
12056 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction))
12057 break;
12058 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12059 }
12060 }
12061}
12062
12063static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12064 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
12065 return;
12066
12067 // Desugar the type of the surrogate down to a function type,
12068 // retaining as many typedefs as possible while still showing
12069 // the function type (and, therefore, its parameter types).
12070 QualType FnType = Cand->Surrogate->getConversionType();
12071 bool isLValueReference = false;
12072 bool isRValueReference = false;
12073 bool isPointer = false;
12074 if (const LValueReferenceType *FnTypeRef =
12075 FnType->getAs<LValueReferenceType>()) {
12076 FnType = FnTypeRef->getPointeeType();
12077 isLValueReference = true;
12078 } else if (const RValueReferenceType *FnTypeRef =
12079 FnType->getAs<RValueReferenceType>()) {
12080 FnType = FnTypeRef->getPointeeType();
12081 isRValueReference = true;
12082 }
12083 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12084 FnType = FnTypePtr->getPointeeType();
12085 isPointer = true;
12086 }
12087 // Desugar down to a function type.
12088 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12089 // Reconstruct the pointer/reference as appropriate.
12090 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
12091 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
12092 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
12093
12094 if (!Cand->Viable &&
12095 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12096 S.Diag(Loc: Cand->Surrogate->getLocation(),
12097 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
12098 << Cand->Surrogate;
12099 ConstraintSatisfaction Satisfaction;
12100 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
12101 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12102 } else {
12103 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
12104 << FnType;
12105 }
12106}
12107
12108static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12109 SourceLocation OpLoc,
12110 OverloadCandidate *Cand) {
12111 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12112 std::string TypeStr("operator");
12113 TypeStr += Opc;
12114 TypeStr += "(";
12115 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12116 if (Cand->Conversions.size() == 1) {
12117 TypeStr += ")";
12118 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
12119 } else {
12120 TypeStr += ", ";
12121 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12122 TypeStr += ")";
12123 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
12124 }
12125}
12126
12127static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12128 OverloadCandidate *Cand) {
12129 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12130 if (ICS.isBad()) break; // all meaningless after first invalid
12131 if (!ICS.isAmbiguous()) continue;
12132
12133 ICS.DiagnoseAmbiguousConversion(
12134 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
12135 }
12136}
12137
12138static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12139 if (Cand->Function)
12140 return Cand->Function->getLocation();
12141 if (Cand->IsSurrogate)
12142 return Cand->Surrogate->getLocation();
12143 return SourceLocation();
12144}
12145
12146static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12147 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12148 case TemplateDeductionResult::Success:
12149 case TemplateDeductionResult::NonDependentConversionFailure:
12150 case TemplateDeductionResult::AlreadyDiagnosed:
12151 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12152
12153 case TemplateDeductionResult::Invalid:
12154 case TemplateDeductionResult::Incomplete:
12155 case TemplateDeductionResult::IncompletePack:
12156 return 1;
12157
12158 case TemplateDeductionResult::Underqualified:
12159 case TemplateDeductionResult::Inconsistent:
12160 return 2;
12161
12162 case TemplateDeductionResult::SubstitutionFailure:
12163 case TemplateDeductionResult::DeducedMismatch:
12164 case TemplateDeductionResult::ConstraintsNotSatisfied:
12165 case TemplateDeductionResult::DeducedMismatchNested:
12166 case TemplateDeductionResult::NonDeducedMismatch:
12167 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12168 case TemplateDeductionResult::CUDATargetMismatch:
12169 return 3;
12170
12171 case TemplateDeductionResult::InstantiationDepth:
12172 return 4;
12173
12174 case TemplateDeductionResult::InvalidExplicitArguments:
12175 return 5;
12176
12177 case TemplateDeductionResult::TooManyArguments:
12178 case TemplateDeductionResult::TooFewArguments:
12179 return 6;
12180 }
12181 llvm_unreachable("Unhandled deduction result");
12182}
12183
12184namespace {
12185
12186struct CompareOverloadCandidatesForDisplay {
12187 Sema &S;
12188 SourceLocation Loc;
12189 size_t NumArgs;
12190 OverloadCandidateSet::CandidateSetKind CSK;
12191
12192 CompareOverloadCandidatesForDisplay(
12193 Sema &S, SourceLocation Loc, size_t NArgs,
12194 OverloadCandidateSet::CandidateSetKind CSK)
12195 : S(S), NumArgs(NArgs), CSK(CSK) {}
12196
12197 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12198 // If there are too many or too few arguments, that's the high-order bit we
12199 // want to sort by, even if the immediate failure kind was something else.
12200 if (C->FailureKind == ovl_fail_too_many_arguments ||
12201 C->FailureKind == ovl_fail_too_few_arguments)
12202 return static_cast<OverloadFailureKind>(C->FailureKind);
12203
12204 if (C->Function) {
12205 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12206 return ovl_fail_too_many_arguments;
12207 if (NumArgs < C->Function->getMinRequiredArguments())
12208 return ovl_fail_too_few_arguments;
12209 }
12210
12211 return static_cast<OverloadFailureKind>(C->FailureKind);
12212 }
12213
12214 bool operator()(const OverloadCandidate *L,
12215 const OverloadCandidate *R) {
12216 // Fast-path this check.
12217 if (L == R) return false;
12218
12219 // Order first by viability.
12220 if (L->Viable) {
12221 if (!R->Viable) return true;
12222
12223 if (int Ord = CompareConversions(L: *L, R: *R))
12224 return Ord < 0;
12225 // Use other tie breakers.
12226 } else if (R->Viable)
12227 return false;
12228
12229 assert(L->Viable == R->Viable);
12230
12231 // Criteria by which we can sort non-viable candidates:
12232 if (!L->Viable) {
12233 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
12234 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
12235
12236 // 1. Arity mismatches come after other candidates.
12237 if (LFailureKind == ovl_fail_too_many_arguments ||
12238 LFailureKind == ovl_fail_too_few_arguments) {
12239 if (RFailureKind == ovl_fail_too_many_arguments ||
12240 RFailureKind == ovl_fail_too_few_arguments) {
12241 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
12242 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
12243 if (LDist == RDist) {
12244 if (LFailureKind == RFailureKind)
12245 // Sort non-surrogates before surrogates.
12246 return !L->IsSurrogate && R->IsSurrogate;
12247 // Sort candidates requiring fewer parameters than there were
12248 // arguments given after candidates requiring more parameters
12249 // than there were arguments given.
12250 return LFailureKind == ovl_fail_too_many_arguments;
12251 }
12252 return LDist < RDist;
12253 }
12254 return false;
12255 }
12256 if (RFailureKind == ovl_fail_too_many_arguments ||
12257 RFailureKind == ovl_fail_too_few_arguments)
12258 return true;
12259
12260 // 2. Bad conversions come first and are ordered by the number
12261 // of bad conversions and quality of good conversions.
12262 if (LFailureKind == ovl_fail_bad_conversion) {
12263 if (RFailureKind != ovl_fail_bad_conversion)
12264 return true;
12265
12266 // The conversion that can be fixed with a smaller number of changes,
12267 // comes first.
12268 unsigned numLFixes = L->Fix.NumConversionsFixed;
12269 unsigned numRFixes = R->Fix.NumConversionsFixed;
12270 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12271 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12272 if (numLFixes != numRFixes) {
12273 return numLFixes < numRFixes;
12274 }
12275
12276 // If there's any ordering between the defined conversions...
12277 if (int Ord = CompareConversions(L: *L, R: *R))
12278 return Ord < 0;
12279 } else if (RFailureKind == ovl_fail_bad_conversion)
12280 return false;
12281
12282 if (LFailureKind == ovl_fail_bad_deduction) {
12283 if (RFailureKind != ovl_fail_bad_deduction)
12284 return true;
12285
12286 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
12287 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
12288 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
12289 if (LRank != RRank)
12290 return LRank < RRank;
12291 }
12292 } else if (RFailureKind == ovl_fail_bad_deduction)
12293 return false;
12294
12295 // TODO: others?
12296 }
12297
12298 // Sort everything else by location.
12299 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
12300 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
12301
12302 // Put candidates without locations (e.g. builtins) at the end.
12303 if (LLoc.isValid() && RLoc.isValid())
12304 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
12305 if (LLoc.isValid() && !RLoc.isValid())
12306 return true;
12307 if (RLoc.isValid() && !LLoc.isValid())
12308 return false;
12309 assert(!LLoc.isValid() && !RLoc.isValid());
12310 // For builtins and other functions without locations, fallback to the order
12311 // in which they were added into the candidate set.
12312 return L < R;
12313 }
12314
12315private:
12316 struct ConversionSignals {
12317 unsigned KindRank = 0;
12318 ImplicitConversionRank Rank = ICR_Exact_Match;
12319
12320 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12321 ConversionSignals Sig;
12322 Sig.KindRank = Seq.getKindRank();
12323 if (Seq.isStandard())
12324 Sig.Rank = Seq.Standard.getRank();
12325 else if (Seq.isUserDefined())
12326 Sig.Rank = Seq.UserDefined.After.getRank();
12327 // We intend StaticObjectArgumentConversion to compare the same as
12328 // StandardConversion with ICR_ExactMatch rank.
12329 return Sig;
12330 }
12331
12332 static ConversionSignals ForObjectArgument() {
12333 // We intend StaticObjectArgumentConversion to compare the same as
12334 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12335 return {};
12336 }
12337 };
12338
12339 // Returns -1 if conversions in L are considered better.
12340 // 0 if they are considered indistinguishable.
12341 // 1 if conversions in R are better.
12342 int CompareConversions(const OverloadCandidate &L,
12343 const OverloadCandidate &R) {
12344 // We cannot use `isBetterOverloadCandidate` because it is defined
12345 // according to the C++ standard and provides a partial order, but we need
12346 // a total order as this function is used in sort.
12347 assert(L.Conversions.size() == R.Conversions.size());
12348 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12349 auto LS = L.IgnoreObjectArgument && I == 0
12350 ? ConversionSignals::ForObjectArgument()
12351 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
12352 auto RS = R.IgnoreObjectArgument
12353 ? ConversionSignals::ForObjectArgument()
12354 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
12355 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
12356 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
12357 ? -1
12358 : 1;
12359 }
12360 // FIXME: find a way to compare templates for being more or less
12361 // specialized that provides a strict weak ordering.
12362 return 0;
12363 }
12364};
12365}
12366
12367/// CompleteNonViableCandidate - Normally, overload resolution only
12368/// computes up to the first bad conversion. Produces the FixIt set if
12369/// possible.
12370static void
12371CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
12372 ArrayRef<Expr *> Args,
12373 OverloadCandidateSet::CandidateSetKind CSK) {
12374 assert(!Cand->Viable);
12375
12376 // Don't do anything on failures other than bad conversion.
12377 if (Cand->FailureKind != ovl_fail_bad_conversion)
12378 return;
12379
12380 // We only want the FixIts if all the arguments can be corrected.
12381 bool Unfixable = false;
12382 // Use a implicit copy initialization to check conversion fixes.
12383 Cand->Fix.setConversionChecker(TryCopyInitialization);
12384
12385 // Attempt to fix the bad conversion.
12386 unsigned ConvCount = Cand->Conversions.size();
12387 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12388 ++ConvIdx) {
12389 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12390 if (Cand->Conversions[ConvIdx].isInitialized() &&
12391 Cand->Conversions[ConvIdx].isBad()) {
12392 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
12393 break;
12394 }
12395 }
12396
12397 // FIXME: this should probably be preserved from the overload
12398 // operation somehow.
12399 bool SuppressUserConversions = false;
12400
12401 unsigned ConvIdx = 0;
12402 unsigned ArgIdx = 0;
12403 ArrayRef<QualType> ParamTypes;
12404 bool Reversed = Cand->isReversed();
12405
12406 if (Cand->IsSurrogate) {
12407 QualType ConvType
12408 = Cand->Surrogate->getConversionType().getNonReferenceType();
12409 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12410 ConvType = ConvPtrType->getPointeeType();
12411 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12412 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12413 ConvIdx = 1;
12414 } else if (Cand->Function) {
12415 ParamTypes =
12416 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12417 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
12418 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed) {
12419 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12420 ConvIdx = 1;
12421 if (CSK == OverloadCandidateSet::CSK_Operator &&
12422 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12423 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
12424 OO_Subscript)
12425 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12426 ArgIdx = 1;
12427 }
12428 } else {
12429 // Builtin operator.
12430 assert(ConvCount <= 3);
12431 ParamTypes = Cand->BuiltinParamTypes;
12432 }
12433
12434 // Fill in the rest of the conversions.
12435 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12436 ConvIdx != ConvCount;
12437 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12438 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12439 if (Cand->Conversions[ConvIdx].isInitialized()) {
12440 // We've already checked this conversion.
12441 } else if (ParamIdx < ParamTypes.size()) {
12442 if (ParamTypes[ParamIdx]->isDependentType())
12443 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12444 Args[ArgIdx]->getType());
12445 else {
12446 Cand->Conversions[ConvIdx] =
12447 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
12448 SuppressUserConversions,
12449 /*InOverloadResolution=*/true,
12450 /*AllowObjCWritebackConversion=*/
12451 S.getLangOpts().ObjCAutoRefCount);
12452 // Store the FixIt in the candidate if it exists.
12453 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12454 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
12455 }
12456 } else
12457 Cand->Conversions[ConvIdx].setEllipsis();
12458 }
12459}
12460
12461SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
12462 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
12463 SourceLocation OpLoc,
12464 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12465 // Sort the candidates by viability and position. Sorting directly would
12466 // be prohibitive, so we make a set of pointers and sort those.
12467 SmallVector<OverloadCandidate*, 32> Cands;
12468 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
12469 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12470 if (!Filter(*Cand))
12471 continue;
12472 switch (OCD) {
12473 case OCD_AllCandidates:
12474 if (!Cand->Viable) {
12475 if (!Cand->Function && !Cand->IsSurrogate) {
12476 // This a non-viable builtin candidate. We do not, in general,
12477 // want to list every possible builtin candidate.
12478 continue;
12479 }
12480 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
12481 }
12482 break;
12483
12484 case OCD_ViableCandidates:
12485 if (!Cand->Viable)
12486 continue;
12487 break;
12488
12489 case OCD_AmbiguousCandidates:
12490 if (!Cand->Best)
12491 continue;
12492 break;
12493 }
12494
12495 Cands.push_back(Elt: Cand);
12496 }
12497
12498 llvm::stable_sort(
12499 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12500
12501 return Cands;
12502}
12503
12504bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
12505 SourceLocation OpLoc) {
12506 bool DeferHint = false;
12507 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12508 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12509 // host device candidates.
12510 auto WrongSidedCands =
12511 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
12512 return (Cand.Viable == false &&
12513 Cand.FailureKind == ovl_fail_bad_target) ||
12514 (Cand.Function &&
12515 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12516 Cand.Function->template hasAttr<CUDADeviceAttr>());
12517 });
12518 DeferHint = !WrongSidedCands.empty();
12519 }
12520 return DeferHint;
12521}
12522
12523/// When overload resolution fails, prints diagnostic messages containing the
12524/// candidates in the candidate set.
12525void OverloadCandidateSet::NoteCandidates(
12526 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
12527 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12528 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12529
12530 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12531
12532 S.Diag(Loc: PD.first, PD: PD.second, DeferHint: shouldDeferDiags(S, Args, OpLoc));
12533
12534 // In WebAssembly we don't want to emit further diagnostics if a table is
12535 // passed as an argument to a function.
12536 bool NoteCands = true;
12537 for (const Expr *Arg : Args) {
12538 if (Arg->getType()->isWebAssemblyTableType())
12539 NoteCands = false;
12540 }
12541
12542 if (NoteCands)
12543 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12544
12545 if (OCD == OCD_AmbiguousCandidates)
12546 MaybeDiagnoseAmbiguousConstraints(S, Cands: {begin(), end()});
12547}
12548
12549void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
12550 ArrayRef<OverloadCandidate *> Cands,
12551 StringRef Opc, SourceLocation OpLoc) {
12552 bool ReportedAmbiguousConversions = false;
12553
12554 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12555 unsigned CandsShown = 0;
12556 auto I = Cands.begin(), E = Cands.end();
12557 for (; I != E; ++I) {
12558 OverloadCandidate *Cand = *I;
12559
12560 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12561 ShowOverloads == Ovl_Best) {
12562 break;
12563 }
12564 ++CandsShown;
12565
12566 if (Cand->Function)
12567 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
12568 /*TakingCandidateAddress=*/false, CtorDestAS: DestAS);
12569 else if (Cand->IsSurrogate)
12570 NoteSurrogateCandidate(S, Cand);
12571 else {
12572 assert(Cand->Viable &&
12573 "Non-viable built-in candidates are not added to Cands.");
12574 // Generally we only see ambiguities including viable builtin
12575 // operators if overload resolution got screwed up by an
12576 // ambiguous user-defined conversion.
12577 //
12578 // FIXME: It's quite possible for different conversions to see
12579 // different ambiguities, though.
12580 if (!ReportedAmbiguousConversions) {
12581 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12582 ReportedAmbiguousConversions = true;
12583 }
12584
12585 // If this is a viable builtin, print it.
12586 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12587 }
12588 }
12589
12590 // Inform S.Diags that we've shown an overload set with N elements. This may
12591 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12592 S.Diags.overloadCandidatesShown(N: CandsShown);
12593
12594 if (I != E)
12595 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates,
12596 DeferHint: shouldDeferDiags(S, Args, OpLoc))
12597 << int(E - I);
12598}
12599
12600static SourceLocation
12601GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
12602 return Cand->Specialization ? Cand->Specialization->getLocation()
12603 : SourceLocation();
12604}
12605
12606namespace {
12607struct CompareTemplateSpecCandidatesForDisplay {
12608 Sema &S;
12609 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12610
12611 bool operator()(const TemplateSpecCandidate *L,
12612 const TemplateSpecCandidate *R) {
12613 // Fast-path this check.
12614 if (L == R)
12615 return false;
12616
12617 // Assuming that both candidates are not matches...
12618
12619 // Sort by the ranking of deduction failures.
12620 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
12621 return RankDeductionFailure(DFI: L->DeductionFailure) <
12622 RankDeductionFailure(DFI: R->DeductionFailure);
12623
12624 // Sort everything else by location.
12625 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
12626 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
12627
12628 // Put candidates without locations (e.g. builtins) at the end.
12629 if (LLoc.isInvalid())
12630 return false;
12631 if (RLoc.isInvalid())
12632 return true;
12633
12634 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
12635 }
12636};
12637}
12638
12639/// Diagnose a template argument deduction failure.
12640/// We are treating these failures as overload failures due to bad
12641/// deductions.
12642void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
12643 bool ForTakingAddress) {
12644 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
12645 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
12646}
12647
12648void TemplateSpecCandidateSet::destroyCandidates() {
12649 for (iterator i = begin(), e = end(); i != e; ++i) {
12650 i->DeductionFailure.Destroy();
12651 }
12652}
12653
12654void TemplateSpecCandidateSet::clear() {
12655 destroyCandidates();
12656 Candidates.clear();
12657}
12658
12659/// NoteCandidates - When no template specialization match is found, prints
12660/// diagnostic messages containing the non-matching specializations that form
12661/// the candidate set.
12662/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12663/// OCD == OCD_AllCandidates and Cand->Viable == false.
12664void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12665 // Sort the candidates by position (assuming no candidate is a match).
12666 // Sorting directly would be prohibitive, so we make a set of pointers
12667 // and sort those.
12668 SmallVector<TemplateSpecCandidate *, 32> Cands;
12669 Cands.reserve(N: size());
12670 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12671 if (Cand->Specialization)
12672 Cands.push_back(Elt: Cand);
12673 // Otherwise, this is a non-matching builtin candidate. We do not,
12674 // in general, want to list every possible builtin candidate.
12675 }
12676
12677 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
12678
12679 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12680 // for generalization purposes (?).
12681 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12682
12683 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12684 unsigned CandsShown = 0;
12685 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12686 TemplateSpecCandidate *Cand = *I;
12687
12688 // Set an arbitrary limit on the number of candidates we'll spam
12689 // the user with. FIXME: This limit should depend on details of the
12690 // candidate list.
12691 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12692 break;
12693 ++CandsShown;
12694
12695 assert(Cand->Specialization &&
12696 "Non-matching built-in candidates are not added to Cands.");
12697 Cand->NoteDeductionFailure(S, ForTakingAddress);
12698 }
12699
12700 if (I != E)
12701 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
12702}
12703
12704// [PossiblyAFunctionType] --> [Return]
12705// NonFunctionType --> NonFunctionType
12706// R (A) --> R(A)
12707// R (*)(A) --> R (A)
12708// R (&)(A) --> R (A)
12709// R (S::*)(A) --> R (A)
12710QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12711 QualType Ret = PossiblyAFunctionType;
12712 if (const PointerType *ToTypePtr =
12713 PossiblyAFunctionType->getAs<PointerType>())
12714 Ret = ToTypePtr->getPointeeType();
12715 else if (const ReferenceType *ToTypeRef =
12716 PossiblyAFunctionType->getAs<ReferenceType>())
12717 Ret = ToTypeRef->getPointeeType();
12718 else if (const MemberPointerType *MemTypePtr =
12719 PossiblyAFunctionType->getAs<MemberPointerType>())
12720 Ret = MemTypePtr->getPointeeType();
12721 Ret =
12722 Context.getCanonicalType(T: Ret).getUnqualifiedType();
12723 return Ret;
12724}
12725
12726static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12727 bool Complain = true) {
12728 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12729 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
12730 return true;
12731
12732 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12733 if (S.getLangOpts().CPlusPlus17 &&
12734 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
12735 !S.ResolveExceptionSpec(Loc, FPT))
12736 return true;
12737
12738 return false;
12739}
12740
12741namespace {
12742// A helper class to help with address of function resolution
12743// - allows us to avoid passing around all those ugly parameters
12744class AddressOfFunctionResolver {
12745 Sema& S;
12746 Expr* SourceExpr;
12747 const QualType& TargetType;
12748 QualType TargetFunctionType; // Extracted function type from target type
12749
12750 bool Complain;
12751 //DeclAccessPair& ResultFunctionAccessPair;
12752 ASTContext& Context;
12753
12754 bool TargetTypeIsNonStaticMemberFunction;
12755 bool FoundNonTemplateFunction;
12756 bool StaticMemberFunctionFromBoundPointer;
12757 bool HasComplained;
12758
12759 OverloadExpr::FindResult OvlExprInfo;
12760 OverloadExpr *OvlExpr;
12761 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12762 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12763 TemplateSpecCandidateSet FailedCandidates;
12764
12765public:
12766 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12767 const QualType &TargetType, bool Complain)
12768 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12769 Complain(Complain), Context(S.getASTContext()),
12770 TargetTypeIsNonStaticMemberFunction(
12771 !!TargetType->getAs<MemberPointerType>()),
12772 FoundNonTemplateFunction(false),
12773 StaticMemberFunctionFromBoundPointer(false),
12774 HasComplained(false),
12775 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
12776 OvlExpr(OvlExprInfo.Expression),
12777 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12778 ExtractUnqualifiedFunctionTypeFromTargetType();
12779
12780 if (TargetFunctionType->isFunctionType()) {
12781 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
12782 if (!UME->isImplicitAccess() &&
12783 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
12784 StaticMemberFunctionFromBoundPointer = true;
12785 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12786 DeclAccessPair dap;
12787 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12788 ovl: OvlExpr, Complain: false, Found: &dap)) {
12789 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
12790 if (!Method->isStatic()) {
12791 // If the target type is a non-function type and the function found
12792 // is a non-static member function, pretend as if that was the
12793 // target, it's the only possible type to end up with.
12794 TargetTypeIsNonStaticMemberFunction = true;
12795
12796 // And skip adding the function if its not in the proper form.
12797 // We'll diagnose this due to an empty set of functions.
12798 if (!OvlExprInfo.HasFormOfMemberPointer)
12799 return;
12800 }
12801
12802 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
12803 }
12804 return;
12805 }
12806
12807 if (OvlExpr->hasExplicitTemplateArgs())
12808 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
12809
12810 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12811 // C++ [over.over]p4:
12812 // If more than one function is selected, [...]
12813 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12814 if (FoundNonTemplateFunction)
12815 EliminateAllTemplateMatches();
12816 else
12817 EliminateAllExceptMostSpecializedTemplate();
12818 }
12819 }
12820
12821 if (S.getLangOpts().CUDA && Matches.size() > 1)
12822 EliminateSuboptimalCudaMatches();
12823 }
12824
12825 bool hasComplained() const { return HasComplained; }
12826
12827private:
12828 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12829 QualType Discard;
12830 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
12831 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType, ResultTy&: Discard);
12832 }
12833
12834 /// \return true if A is considered a better overload candidate for the
12835 /// desired type than B.
12836 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12837 // If A doesn't have exactly the correct type, we don't want to classify it
12838 // as "better" than anything else. This way, the user is required to
12839 // disambiguate for us if there are multiple candidates and no exact match.
12840 return candidateHasExactlyCorrectType(FD: A) &&
12841 (!candidateHasExactlyCorrectType(FD: B) ||
12842 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
12843 }
12844
12845 /// \return true if we were able to eliminate all but one overload candidate,
12846 /// false otherwise.
12847 bool eliminiateSuboptimalOverloadCandidates() {
12848 // Same algorithm as overload resolution -- one pass to pick the "best",
12849 // another pass to be sure that nothing is better than the best.
12850 auto Best = Matches.begin();
12851 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12852 if (isBetterCandidate(A: I->second, B: Best->second))
12853 Best = I;
12854
12855 const FunctionDecl *BestFn = Best->second;
12856 auto IsBestOrInferiorToBest = [this, BestFn](
12857 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12858 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
12859 };
12860
12861 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12862 // option, so we can potentially give the user a better error
12863 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
12864 return false;
12865 Matches[0] = *Best;
12866 Matches.resize(N: 1);
12867 return true;
12868 }
12869
12870 bool isTargetTypeAFunction() const {
12871 return TargetFunctionType->isFunctionType();
12872 }
12873
12874 // [ToType] [Return]
12875
12876 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12877 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12878 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12879 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12880 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
12881 }
12882
12883 // return true if any matching specializations were found
12884 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12885 const DeclAccessPair& CurAccessFunPair) {
12886 if (CXXMethodDecl *Method
12887 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
12888 // Skip non-static function templates when converting to pointer, and
12889 // static when converting to member pointer.
12890 bool CanConvertToFunctionPointer =
12891 Method->isStatic() || Method->isExplicitObjectMemberFunction();
12892 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12893 return false;
12894 }
12895 else if (TargetTypeIsNonStaticMemberFunction)
12896 return false;
12897
12898 // C++ [over.over]p2:
12899 // If the name is a function template, template argument deduction is
12900 // done (14.8.2.2), and if the argument deduction succeeds, the
12901 // resulting template argument list is used to generate a single
12902 // function template specialization, which is added to the set of
12903 // overloaded functions considered.
12904 FunctionDecl *Specialization = nullptr;
12905 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12906 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
12907 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
12908 Specialization, Info, /*IsAddressOfFunction*/ true);
12909 Result != TemplateDeductionResult::Success) {
12910 // Make a note of the failed deduction for diagnostics.
12911 FailedCandidates.addCandidate()
12912 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
12913 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
12914 return false;
12915 }
12916
12917 // Template argument deduction ensures that we have an exact match or
12918 // compatible pointer-to-function arguments that would be adjusted by ICS.
12919 // This function template specicalization works.
12920 assert(S.isSameOrCompatibleFunctionType(
12921 Context.getCanonicalType(Specialization->getType()),
12922 Context.getCanonicalType(TargetFunctionType)));
12923
12924 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
12925 return false;
12926
12927 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
12928 return true;
12929 }
12930
12931 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12932 const DeclAccessPair& CurAccessFunPair) {
12933 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
12934 // Skip non-static functions when converting to pointer, and static
12935 // when converting to member pointer.
12936 bool CanConvertToFunctionPointer =
12937 Method->isStatic() || Method->isExplicitObjectMemberFunction();
12938 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12939 return false;
12940 }
12941 else if (TargetTypeIsNonStaticMemberFunction)
12942 return false;
12943
12944 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
12945 if (S.getLangOpts().CUDA) {
12946 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12947 if (!(Caller && Caller->isImplicit()) &&
12948 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
12949 return false;
12950 }
12951 if (FunDecl->isMultiVersion()) {
12952 const auto *TA = FunDecl->getAttr<TargetAttr>();
12953 if (TA && !TA->isDefaultVersion())
12954 return false;
12955 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
12956 if (TVA && !TVA->isDefaultVersion())
12957 return false;
12958 }
12959
12960 // If any candidate has a placeholder return type, trigger its deduction
12961 // now.
12962 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
12963 Complain)) {
12964 HasComplained |= Complain;
12965 return false;
12966 }
12967
12968 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
12969 return false;
12970
12971 // If we're in C, we need to support types that aren't exactly identical.
12972 if (!S.getLangOpts().CPlusPlus ||
12973 candidateHasExactlyCorrectType(FD: FunDecl)) {
12974 Matches.push_back(Elt: std::make_pair(
12975 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
12976 FoundNonTemplateFunction = true;
12977 return true;
12978 }
12979 }
12980
12981 return false;
12982 }
12983
12984 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12985 bool Ret = false;
12986
12987 // If the overload expression doesn't have the form of a pointer to
12988 // member, don't try to convert it to a pointer-to-member type.
12989 if (IsInvalidFormOfPointerToMemberFunction())
12990 return false;
12991
12992 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12993 E = OvlExpr->decls_end();
12994 I != E; ++I) {
12995 // Look through any using declarations to find the underlying function.
12996 NamedDecl *Fn = (*I)->getUnderlyingDecl();
12997
12998 // C++ [over.over]p3:
12999 // Non-member functions and static member functions match
13000 // targets of type "pointer-to-function" or "reference-to-function."
13001 // Nonstatic member functions match targets of
13002 // type "pointer-to-member-function."
13003 // Note that according to DR 247, the containing class does not matter.
13004 if (FunctionTemplateDecl *FunctionTemplate
13005 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13006 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13007 Ret = true;
13008 }
13009 // If we have explicit template arguments supplied, skip non-templates.
13010 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13011 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13012 Ret = true;
13013 }
13014 assert(Ret || Matches.empty());
13015 return Ret;
13016 }
13017
13018 void EliminateAllExceptMostSpecializedTemplate() {
13019 // [...] and any given function template specialization F1 is
13020 // eliminated if the set contains a second function template
13021 // specialization whose function template is more specialized
13022 // than the function template of F1 according to the partial
13023 // ordering rules of 14.5.5.2.
13024
13025 // The algorithm specified above is quadratic. We instead use a
13026 // two-pass algorithm (similar to the one used to identify the
13027 // best viable function in an overload set) that identifies the
13028 // best function template (if it exists).
13029
13030 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13031 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13032 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
13033
13034 // TODO: It looks like FailedCandidates does not serve much purpose
13035 // here, since the no_viable diagnostic has index 0.
13036 UnresolvedSetIterator Result = S.getMostSpecialized(
13037 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
13038 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
13039 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
13040 << Matches[0].second->getDeclName(),
13041 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
13042 << (unsigned)oc_function << (unsigned)ocs_described_template,
13043 Complain, TargetType: TargetFunctionType);
13044
13045 if (Result != MatchesCopy.end()) {
13046 // Make it the first and only element
13047 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13048 Matches[0].second = cast<FunctionDecl>(Val: *Result);
13049 Matches.resize(N: 1);
13050 } else
13051 HasComplained |= Complain;
13052 }
13053
13054 void EliminateAllTemplateMatches() {
13055 // [...] any function template specializations in the set are
13056 // eliminated if the set also contains a non-template function, [...]
13057 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13058 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13059 ++I;
13060 else {
13061 Matches[I] = Matches[--N];
13062 Matches.resize(N);
13063 }
13064 }
13065 }
13066
13067 void EliminateSuboptimalCudaMatches() {
13068 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
13069 Matches);
13070 }
13071
13072public:
13073 void ComplainNoMatchesFound() const {
13074 assert(Matches.empty());
13075 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
13076 << OvlExpr->getName() << TargetFunctionType
13077 << OvlExpr->getSourceRange();
13078 if (FailedCandidates.empty())
13079 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
13080 /*TakingAddress=*/true);
13081 else {
13082 // We have some deduction failure messages. Use them to diagnose
13083 // the function templates, and diagnose the non-template candidates
13084 // normally.
13085 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13086 IEnd = OvlExpr->decls_end();
13087 I != IEnd; ++I)
13088 if (FunctionDecl *Fun =
13089 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
13090 if (!functionHasPassObjectSizeParams(FD: Fun))
13091 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
13092 /*TakingAddress=*/true);
13093 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
13094 }
13095 }
13096
13097 bool IsInvalidFormOfPointerToMemberFunction() const {
13098 return TargetTypeIsNonStaticMemberFunction &&
13099 !OvlExprInfo.HasFormOfMemberPointer;
13100 }
13101
13102 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13103 // TODO: Should we condition this on whether any functions might
13104 // have matched, or is it more appropriate to do that in callers?
13105 // TODO: a fixit wouldn't hurt.
13106 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
13107 << TargetType << OvlExpr->getSourceRange();
13108 }
13109
13110 bool IsStaticMemberFunctionFromBoundPointer() const {
13111 return StaticMemberFunctionFromBoundPointer;
13112 }
13113
13114 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13115 S.Diag(Loc: OvlExpr->getBeginLoc(),
13116 DiagID: diag::err_invalid_form_pointer_member_function)
13117 << OvlExpr->getSourceRange();
13118 }
13119
13120 void ComplainOfInvalidConversion() const {
13121 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
13122 << OvlExpr->getName() << TargetType;
13123 }
13124
13125 void ComplainMultipleMatchesFound() const {
13126 assert(Matches.size() > 1);
13127 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
13128 << OvlExpr->getName() << OvlExpr->getSourceRange();
13129 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
13130 /*TakingAddress=*/true);
13131 }
13132
13133 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13134
13135 int getNumMatches() const { return Matches.size(); }
13136
13137 FunctionDecl* getMatchingFunctionDecl() const {
13138 if (Matches.size() != 1) return nullptr;
13139 return Matches[0].second;
13140 }
13141
13142 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13143 if (Matches.size() != 1) return nullptr;
13144 return &Matches[0].first;
13145 }
13146};
13147}
13148
13149FunctionDecl *
13150Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13151 QualType TargetType,
13152 bool Complain,
13153 DeclAccessPair &FoundResult,
13154 bool *pHadMultipleCandidates) {
13155 assert(AddressOfExpr->getType() == Context.OverloadTy);
13156
13157 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13158 Complain);
13159 int NumMatches = Resolver.getNumMatches();
13160 FunctionDecl *Fn = nullptr;
13161 bool ShouldComplain = Complain && !Resolver.hasComplained();
13162 if (NumMatches == 0 && ShouldComplain) {
13163 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13164 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13165 else
13166 Resolver.ComplainNoMatchesFound();
13167 }
13168 else if (NumMatches > 1 && ShouldComplain)
13169 Resolver.ComplainMultipleMatchesFound();
13170 else if (NumMatches == 1) {
13171 Fn = Resolver.getMatchingFunctionDecl();
13172 assert(Fn);
13173 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13174 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
13175 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13176 if (Complain) {
13177 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13178 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13179 else
13180 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
13181 }
13182 }
13183
13184 if (pHadMultipleCandidates)
13185 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13186 return Fn;
13187}
13188
13189FunctionDecl *
13190Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13191 OverloadExpr::FindResult R = OverloadExpr::find(E);
13192 OverloadExpr *Ovl = R.Expression;
13193 bool IsResultAmbiguous = false;
13194 FunctionDecl *Result = nullptr;
13195 DeclAccessPair DAP;
13196 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13197
13198 // Return positive for better, negative for worse, 0 for equal preference.
13199 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13200 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13201 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
13202 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
13203 };
13204
13205 // Don't use the AddressOfResolver because we're specifically looking for
13206 // cases where we have one overload candidate that lacks
13207 // enable_if/pass_object_size/...
13208 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13209 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
13210 if (!FD)
13211 return nullptr;
13212
13213 if (!checkAddressOfFunctionIsAvailable(Function: FD))
13214 continue;
13215
13216 // If we found a better result, update Result.
13217 auto FoundBetter = [&]() {
13218 IsResultAmbiguous = false;
13219 DAP = I.getPair();
13220 Result = FD;
13221 };
13222
13223 // We have more than one result - see if it is more constrained than the
13224 // previous one.
13225 if (Result) {
13226 // Check CUDA preference first. If the candidates have differennt CUDA
13227 // preference, choose the one with higher CUDA preference. Otherwise,
13228 // choose the one with more constraints.
13229 if (getLangOpts().CUDA) {
13230 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13231 // FD has different preference than Result.
13232 if (PreferenceByCUDA != 0) {
13233 // FD is more preferable than Result.
13234 if (PreferenceByCUDA > 0)
13235 FoundBetter();
13236 continue;
13237 }
13238 }
13239 // FD has the same CUDA prefernece than Result. Continue check
13240 // constraints.
13241 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD1: FD, FD2: Result);
13242 if (MoreConstrained != FD) {
13243 if (!MoreConstrained) {
13244 IsResultAmbiguous = true;
13245 AmbiguousDecls.push_back(Elt: FD);
13246 }
13247 continue;
13248 }
13249 // FD is more constrained - replace Result with it.
13250 }
13251 FoundBetter();
13252 }
13253
13254 if (IsResultAmbiguous)
13255 return nullptr;
13256
13257 if (Result) {
13258 SmallVector<const Expr *, 1> ResultAC;
13259 // We skipped over some ambiguous declarations which might be ambiguous with
13260 // the selected result.
13261 for (FunctionDecl *Skipped : AmbiguousDecls) {
13262 // If skipped candidate has different CUDA preference than the result,
13263 // there is no ambiguity. Otherwise check whether they have different
13264 // constraints.
13265 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13266 continue;
13267 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
13268 return nullptr;
13269 }
13270 Pair = DAP;
13271 }
13272 return Result;
13273}
13274
13275bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
13276 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13277 Expr *E = SrcExpr.get();
13278 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13279
13280 DeclAccessPair DAP;
13281 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
13282 if (!Found || Found->isCPUDispatchMultiVersion() ||
13283 Found->isCPUSpecificMultiVersion())
13284 return false;
13285
13286 // Emitting multiple diagnostics for a function that is both inaccessible and
13287 // unavailable is consistent with our behavior elsewhere. So, always check
13288 // for both.
13289 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
13290 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
13291 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
13292 if (Res.isInvalid())
13293 return false;
13294 Expr *Fixed = Res.get();
13295 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13296 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
13297 else
13298 SrcExpr = Fixed;
13299 return true;
13300}
13301
13302FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
13303 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13304 TemplateSpecCandidateSet *FailedTSC) {
13305 // C++ [over.over]p1:
13306 // [...] [Note: any redundant set of parentheses surrounding the
13307 // overloaded function name is ignored (5.1). ]
13308 // C++ [over.over]p1:
13309 // [...] The overloaded function name can be preceded by the &
13310 // operator.
13311
13312 // If we didn't actually find any template-ids, we're done.
13313 if (!ovl->hasExplicitTemplateArgs())
13314 return nullptr;
13315
13316 TemplateArgumentListInfo ExplicitTemplateArgs;
13317 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
13318
13319 // Look through all of the overloaded functions, searching for one
13320 // whose type matches exactly.
13321 FunctionDecl *Matched = nullptr;
13322 for (UnresolvedSetIterator I = ovl->decls_begin(),
13323 E = ovl->decls_end(); I != E; ++I) {
13324 // C++0x [temp.arg.explicit]p3:
13325 // [...] In contexts where deduction is done and fails, or in contexts
13326 // where deduction is not done, if a template argument list is
13327 // specified and it, along with any default template arguments,
13328 // identifies a single function template specialization, then the
13329 // template-id is an lvalue for the function template specialization.
13330 FunctionTemplateDecl *FunctionTemplate
13331 = cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
13332
13333 // C++ [over.over]p2:
13334 // If the name is a function template, template argument deduction is
13335 // done (14.8.2.2), and if the argument deduction succeeds, the
13336 // resulting template argument list is used to generate a single
13337 // function template specialization, which is added to the set of
13338 // overloaded functions considered.
13339 FunctionDecl *Specialization = nullptr;
13340 TemplateDeductionInfo Info(ovl->getNameLoc());
13341 if (TemplateDeductionResult Result = DeduceTemplateArguments(
13342 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
13343 /*IsAddressOfFunction*/ true);
13344 Result != TemplateDeductionResult::Success) {
13345 // Make a note of the failed deduction for diagnostics.
13346 if (FailedTSC)
13347 FailedTSC->addCandidate().set(
13348 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
13349 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13350 continue;
13351 }
13352
13353 assert(Specialization && "no specialization and no error?");
13354
13355 // Multiple matches; we can't resolve to a single declaration.
13356 if (Matched) {
13357 if (Complain) {
13358 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
13359 << ovl->getName();
13360 NoteAllOverloadCandidates(OverloadedExpr: ovl);
13361 }
13362 return nullptr;
13363 }
13364
13365 Matched = Specialization;
13366 if (FoundResult) *FoundResult = I.getPair();
13367 }
13368
13369 if (Matched &&
13370 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
13371 return nullptr;
13372
13373 return Matched;
13374}
13375
13376bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
13377 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13378 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13379 unsigned DiagIDForComplaining) {
13380 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13381
13382 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
13383
13384 DeclAccessPair found;
13385 ExprResult SingleFunctionExpression;
13386 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13387 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
13388 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
13389 SrcExpr = ExprError();
13390 return true;
13391 }
13392
13393 // It is only correct to resolve to an instance method if we're
13394 // resolving a form that's permitted to be a pointer to member.
13395 // Otherwise we'll end up making a bound member expression, which
13396 // is illegal in all the contexts we resolve like this.
13397 if (!ovl.HasFormOfMemberPointer &&
13398 isa<CXXMethodDecl>(Val: fn) &&
13399 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
13400 if (!complain) return false;
13401
13402 Diag(Loc: ovl.Expression->getExprLoc(),
13403 DiagID: diag::err_bound_member_function)
13404 << 0 << ovl.Expression->getSourceRange();
13405
13406 // TODO: I believe we only end up here if there's a mix of
13407 // static and non-static candidates (otherwise the expression
13408 // would have 'bound member' type, not 'overload' type).
13409 // Ideally we would note which candidate was chosen and why
13410 // the static candidates were rejected.
13411 SrcExpr = ExprError();
13412 return true;
13413 }
13414
13415 // Fix the expression to refer to 'fn'.
13416 SingleFunctionExpression =
13417 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
13418
13419 // If desired, do function-to-pointer decay.
13420 if (doFunctionPointerConversion) {
13421 SingleFunctionExpression =
13422 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
13423 if (SingleFunctionExpression.isInvalid()) {
13424 SrcExpr = ExprError();
13425 return true;
13426 }
13427 }
13428 }
13429
13430 if (!SingleFunctionExpression.isUsable()) {
13431 if (complain) {
13432 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
13433 << ovl.Expression->getName()
13434 << DestTypeForComplaining
13435 << OpRangeForComplaining
13436 << ovl.Expression->getQualifierLoc().getSourceRange();
13437 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
13438
13439 SrcExpr = ExprError();
13440 return true;
13441 }
13442
13443 return false;
13444 }
13445
13446 SrcExpr = SingleFunctionExpression;
13447 return true;
13448}
13449
13450/// Add a single candidate to the overload set.
13451static void AddOverloadedCallCandidate(Sema &S,
13452 DeclAccessPair FoundDecl,
13453 TemplateArgumentListInfo *ExplicitTemplateArgs,
13454 ArrayRef<Expr *> Args,
13455 OverloadCandidateSet &CandidateSet,
13456 bool PartialOverloading,
13457 bool KnownValid) {
13458 NamedDecl *Callee = FoundDecl.getDecl();
13459 if (isa<UsingShadowDecl>(Val: Callee))
13460 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
13461
13462 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
13463 if (ExplicitTemplateArgs) {
13464 assert(!KnownValid && "Explicit template arguments?");
13465 return;
13466 }
13467 // Prevent ill-formed function decls to be added as overload candidates.
13468 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
13469 return;
13470
13471 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
13472 /*SuppressUserConversions=*/false,
13473 PartialOverloading);
13474 return;
13475 }
13476
13477 if (FunctionTemplateDecl *FuncTemplate
13478 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
13479 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
13480 ExplicitTemplateArgs, Args, CandidateSet,
13481 /*SuppressUserConversions=*/false,
13482 PartialOverloading);
13483 return;
13484 }
13485
13486 assert(!KnownValid && "unhandled case in overloaded call candidate");
13487}
13488
13489void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
13490 ArrayRef<Expr *> Args,
13491 OverloadCandidateSet &CandidateSet,
13492 bool PartialOverloading) {
13493
13494#ifndef NDEBUG
13495 // Verify that ArgumentDependentLookup is consistent with the rules
13496 // in C++0x [basic.lookup.argdep]p3:
13497 //
13498 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13499 // and let Y be the lookup set produced by argument dependent
13500 // lookup (defined as follows). If X contains
13501 //
13502 // -- a declaration of a class member, or
13503 //
13504 // -- a block-scope function declaration that is not a
13505 // using-declaration, or
13506 //
13507 // -- a declaration that is neither a function or a function
13508 // template
13509 //
13510 // then Y is empty.
13511
13512 if (ULE->requiresADL()) {
13513 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13514 E = ULE->decls_end(); I != E; ++I) {
13515 assert(!(*I)->getDeclContext()->isRecord());
13516 assert(isa<UsingShadowDecl>(*I) ||
13517 !(*I)->getDeclContext()->isFunctionOrMethod());
13518 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13519 }
13520 }
13521#endif
13522
13523 // It would be nice to avoid this copy.
13524 TemplateArgumentListInfo TABuffer;
13525 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13526 if (ULE->hasExplicitTemplateArgs()) {
13527 ULE->copyTemplateArgumentsInto(List&: TABuffer);
13528 ExplicitTemplateArgs = &TABuffer;
13529 }
13530
13531 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13532 E = ULE->decls_end(); I != E; ++I)
13533 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
13534 CandidateSet, PartialOverloading,
13535 /*KnownValid*/ true);
13536
13537 if (ULE->requiresADL())
13538 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
13539 Args, ExplicitTemplateArgs,
13540 CandidateSet, PartialOverloading);
13541}
13542
13543void Sema::AddOverloadedCallCandidates(
13544 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13545 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13546 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13547 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
13548 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
13549}
13550
13551/// Determine whether a declaration with the specified name could be moved into
13552/// a different namespace.
13553static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13554 switch (Name.getCXXOverloadedOperator()) {
13555 case OO_New: case OO_Array_New:
13556 case OO_Delete: case OO_Array_Delete:
13557 return false;
13558
13559 default:
13560 return true;
13561 }
13562}
13563
13564/// Attempt to recover from an ill-formed use of a non-dependent name in a
13565/// template, where the non-dependent name was declared after the template
13566/// was defined. This is common in code written for a compilers which do not
13567/// correctly implement two-stage name lookup.
13568///
13569/// Returns true if a viable candidate was found and a diagnostic was issued.
13570static bool DiagnoseTwoPhaseLookup(
13571 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13572 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
13573 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13574 CXXRecordDecl **FoundInClass = nullptr) {
13575 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13576 return false;
13577
13578 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13579 if (DC->isTransparentContext())
13580 continue;
13581
13582 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
13583
13584 if (!R.empty()) {
13585 R.suppressDiagnostics();
13586
13587 OverloadCandidateSet Candidates(FnLoc, CSK);
13588 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13589 CandidateSet&: Candidates);
13590
13591 OverloadCandidateSet::iterator Best;
13592 OverloadingResult OR =
13593 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
13594
13595 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
13596 // We either found non-function declarations or a best viable function
13597 // at class scope. A class-scope lookup result disables ADL. Don't
13598 // look past this, but let the caller know that we found something that
13599 // either is, or might be, usable in this class.
13600 if (FoundInClass) {
13601 *FoundInClass = RD;
13602 if (OR == OR_Success) {
13603 R.clear();
13604 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
13605 R.resolveKind();
13606 }
13607 }
13608 return false;
13609 }
13610
13611 if (OR != OR_Success) {
13612 // There wasn't a unique best function or function template.
13613 return false;
13614 }
13615
13616 // Find the namespaces where ADL would have looked, and suggest
13617 // declaring the function there instead.
13618 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13619 Sema::AssociatedClassSet AssociatedClasses;
13620 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
13621 AssociatedNamespaces,
13622 AssociatedClasses);
13623 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13624 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
13625 DeclContext *Std = SemaRef.getStdNamespace();
13626 for (Sema::AssociatedNamespaceSet::iterator
13627 it = AssociatedNamespaces.begin(),
13628 end = AssociatedNamespaces.end(); it != end; ++it) {
13629 // Never suggest declaring a function within namespace 'std'.
13630 if (Std && Std->Encloses(DC: *it))
13631 continue;
13632
13633 // Never suggest declaring a function within a namespace with a
13634 // reserved name, like __gnu_cxx.
13635 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
13636 if (NS &&
13637 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
13638 continue;
13639
13640 SuggestedNamespaces.insert(X: *it);
13641 }
13642 }
13643
13644 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
13645 << R.getLookupName();
13646 if (SuggestedNamespaces.empty()) {
13647 SemaRef.Diag(Loc: Best->Function->getLocation(),
13648 DiagID: diag::note_not_found_by_two_phase_lookup)
13649 << R.getLookupName() << 0;
13650 } else if (SuggestedNamespaces.size() == 1) {
13651 SemaRef.Diag(Loc: Best->Function->getLocation(),
13652 DiagID: diag::note_not_found_by_two_phase_lookup)
13653 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13654 } else {
13655 // FIXME: It would be useful to list the associated namespaces here,
13656 // but the diagnostics infrastructure doesn't provide a way to produce
13657 // a localized representation of a list of items.
13658 SemaRef.Diag(Loc: Best->Function->getLocation(),
13659 DiagID: diag::note_not_found_by_two_phase_lookup)
13660 << R.getLookupName() << 2;
13661 }
13662
13663 // Try to recover by calling this function.
13664 return true;
13665 }
13666
13667 R.clear();
13668 }
13669
13670 return false;
13671}
13672
13673/// Attempt to recover from ill-formed use of a non-dependent operator in a
13674/// template, where the non-dependent operator was declared after the template
13675/// was defined.
13676///
13677/// Returns true if a viable candidate was found and a diagnostic was issued.
13678static bool
13679DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13680 SourceLocation OpLoc,
13681 ArrayRef<Expr *> Args) {
13682 DeclarationName OpName =
13683 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13684 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13685 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
13686 CSK: OverloadCandidateSet::CSK_Operator,
13687 /*ExplicitTemplateArgs=*/nullptr, Args);
13688}
13689
13690namespace {
13691class BuildRecoveryCallExprRAII {
13692 Sema &SemaRef;
13693 Sema::SatisfactionStackResetRAII SatStack;
13694
13695public:
13696 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13697 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13698 SemaRef.IsBuildingRecoveryCallExpr = true;
13699 }
13700
13701 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13702};
13703}
13704
13705/// Attempts to recover from a call where no functions were found.
13706///
13707/// This function will do one of three things:
13708/// * Diagnose, recover, and return a recovery expression.
13709/// * Diagnose, fail to recover, and return ExprError().
13710/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13711/// expected to diagnose as appropriate.
13712static ExprResult
13713BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13714 UnresolvedLookupExpr *ULE,
13715 SourceLocation LParenLoc,
13716 MutableArrayRef<Expr *> Args,
13717 SourceLocation RParenLoc,
13718 bool EmptyLookup, bool AllowTypoCorrection) {
13719 // Do not try to recover if it is already building a recovery call.
13720 // This stops infinite loops for template instantiations like
13721 //
13722 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13723 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13724 if (SemaRef.IsBuildingRecoveryCallExpr)
13725 return ExprResult();
13726 BuildRecoveryCallExprRAII RCE(SemaRef);
13727
13728 CXXScopeSpec SS;
13729 SS.Adopt(Other: ULE->getQualifierLoc());
13730 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13731
13732 TemplateArgumentListInfo TABuffer;
13733 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13734 if (ULE->hasExplicitTemplateArgs()) {
13735 ULE->copyTemplateArgumentsInto(List&: TABuffer);
13736 ExplicitTemplateArgs = &TABuffer;
13737 }
13738
13739 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13740 Sema::LookupOrdinaryName);
13741 CXXRecordDecl *FoundInClass = nullptr;
13742 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
13743 CSK: OverloadCandidateSet::CSK_Normal,
13744 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
13745 // OK, diagnosed a two-phase lookup issue.
13746 } else if (EmptyLookup) {
13747 // Try to recover from an empty lookup with typo correction.
13748 R.clear();
13749 NoTypoCorrectionCCC NoTypoValidator{};
13750 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13751 ExplicitTemplateArgs != nullptr,
13752 dyn_cast<MemberExpr>(Val: Fn));
13753 CorrectionCandidateCallback &Validator =
13754 AllowTypoCorrection
13755 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13756 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13757 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
13758 Args))
13759 return ExprError();
13760 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13761 // We found a usable declaration of the name in a dependent base of some
13762 // enclosing class.
13763 // FIXME: We should also explain why the candidates found by name lookup
13764 // were not viable.
13765 if (SemaRef.DiagnoseDependentMemberLookup(R))
13766 return ExprError();
13767 } else {
13768 // We had viable candidates and couldn't recover; let the caller diagnose
13769 // this.
13770 return ExprResult();
13771 }
13772
13773 // If we get here, we should have issued a diagnostic and formed a recovery
13774 // lookup result.
13775 assert(!R.empty() && "lookup results empty despite recovery");
13776
13777 // If recovery created an ambiguity, just bail out.
13778 if (R.isAmbiguous()) {
13779 R.suppressDiagnostics();
13780 return ExprError();
13781 }
13782
13783 // Build an implicit member call if appropriate. Just drop the
13784 // casts and such from the call, we don't really care.
13785 ExprResult NewFn = ExprError();
13786 if ((*R.begin())->isCXXClassMember())
13787 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13788 TemplateArgs: ExplicitTemplateArgs, S);
13789 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13790 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
13791 TemplateArgs: ExplicitTemplateArgs);
13792 else
13793 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
13794
13795 if (NewFn.isInvalid())
13796 return ExprError();
13797
13798 // This shouldn't cause an infinite loop because we're giving it
13799 // an expression with viable lookup results, which should never
13800 // end up here.
13801 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
13802 ArgExprs: MultiExprArg(Args.data(), Args.size()),
13803 RParenLoc);
13804}
13805
13806bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13807 UnresolvedLookupExpr *ULE,
13808 MultiExprArg Args,
13809 SourceLocation RParenLoc,
13810 OverloadCandidateSet *CandidateSet,
13811 ExprResult *Result) {
13812#ifndef NDEBUG
13813 if (ULE->requiresADL()) {
13814 // To do ADL, we must have found an unqualified name.
13815 assert(!ULE->getQualifier() && "qualified name with ADL");
13816
13817 // We don't perform ADL for implicit declarations of builtins.
13818 // Verify that this was correctly set up.
13819 FunctionDecl *F;
13820 if (ULE->decls_begin() != ULE->decls_end() &&
13821 ULE->decls_begin() + 1 == ULE->decls_end() &&
13822 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13823 F->getBuiltinID() && F->isImplicit())
13824 llvm_unreachable("performing ADL for builtin");
13825
13826 // We don't perform ADL in C.
13827 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13828 }
13829#endif
13830
13831 UnbridgedCastsSet UnbridgedCasts;
13832 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
13833 *Result = ExprError();
13834 return true;
13835 }
13836
13837 // Add the functions denoted by the callee to the set of candidate
13838 // functions, including those from argument-dependent lookup.
13839 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
13840
13841 if (getLangOpts().MSVCCompat &&
13842 CurContext->isDependentContext() && !isSFINAEContext() &&
13843 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
13844
13845 OverloadCandidateSet::iterator Best;
13846 if (CandidateSet->empty() ||
13847 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
13848 OR_No_Viable_Function) {
13849 // In Microsoft mode, if we are inside a template class member function
13850 // then create a type dependent CallExpr. The goal is to postpone name
13851 // lookup to instantiation time to be able to search into type dependent
13852 // base classes.
13853 CallExpr *CE =
13854 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
13855 RParenLoc, FPFeatures: CurFPFeatureOverrides());
13856 CE->markDependentForPostponedNameLookup();
13857 *Result = CE;
13858 return true;
13859 }
13860 }
13861
13862 if (CandidateSet->empty())
13863 return false;
13864
13865 UnbridgedCasts.restore();
13866 return false;
13867}
13868
13869// Guess at what the return type for an unresolvable overload should be.
13870static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13871 OverloadCandidateSet::iterator *Best) {
13872 std::optional<QualType> Result;
13873 // Adjust Type after seeing a candidate.
13874 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13875 if (!Candidate.Function)
13876 return;
13877 if (Candidate.Function->isInvalidDecl())
13878 return;
13879 QualType T = Candidate.Function->getReturnType();
13880 if (T.isNull())
13881 return;
13882 if (!Result)
13883 Result = T;
13884 else if (Result != T)
13885 Result = QualType();
13886 };
13887
13888 // Look for an unambiguous type from a progressively larger subset.
13889 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13890 //
13891 // First, consider only the best candidate.
13892 if (Best && *Best != CS.end())
13893 ConsiderCandidate(**Best);
13894 // Next, consider only viable candidates.
13895 if (!Result)
13896 for (const auto &C : CS)
13897 if (C.Viable)
13898 ConsiderCandidate(C);
13899 // Finally, consider all candidates.
13900 if (!Result)
13901 for (const auto &C : CS)
13902 ConsiderCandidate(C);
13903
13904 if (!Result)
13905 return QualType();
13906 auto Value = *Result;
13907 if (Value.isNull() || Value->isUndeducedType())
13908 return QualType();
13909 return Value;
13910}
13911
13912/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13913/// the completed call expression. If overload resolution fails, emits
13914/// diagnostics and returns ExprError()
13915static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13916 UnresolvedLookupExpr *ULE,
13917 SourceLocation LParenLoc,
13918 MultiExprArg Args,
13919 SourceLocation RParenLoc,
13920 Expr *ExecConfig,
13921 OverloadCandidateSet *CandidateSet,
13922 OverloadCandidateSet::iterator *Best,
13923 OverloadingResult OverloadResult,
13924 bool AllowTypoCorrection) {
13925 switch (OverloadResult) {
13926 case OR_Success: {
13927 FunctionDecl *FDecl = (*Best)->Function;
13928 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
13929 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
13930 return ExprError();
13931 ExprResult Res =
13932 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
13933 if (Res.isInvalid())
13934 return ExprError();
13935 return SemaRef.BuildResolvedCallExpr(
13936 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
13937 /*IsExecConfig=*/false, UsesADL: (*Best)->IsADLCandidate);
13938 }
13939
13940 case OR_No_Viable_Function: {
13941 if (*Best != CandidateSet->end() &&
13942 CandidateSet->getKind() ==
13943 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
13944 if (CXXMethodDecl *M =
13945 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
13946 M && M->isImplicitObjectMemberFunction()) {
13947 CandidateSet->NoteCandidates(
13948 PD: PartialDiagnosticAt(
13949 Fn->getBeginLoc(),
13950 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
13951 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
13952 return ExprError();
13953 }
13954 }
13955
13956 // Try to recover by looking for viable functions which the user might
13957 // have meant to call.
13958 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13959 Args, RParenLoc,
13960 EmptyLookup: CandidateSet->empty(),
13961 AllowTypoCorrection);
13962 if (Recovery.isInvalid() || Recovery.isUsable())
13963 return Recovery;
13964
13965 // If the user passes in a function that we can't take the address of, we
13966 // generally end up emitting really bad error messages. Here, we attempt to
13967 // emit better ones.
13968 for (const Expr *Arg : Args) {
13969 if (!Arg->getType()->isFunctionType())
13970 continue;
13971 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
13972 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
13973 if (FD &&
13974 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
13975 Loc: Arg->getExprLoc()))
13976 return ExprError();
13977 }
13978 }
13979
13980 CandidateSet->NoteCandidates(
13981 PD: PartialDiagnosticAt(
13982 Fn->getBeginLoc(),
13983 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
13984 << ULE->getName() << Fn->getSourceRange()),
13985 S&: SemaRef, OCD: OCD_AllCandidates, Args);
13986 break;
13987 }
13988
13989 case OR_Ambiguous:
13990 CandidateSet->NoteCandidates(
13991 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
13992 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
13993 << ULE->getName() << Fn->getSourceRange()),
13994 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
13995 break;
13996
13997 case OR_Deleted: {
13998 FunctionDecl *FDecl = (*Best)->Function;
13999 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
14000 Range: Fn->getSourceRange(), Name: ULE->getName(),
14001 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
14002
14003 // We emitted an error for the unavailable/deleted function call but keep
14004 // the call in the AST.
14005 ExprResult Res =
14006 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14007 if (Res.isInvalid())
14008 return ExprError();
14009 return SemaRef.BuildResolvedCallExpr(
14010 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14011 /*IsExecConfig=*/false, UsesADL: (*Best)->IsADLCandidate);
14012 }
14013 }
14014
14015 // Overload resolution failed, try to recover.
14016 SmallVector<Expr *, 8> SubExprs = {Fn};
14017 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
14018 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
14019 T: chooseRecoveryType(CS&: *CandidateSet, Best));
14020}
14021
14022static void markUnaddressableCandidatesUnviable(Sema &S,
14023 OverloadCandidateSet &CS) {
14024 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14025 if (I->Viable &&
14026 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
14027 I->Viable = false;
14028 I->FailureKind = ovl_fail_addr_not_available;
14029 }
14030 }
14031}
14032
14033ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14034 UnresolvedLookupExpr *ULE,
14035 SourceLocation LParenLoc,
14036 MultiExprArg Args,
14037 SourceLocation RParenLoc,
14038 Expr *ExecConfig,
14039 bool AllowTypoCorrection,
14040 bool CalleesAddressIsTaken) {
14041 OverloadCandidateSet CandidateSet(
14042 Fn->getExprLoc(), CalleesAddressIsTaken
14043 ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14044 : OverloadCandidateSet::CSK_Normal);
14045 ExprResult result;
14046
14047 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
14048 Result: &result))
14049 return result;
14050
14051 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14052 // functions that aren't addressible are considered unviable.
14053 if (CalleesAddressIsTaken)
14054 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
14055
14056 OverloadCandidateSet::iterator Best;
14057 OverloadingResult OverloadResult =
14058 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
14059
14060 // Model the case with a call to a templated function whose definition
14061 // encloses the call and whose return type contains a placeholder type as if
14062 // the UnresolvedLookupExpr was type-dependent.
14063 if (OverloadResult == OR_Success) {
14064 const FunctionDecl *FDecl = Best->Function;
14065 if (FDecl && FDecl->isTemplateInstantiation() &&
14066 FDecl->getReturnType()->isUndeducedType()) {
14067 if (const auto *TP =
14068 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14069 TP && TP->willHaveBody()) {
14070 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
14071 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
14072 }
14073 }
14074 }
14075
14076 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14077 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
14078 OverloadResult, AllowTypoCorrection);
14079}
14080
14081ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14082 NestedNameSpecifierLoc NNSLoc,
14083 DeclarationNameInfo DNI,
14084 const UnresolvedSetImpl &Fns,
14085 bool PerformADL) {
14086 return UnresolvedLookupExpr::Create(
14087 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
14088 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14089}
14090
14091ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14092 CXXConversionDecl *Method,
14093 bool HadMultipleCandidates) {
14094 // Convert the expression to match the conversion function's implicit object
14095 // parameter.
14096 ExprResult Exp;
14097 if (Method->isExplicitObjectMemberFunction())
14098 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
14099 else
14100 Exp = PerformImplicitObjectArgumentInitialization(From: E, /*Qualifier=*/nullptr,
14101 FoundDecl, Method);
14102 if (Exp.isInvalid())
14103 return true;
14104
14105 if (Method->getParent()->isLambda() &&
14106 Method->getConversionType()->isBlockPointerType()) {
14107 // This is a lambda conversion to block pointer; check if the argument
14108 // was a LambdaExpr.
14109 Expr *SubE = E;
14110 auto *CE = dyn_cast<CastExpr>(Val: SubE);
14111 if (CE && CE->getCastKind() == CK_NoOp)
14112 SubE = CE->getSubExpr();
14113 SubE = SubE->IgnoreParens();
14114 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
14115 SubE = BE->getSubExpr();
14116 if (isa<LambdaExpr>(Val: SubE)) {
14117 // For the conversion to block pointer on a lambda expression, we
14118 // construct a special BlockLiteral instead; this doesn't really make
14119 // a difference in ARC, but outside of ARC the resulting block literal
14120 // follows the normal lifetime rules for block literals instead of being
14121 // autoreleased.
14122 PushExpressionEvaluationContext(
14123 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
14124 ExprResult BlockExp = BuildBlockForLambdaConversion(
14125 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
14126 PopExpressionEvaluationContext();
14127
14128 // FIXME: This note should be produced by a CodeSynthesisContext.
14129 if (BlockExp.isInvalid())
14130 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
14131 return BlockExp;
14132 }
14133 }
14134 CallExpr *CE;
14135 QualType ResultType = Method->getReturnType();
14136 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
14137 ResultType = ResultType.getNonLValueExprType(Context);
14138 if (Method->isExplicitObjectMemberFunction()) {
14139 ExprResult FnExpr =
14140 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
14141 HadMultipleCandidates, Loc: E->getBeginLoc());
14142 if (FnExpr.isInvalid())
14143 return ExprError();
14144 Expr *ObjectParam = Exp.get();
14145 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
14146 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
14147 FPFeatures: CurFPFeatureOverrides());
14148 } else {
14149 MemberExpr *ME =
14150 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
14151 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
14152 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
14153 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
14154 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
14155
14156 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
14157 RP: Exp.get()->getEndLoc(),
14158 FPFeatures: CurFPFeatureOverrides());
14159 }
14160
14161 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
14162 Proto: Method->getType()->castAs<FunctionProtoType>()))
14163 return ExprError();
14164
14165 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
14166}
14167
14168ExprResult
14169Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
14170 const UnresolvedSetImpl &Fns,
14171 Expr *Input, bool PerformADL) {
14172 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
14173 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14174 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14175 // TODO: provide better source location info.
14176 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14177
14178 if (checkPlaceholderForOverload(S&: *this, E&: Input))
14179 return ExprError();
14180
14181 Expr *Args[2] = { Input, nullptr };
14182 unsigned NumArgs = 1;
14183
14184 // For post-increment and post-decrement, add the implicit '0' as
14185 // the second argument, so that we know this is a post-increment or
14186 // post-decrement.
14187 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14188 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
14189 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
14190 l: SourceLocation());
14191 NumArgs = 2;
14192 }
14193
14194 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14195
14196 if (Input->isTypeDependent()) {
14197 ExprValueKind VK = ExprValueKind::VK_PRValue;
14198 // [C++26][expr.unary.op][expr.pre.incr]
14199 // The * operator yields an lvalue of type
14200 // The pre/post increment operators yied an lvalue.
14201 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14202 VK = VK_LValue;
14203
14204 if (Fns.empty())
14205 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
14206 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
14207 FPFeatures: CurFPFeatureOverrides());
14208
14209 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14210 ExprResult Fn = CreateUnresolvedLookupExpr(
14211 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
14212 if (Fn.isInvalid())
14213 return ExprError();
14214 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
14215 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
14216 FPFeatures: CurFPFeatureOverrides());
14217 }
14218
14219 // Build an empty overload set.
14220 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
14221
14222 // Add the candidates from the given function set.
14223 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
14224
14225 // Add operator candidates that are member functions.
14226 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
14227
14228 // Add candidates from ADL.
14229 if (PerformADL) {
14230 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
14231 /*ExplicitTemplateArgs*/nullptr,
14232 CandidateSet);
14233 }
14234
14235 // Add builtin operator candidates.
14236 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
14237
14238 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14239
14240 // Perform overload resolution.
14241 OverloadCandidateSet::iterator Best;
14242 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
14243 case OR_Success: {
14244 // We found a built-in operator or an overloaded operator.
14245 FunctionDecl *FnDecl = Best->Function;
14246
14247 if (FnDecl) {
14248 Expr *Base = nullptr;
14249 // We matched an overloaded operator. Build a call to that
14250 // operator.
14251
14252 // Convert the arguments.
14253 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
14254 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
14255
14256 ExprResult InputInit;
14257 if (Method->isExplicitObjectMemberFunction())
14258 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
14259 else
14260 InputInit = PerformImplicitObjectArgumentInitialization(
14261 From: Input, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
14262 if (InputInit.isInvalid())
14263 return ExprError();
14264 Base = Input = InputInit.get();
14265 } else {
14266 // Convert the arguments.
14267 ExprResult InputInit
14268 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
14269 Context,
14270 Parm: FnDecl->getParamDecl(i: 0)),
14271 EqualLoc: SourceLocation(),
14272 Init: Input);
14273 if (InputInit.isInvalid())
14274 return ExprError();
14275 Input = InputInit.get();
14276 }
14277
14278 // Build the actual expression node.
14279 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
14280 Base, HadMultipleCandidates,
14281 Loc: OpLoc);
14282 if (FnExpr.isInvalid())
14283 return ExprError();
14284
14285 // Determine the result type.
14286 QualType ResultTy = FnDecl->getReturnType();
14287 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
14288 ResultTy = ResultTy.getNonLValueExprType(Context);
14289
14290 Args[0] = Input;
14291 CallExpr *TheCall = CXXOperatorCallExpr::Create(
14292 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
14293 FPFeatures: CurFPFeatureOverrides(), UsesADL: Best->IsADLCandidate);
14294
14295 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
14296 return ExprError();
14297
14298 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
14299 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
14300 return ExprError();
14301 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
14302 } else {
14303 // We matched a built-in operator. Convert the arguments, then
14304 // break out so that we will build the appropriate built-in
14305 // operator node.
14306 ExprResult InputRes = PerformImplicitConversion(
14307 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0], Action: AA_Passing,
14308 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
14309 if (InputRes.isInvalid())
14310 return ExprError();
14311 Input = InputRes.get();
14312 break;
14313 }
14314 }
14315
14316 case OR_No_Viable_Function:
14317 // This is an erroneous use of an operator which can be overloaded by
14318 // a non-member function. Check for non-member operators which were
14319 // defined too late to be candidates.
14320 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
14321 // FIXME: Recover by calling the found function.
14322 return ExprError();
14323
14324 // No viable function; fall through to handling this as a
14325 // built-in operator, which will produce an error message for us.
14326 break;
14327
14328 case OR_Ambiguous:
14329 CandidateSet.NoteCandidates(
14330 PD: PartialDiagnosticAt(OpLoc,
14331 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
14332 << UnaryOperator::getOpcodeStr(Op: Opc)
14333 << Input->getType() << Input->getSourceRange()),
14334 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
14335 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
14336 return ExprError();
14337
14338 case OR_Deleted: {
14339 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14340 // object whose method was called. Later in NoteCandidates size of ArgsArray
14341 // is passed further and it eventually ends up compared to number of
14342 // function candidate parameters which never includes the object parameter,
14343 // so slice ArgsArray to make sure apples are compared to apples.
14344 StringLiteral *Msg = Best->Function->getDeletedMessage();
14345 CandidateSet.NoteCandidates(
14346 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
14347 << UnaryOperator::getOpcodeStr(Op: Opc)
14348 << (Msg != nullptr)
14349 << (Msg ? Msg->getString() : StringRef())
14350 << Input->getSourceRange()),
14351 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
14352 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
14353 return ExprError();
14354 }
14355 }
14356
14357 // Either we found no viable overloaded operator or we matched a
14358 // built-in operator. In either case, fall through to trying to
14359 // build a built-in operation.
14360 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
14361}
14362
14363void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
14364 OverloadedOperatorKind Op,
14365 const UnresolvedSetImpl &Fns,
14366 ArrayRef<Expr *> Args, bool PerformADL) {
14367 SourceLocation OpLoc = CandidateSet.getLocation();
14368
14369 OverloadedOperatorKind ExtraOp =
14370 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
14371 ? getRewrittenOverloadedOperator(Kind: Op)
14372 : OO_None;
14373
14374 // Add the candidates from the given function set. This also adds the
14375 // rewritten candidates using these functions if necessary.
14376 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14377
14378 // Add operator candidates that are member functions.
14379 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14380 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14381 AddMemberOperatorCandidates(Op, OpLoc, Args: {Args[1], Args[0]}, CandidateSet,
14382 PO: OverloadCandidateParamOrder::Reversed);
14383
14384 // In C++20, also add any rewritten member candidates.
14385 if (ExtraOp) {
14386 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
14387 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
14388 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: {Args[1], Args[0]},
14389 CandidateSet,
14390 PO: OverloadCandidateParamOrder::Reversed);
14391 }
14392
14393 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14394 // performed for an assignment operator (nor for operator[] nor operator->,
14395 // which don't get here).
14396 if (Op != OO_Equal && PerformADL) {
14397 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14398 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
14399 /*ExplicitTemplateArgs*/ nullptr,
14400 CandidateSet);
14401 if (ExtraOp) {
14402 DeclarationName ExtraOpName =
14403 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
14404 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
14405 /*ExplicitTemplateArgs*/ nullptr,
14406 CandidateSet);
14407 }
14408 }
14409
14410 // Add builtin operator candidates.
14411 //
14412 // FIXME: We don't add any rewritten candidates here. This is strictly
14413 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14414 // resulting in our selecting a rewritten builtin candidate. For example:
14415 //
14416 // enum class E { e };
14417 // bool operator!=(E, E) requires false;
14418 // bool k = E::e != E::e;
14419 //
14420 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14421 // it seems unreasonable to consider rewritten builtin candidates. A core
14422 // issue has been filed proposing to removed this requirement.
14423 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14424}
14425
14426ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
14427 BinaryOperatorKind Opc,
14428 const UnresolvedSetImpl &Fns, Expr *LHS,
14429 Expr *RHS, bool PerformADL,
14430 bool AllowRewrittenCandidates,
14431 FunctionDecl *DefaultedFn) {
14432 Expr *Args[2] = { LHS, RHS };
14433 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14434
14435 if (!getLangOpts().CPlusPlus20)
14436 AllowRewrittenCandidates = false;
14437
14438 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
14439
14440 // If either side is type-dependent, create an appropriate dependent
14441 // expression.
14442 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14443 if (Fns.empty()) {
14444 // If there are no functions to store, just build a dependent
14445 // BinaryOperator or CompoundAssignment.
14446 if (BinaryOperator::isCompoundAssignmentOp(Opc))
14447 return CompoundAssignOperator::Create(
14448 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
14449 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
14450 CompResultType: Context.DependentTy);
14451 return BinaryOperator::Create(
14452 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
14453 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
14454 }
14455
14456 // FIXME: save results of ADL from here?
14457 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14458 // TODO: provide better source location info in DNLoc component.
14459 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14460 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14461 ExprResult Fn = CreateUnresolvedLookupExpr(
14462 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
14463 if (Fn.isInvalid())
14464 return ExprError();
14465 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
14466 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
14467 FPFeatures: CurFPFeatureOverrides());
14468 }
14469
14470 // If this is the .* operator, which is not overloadable, just
14471 // create a built-in binary operator.
14472 if (Opc == BO_PtrMemD) {
14473 auto CheckPlaceholder = [&](Expr *&Arg) {
14474 ExprResult Res = CheckPlaceholderExpr(E: Arg);
14475 if (Res.isUsable())
14476 Arg = Res.get();
14477 return !Res.isUsable();
14478 };
14479
14480 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14481 // expression that contains placeholders (in either the LHS or RHS).
14482 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14483 return ExprError();
14484 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
14485 }
14486
14487 // Always do placeholder-like conversions on the RHS.
14488 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
14489 return ExprError();
14490
14491 // Do placeholder-like conversion on the LHS; note that we should
14492 // not get here with a PseudoObject LHS.
14493 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14494 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
14495 return ExprError();
14496
14497 // If this is the assignment operator, we only perform overload resolution
14498 // if the left-hand side is a class or enumeration type. This is actually
14499 // a hack. The standard requires that we do overload resolution between the
14500 // various built-in candidates, but as DR507 points out, this can lead to
14501 // problems. So we do it this way, which pretty much follows what GCC does.
14502 // Note that we go the traditional code path for compound assignment forms.
14503 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14504 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
14505
14506 // Build the overload set.
14507 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
14508 OverloadCandidateSet::OperatorRewriteInfo(
14509 Op, OpLoc, AllowRewrittenCandidates));
14510 if (DefaultedFn)
14511 CandidateSet.exclude(F: DefaultedFn);
14512 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14513
14514 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14515
14516 // Perform overload resolution.
14517 OverloadCandidateSet::iterator Best;
14518 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
14519 case OR_Success: {
14520 // We found a built-in operator or an overloaded operator.
14521 FunctionDecl *FnDecl = Best->Function;
14522
14523 bool IsReversed = Best->isReversed();
14524 if (IsReversed)
14525 std::swap(a&: Args[0], b&: Args[1]);
14526
14527 if (FnDecl) {
14528
14529 if (FnDecl->isInvalidDecl())
14530 return ExprError();
14531
14532 Expr *Base = nullptr;
14533 // We matched an overloaded operator. Build a call to that
14534 // operator.
14535
14536 OverloadedOperatorKind ChosenOp =
14537 FnDecl->getDeclName().getCXXOverloadedOperator();
14538
14539 // C++2a [over.match.oper]p9:
14540 // If a rewritten operator== candidate is selected by overload
14541 // resolution for an operator@, its return type shall be cv bool
14542 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14543 !FnDecl->getReturnType()->isBooleanType()) {
14544 bool IsExtension =
14545 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
14546 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14547 : diag::err_ovl_rewrite_equalequal_not_bool)
14548 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
14549 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14550 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
14551 if (!IsExtension)
14552 return ExprError();
14553 }
14554
14555 if (AllowRewrittenCandidates && !IsReversed &&
14556 CandidateSet.getRewriteInfo().isReversible()) {
14557 // We could have reversed this operator, but didn't. Check if some
14558 // reversed form was a viable candidate, and if so, if it had a
14559 // better conversion for either parameter. If so, this call is
14560 // formally ambiguous, and allowing it is an extension.
14561 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
14562 for (OverloadCandidate &Cand : CandidateSet) {
14563 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14564 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
14565 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14566 if (CompareImplicitConversionSequences(
14567 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
14568 ICS2: Best->Conversions[ArgIdx]) ==
14569 ImplicitConversionSequence::Better) {
14570 AmbiguousWith.push_back(Elt: Cand.Function);
14571 break;
14572 }
14573 }
14574 }
14575 }
14576
14577 if (!AmbiguousWith.empty()) {
14578 bool AmbiguousWithSelf =
14579 AmbiguousWith.size() == 1 &&
14580 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
14581 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
14582 << BinaryOperator::getOpcodeStr(Op: Opc)
14583 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14584 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14585 if (AmbiguousWithSelf) {
14586 Diag(Loc: FnDecl->getLocation(),
14587 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
14588 // Mark member== const or provide matching != to disallow reversed
14589 // args. Eg.
14590 // struct S { bool operator==(const S&); };
14591 // S()==S();
14592 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
14593 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14594 !MD->isConst() &&
14595 !MD->hasCXXExplicitFunctionObjectParameter() &&
14596 Context.hasSameUnqualifiedType(
14597 T1: MD->getFunctionObjectParameterType(),
14598 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
14599 Context.hasSameUnqualifiedType(
14600 T1: MD->getFunctionObjectParameterType(),
14601 T2: Args[0]->getType()) &&
14602 Context.hasSameUnqualifiedType(
14603 T1: MD->getFunctionObjectParameterType(),
14604 T2: Args[1]->getType()))
14605 Diag(Loc: FnDecl->getLocation(),
14606 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14607 } else {
14608 Diag(Loc: FnDecl->getLocation(),
14609 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14610 for (auto *F : AmbiguousWith)
14611 Diag(Loc: F->getLocation(),
14612 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14613 }
14614 }
14615 }
14616
14617 // Check for nonnull = nullable.
14618 // This won't be caught in the arg's initialization: the parameter to
14619 // the assignment operator is not marked nonnull.
14620 if (Op == OO_Equal)
14621 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
14622 SrcType: Args[1]->getType(), Loc: OpLoc);
14623
14624 // Convert the arguments.
14625 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
14626 // Best->Access is only meaningful for class members.
14627 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
14628
14629 ExprResult Arg0, Arg1;
14630 unsigned ParamIdx = 0;
14631 if (Method->isExplicitObjectMemberFunction()) {
14632 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
14633 ParamIdx = 1;
14634 } else {
14635 Arg0 = PerformImplicitObjectArgumentInitialization(
14636 From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
14637 }
14638 Arg1 = PerformCopyInitialization(
14639 Entity: InitializedEntity::InitializeParameter(
14640 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
14641 EqualLoc: SourceLocation(), Init: Args[1]);
14642 if (Arg0.isInvalid() || Arg1.isInvalid())
14643 return ExprError();
14644
14645 Base = Args[0] = Arg0.getAs<Expr>();
14646 Args[1] = RHS = Arg1.getAs<Expr>();
14647 } else {
14648 // Convert the arguments.
14649 ExprResult Arg0 = PerformCopyInitialization(
14650 Entity: InitializedEntity::InitializeParameter(Context,
14651 Parm: FnDecl->getParamDecl(i: 0)),
14652 EqualLoc: SourceLocation(), Init: Args[0]);
14653 if (Arg0.isInvalid())
14654 return ExprError();
14655
14656 ExprResult Arg1 =
14657 PerformCopyInitialization(
14658 Entity: InitializedEntity::InitializeParameter(Context,
14659 Parm: FnDecl->getParamDecl(i: 1)),
14660 EqualLoc: SourceLocation(), Init: Args[1]);
14661 if (Arg1.isInvalid())
14662 return ExprError();
14663 Args[0] = LHS = Arg0.getAs<Expr>();
14664 Args[1] = RHS = Arg1.getAs<Expr>();
14665 }
14666
14667 // Build the actual expression node.
14668 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
14669 FoundDecl: Best->FoundDecl, Base,
14670 HadMultipleCandidates, Loc: OpLoc);
14671 if (FnExpr.isInvalid())
14672 return ExprError();
14673
14674 // Determine the result type.
14675 QualType ResultTy = FnDecl->getReturnType();
14676 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
14677 ResultTy = ResultTy.getNonLValueExprType(Context);
14678
14679 CallExpr *TheCall;
14680 ArrayRef<const Expr *> ArgsArray(Args, 2);
14681 const Expr *ImplicitThis = nullptr;
14682
14683 // We always create a CXXOperatorCallExpr, even for explicit object
14684 // members; CodeGen should take care not to emit the this pointer.
14685 TheCall = CXXOperatorCallExpr::Create(
14686 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
14687 FPFeatures: CurFPFeatureOverrides(), UsesADL: Best->IsADLCandidate);
14688
14689 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
14690 Method && Method->isImplicitObjectMemberFunction()) {
14691 // Cut off the implicit 'this'.
14692 ImplicitThis = ArgsArray[0];
14693 ArgsArray = ArgsArray.slice(N: 1);
14694 }
14695
14696 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
14697 FD: FnDecl))
14698 return ExprError();
14699
14700 if (Op == OO_Equal) {
14701 // Check for a self move.
14702 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
14703 // lifetime check.
14704 checkExprLifetime(SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0]}, Init: Args[1]);
14705 }
14706 if (ImplicitThis) {
14707 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
14708 QualType ThisTypeFromDecl = Context.getPointerType(
14709 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
14710
14711 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
14712 ParamTy: ThisTypeFromDecl);
14713 }
14714
14715 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
14716 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
14717 CallType: VariadicDoesNotApply);
14718
14719 ExprResult R = MaybeBindToTemporary(E: TheCall);
14720 if (R.isInvalid())
14721 return ExprError();
14722
14723 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
14724 if (R.isInvalid())
14725 return ExprError();
14726
14727 // For a rewritten candidate, we've already reversed the arguments
14728 // if needed. Perform the rest of the rewrite now.
14729 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14730 (Op == OO_Spaceship && IsReversed)) {
14731 if (Op == OO_ExclaimEqual) {
14732 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14733 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
14734 } else {
14735 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14736 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
14737 Expr *ZeroLiteral =
14738 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
14739
14740 Sema::CodeSynthesisContext Ctx;
14741 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
14742 Ctx.Entity = FnDecl;
14743 pushCodeSynthesisContext(Ctx);
14744
14745 R = CreateOverloadedBinOp(
14746 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
14747 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14748 /*AllowRewrittenCandidates=*/false);
14749
14750 popCodeSynthesisContext();
14751 }
14752 if (R.isInvalid())
14753 return ExprError();
14754 } else {
14755 assert(ChosenOp == Op && "unexpected operator name");
14756 }
14757
14758 // Make a note in the AST if we did any rewriting.
14759 if (Best->RewriteKind != CRK_None)
14760 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14761
14762 return R;
14763 } else {
14764 // We matched a built-in operator. Convert the arguments, then
14765 // break out so that we will build the appropriate built-in
14766 // operator node.
14767 ExprResult ArgsRes0 = PerformImplicitConversion(
14768 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
14769 Action: AA_Passing, CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
14770 if (ArgsRes0.isInvalid())
14771 return ExprError();
14772 Args[0] = ArgsRes0.get();
14773
14774 ExprResult ArgsRes1 = PerformImplicitConversion(
14775 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
14776 Action: AA_Passing, CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
14777 if (ArgsRes1.isInvalid())
14778 return ExprError();
14779 Args[1] = ArgsRes1.get();
14780 break;
14781 }
14782 }
14783
14784 case OR_No_Viable_Function: {
14785 // C++ [over.match.oper]p9:
14786 // If the operator is the operator , [...] and there are no
14787 // viable functions, then the operator is assumed to be the
14788 // built-in operator and interpreted according to clause 5.
14789 if (Opc == BO_Comma)
14790 break;
14791
14792 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14793 // compare result using '==' and '<'.
14794 if (DefaultedFn && Opc == BO_Cmp) {
14795 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
14796 RHS: Args[1], DefaultedFn);
14797 if (E.isInvalid() || E.isUsable())
14798 return E;
14799 }
14800
14801 // For class as left operand for assignment or compound assignment
14802 // operator do not fall through to handling in built-in, but report that
14803 // no overloaded assignment operator found
14804 ExprResult Result = ExprError();
14805 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
14806 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
14807 Args, OpLoc);
14808 DeferDiagsRAII DDR(*this,
14809 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
14810 if (Args[0]->getType()->isRecordType() &&
14811 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14812 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
14813 << BinaryOperator::getOpcodeStr(Op: Opc)
14814 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14815 if (Args[0]->getType()->isIncompleteType()) {
14816 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
14817 << Args[0]->getType()
14818 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14819 }
14820 } else {
14821 // This is an erroneous use of an operator which can be overloaded by
14822 // a non-member function. Check for non-member operators which were
14823 // defined too late to be candidates.
14824 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
14825 // FIXME: Recover by calling the found function.
14826 return ExprError();
14827
14828 // No viable function; try to create a built-in operation, which will
14829 // produce an error. Then, show the non-viable candidates.
14830 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
14831 }
14832 assert(Result.isInvalid() &&
14833 "C++ binary operator overloading is missing candidates!");
14834 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
14835 return Result;
14836 }
14837
14838 case OR_Ambiguous:
14839 CandidateSet.NoteCandidates(
14840 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
14841 << BinaryOperator::getOpcodeStr(Op: Opc)
14842 << Args[0]->getType()
14843 << Args[1]->getType()
14844 << Args[0]->getSourceRange()
14845 << Args[1]->getSourceRange()),
14846 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
14847 OpLoc);
14848 return ExprError();
14849
14850 case OR_Deleted: {
14851 if (isImplicitlyDeleted(FD: Best->Function)) {
14852 FunctionDecl *DeletedFD = Best->Function;
14853 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
14854 if (DFK.isSpecialMember()) {
14855 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
14856 << Args[0]->getType()
14857 << llvm::to_underlying(E: DFK.asSpecialMember());
14858 } else {
14859 assert(DFK.isComparison());
14860 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
14861 << Args[0]->getType() << DeletedFD;
14862 }
14863
14864 // The user probably meant to call this special member. Just
14865 // explain why it's deleted.
14866 NoteDeletedFunction(FD: DeletedFD);
14867 return ExprError();
14868 }
14869
14870 StringLiteral *Msg = Best->Function->getDeletedMessage();
14871 CandidateSet.NoteCandidates(
14872 PD: PartialDiagnosticAt(
14873 OpLoc,
14874 PDiag(DiagID: diag::err_ovl_deleted_oper)
14875 << getOperatorSpelling(Operator: Best->Function->getDeclName()
14876 .getCXXOverloadedOperator())
14877 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
14878 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
14879 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
14880 OpLoc);
14881 return ExprError();
14882 }
14883 }
14884
14885 // We matched a built-in operator; build it.
14886 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
14887}
14888
14889ExprResult Sema::BuildSynthesizedThreeWayComparison(
14890 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14891 FunctionDecl *DefaultedFn) {
14892 const ComparisonCategoryInfo *Info =
14893 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
14894 // If we're not producing a known comparison category type, we can't
14895 // synthesize a three-way comparison. Let the caller diagnose this.
14896 if (!Info)
14897 return ExprResult((Expr*)nullptr);
14898
14899 // If we ever want to perform this synthesis more generally, we will need to
14900 // apply the temporary materialization conversion to the operands.
14901 assert(LHS->isGLValue() && RHS->isGLValue() &&
14902 "cannot use prvalue expressions more than once");
14903 Expr *OrigLHS = LHS;
14904 Expr *OrigRHS = RHS;
14905
14906 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14907 // each of them multiple times below.
14908 LHS = new (Context)
14909 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14910 LHS->getObjectKind(), LHS);
14911 RHS = new (Context)
14912 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14913 RHS->getObjectKind(), RHS);
14914
14915 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
14916 DefaultedFn);
14917 if (Eq.isInvalid())
14918 return ExprError();
14919
14920 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
14921 AllowRewrittenCandidates: true, DefaultedFn);
14922 if (Less.isInvalid())
14923 return ExprError();
14924
14925 ExprResult Greater;
14926 if (Info->isPartial()) {
14927 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
14928 DefaultedFn);
14929 if (Greater.isInvalid())
14930 return ExprError();
14931 }
14932
14933 // Form the list of comparisons we're going to perform.
14934 struct Comparison {
14935 ExprResult Cmp;
14936 ComparisonCategoryResult Result;
14937 } Comparisons[4] =
14938 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
14939 : ComparisonCategoryResult::Equivalent},
14940 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
14941 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
14942 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
14943 };
14944
14945 int I = Info->isPartial() ? 3 : 2;
14946
14947 // Combine the comparisons with suitable conditional expressions.
14948 ExprResult Result;
14949 for (; I >= 0; --I) {
14950 // Build a reference to the comparison category constant.
14951 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
14952 // FIXME: Missing a constant for a comparison category. Diagnose this?
14953 if (!VI)
14954 return ExprResult((Expr*)nullptr);
14955 ExprResult ThisResult =
14956 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
14957 if (ThisResult.isInvalid())
14958 return ExprError();
14959
14960 // Build a conditional unless this is the final case.
14961 if (Result.get()) {
14962 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
14963 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
14964 if (Result.isInvalid())
14965 return ExprError();
14966 } else {
14967 Result = ThisResult;
14968 }
14969 }
14970
14971 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14972 // bind the OpaqueValueExprs before they're (repeatedly) used.
14973 Expr *SyntacticForm = BinaryOperator::Create(
14974 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
14975 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
14976 FPFeatures: CurFPFeatureOverrides());
14977 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14978 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
14979}
14980
14981static bool PrepareArgumentsForCallToObjectOfClassType(
14982 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14983 MultiExprArg Args, SourceLocation LParenLoc) {
14984
14985 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14986 unsigned NumParams = Proto->getNumParams();
14987 unsigned NumArgsSlots =
14988 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
14989 // Build the full argument list for the method call (the implicit object
14990 // parameter is placed at the beginning of the list).
14991 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
14992 bool IsError = false;
14993 // Initialize the implicit object parameter.
14994 // Check the argument types.
14995 for (unsigned i = 0; i != NumParams; i++) {
14996 Expr *Arg;
14997 if (i < Args.size()) {
14998 Arg = Args[i];
14999 ExprResult InputInit =
15000 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15001 Context&: S.Context, Parm: Method->getParamDecl(i)),
15002 EqualLoc: SourceLocation(), Init: Arg);
15003 IsError |= InputInit.isInvalid();
15004 Arg = InputInit.getAs<Expr>();
15005 } else {
15006 ExprResult DefArg =
15007 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
15008 if (DefArg.isInvalid()) {
15009 IsError = true;
15010 break;
15011 }
15012 Arg = DefArg.getAs<Expr>();
15013 }
15014
15015 MethodArgs.push_back(Elt: Arg);
15016 }
15017 return IsError;
15018}
15019
15020ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15021 SourceLocation RLoc,
15022 Expr *Base,
15023 MultiExprArg ArgExpr) {
15024 SmallVector<Expr *, 2> Args;
15025 Args.push_back(Elt: Base);
15026 for (auto *e : ArgExpr) {
15027 Args.push_back(Elt: e);
15028 }
15029 DeclarationName OpName =
15030 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
15031
15032 SourceRange Range = ArgExpr.empty()
15033 ? SourceRange{}
15034 : SourceRange(ArgExpr.front()->getBeginLoc(),
15035 ArgExpr.back()->getEndLoc());
15036
15037 // If either side is type-dependent, create an appropriate dependent
15038 // expression.
15039 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
15040
15041 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15042 // CHECKME: no 'operator' keyword?
15043 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15044 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15045 ExprResult Fn = CreateUnresolvedLookupExpr(
15046 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
15047 if (Fn.isInvalid())
15048 return ExprError();
15049 // Can't add any actual overloads yet
15050
15051 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
15052 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
15053 FPFeatures: CurFPFeatureOverrides());
15054 }
15055
15056 // Handle placeholders
15057 UnbridgedCastsSet UnbridgedCasts;
15058 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
15059 return ExprError();
15060 }
15061 // Build an empty overload set.
15062 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15063
15064 // Subscript can only be overloaded as a member function.
15065
15066 // Add operator candidates that are member functions.
15067 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15068
15069 // Add builtin operator candidates.
15070 if (Args.size() == 2)
15071 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15072
15073 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15074
15075 // Perform overload resolution.
15076 OverloadCandidateSet::iterator Best;
15077 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
15078 case OR_Success: {
15079 // We found a built-in operator or an overloaded operator.
15080 FunctionDecl *FnDecl = Best->Function;
15081
15082 if (FnDecl) {
15083 // We matched an overloaded operator. Build a call to that
15084 // operator.
15085
15086 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
15087
15088 // Convert the arguments.
15089 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
15090 SmallVector<Expr *, 2> MethodArgs;
15091
15092 // Initialize the object parameter.
15093 if (Method->isExplicitObjectMemberFunction()) {
15094 ExprResult Res =
15095 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
15096 if (Res.isInvalid())
15097 return ExprError();
15098 Args[0] = Res.get();
15099 ArgExpr = Args;
15100 } else {
15101 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15102 From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15103 if (Arg0.isInvalid())
15104 return ExprError();
15105
15106 MethodArgs.push_back(Elt: Arg0.get());
15107 }
15108
15109 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15110 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
15111 if (IsError)
15112 return ExprError();
15113
15114 // Build the actual expression node.
15115 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15116 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15117 ExprResult FnExpr = CreateFunctionRefExpr(
15118 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
15119 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
15120 if (FnExpr.isInvalid())
15121 return ExprError();
15122
15123 // Determine the result type
15124 QualType ResultTy = FnDecl->getReturnType();
15125 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15126 ResultTy = ResultTy.getNonLValueExprType(Context);
15127
15128 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15129 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
15130 FPFeatures: CurFPFeatureOverrides());
15131
15132 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
15133 return ExprError();
15134
15135 if (CheckFunctionCall(FDecl: Method, TheCall,
15136 Proto: Method->getType()->castAs<FunctionProtoType>()))
15137 return ExprError();
15138
15139 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
15140 Decl: FnDecl);
15141 } else {
15142 // We matched a built-in operator. Convert the arguments, then
15143 // break out so that we will build the appropriate built-in
15144 // operator node.
15145 ExprResult ArgsRes0 = PerformImplicitConversion(
15146 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15147 Action: AA_Passing, CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15148 if (ArgsRes0.isInvalid())
15149 return ExprError();
15150 Args[0] = ArgsRes0.get();
15151
15152 ExprResult ArgsRes1 = PerformImplicitConversion(
15153 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15154 Action: AA_Passing, CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15155 if (ArgsRes1.isInvalid())
15156 return ExprError();
15157 Args[1] = ArgsRes1.get();
15158
15159 break;
15160 }
15161 }
15162
15163 case OR_No_Viable_Function: {
15164 PartialDiagnostic PD =
15165 CandidateSet.empty()
15166 ? (PDiag(DiagID: diag::err_ovl_no_oper)
15167 << Args[0]->getType() << /*subscript*/ 0
15168 << Args[0]->getSourceRange() << Range)
15169 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
15170 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15171 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
15172 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
15173 return ExprError();
15174 }
15175
15176 case OR_Ambiguous:
15177 if (Args.size() == 2) {
15178 CandidateSet.NoteCandidates(
15179 PD: PartialDiagnosticAt(
15180 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15181 << "[]" << Args[0]->getType() << Args[1]->getType()
15182 << Args[0]->getSourceRange() << Range),
15183 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
15184 } else {
15185 CandidateSet.NoteCandidates(
15186 PD: PartialDiagnosticAt(LLoc,
15187 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
15188 << Args[0]->getType()
15189 << Args[0]->getSourceRange() << Range),
15190 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
15191 }
15192 return ExprError();
15193
15194 case OR_Deleted: {
15195 StringLiteral *Msg = Best->Function->getDeletedMessage();
15196 CandidateSet.NoteCandidates(
15197 PD: PartialDiagnosticAt(LLoc,
15198 PDiag(DiagID: diag::err_ovl_deleted_oper)
15199 << "[]" << (Msg != nullptr)
15200 << (Msg ? Msg->getString() : StringRef())
15201 << Args[0]->getSourceRange() << Range),
15202 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
15203 return ExprError();
15204 }
15205 }
15206
15207 // We matched a built-in operator; build it.
15208 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
15209}
15210
15211ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
15212 SourceLocation LParenLoc,
15213 MultiExprArg Args,
15214 SourceLocation RParenLoc,
15215 Expr *ExecConfig, bool IsExecConfig,
15216 bool AllowRecovery) {
15217 assert(MemExprE->getType() == Context.BoundMemberTy ||
15218 MemExprE->getType() == Context.OverloadTy);
15219
15220 // Dig out the member expression. This holds both the object
15221 // argument and the member function we're referring to.
15222 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15223
15224 // Determine whether this is a call to a pointer-to-member function.
15225 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
15226 assert(op->getType() == Context.BoundMemberTy);
15227 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15228
15229 QualType fnType =
15230 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15231
15232 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15233 QualType resultType = proto->getCallResultType(Context);
15234 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
15235
15236 // Check that the object type isn't more qualified than the
15237 // member function we're calling.
15238 Qualifiers funcQuals = proto->getMethodQuals();
15239
15240 QualType objectType = op->getLHS()->getType();
15241 if (op->getOpcode() == BO_PtrMemI)
15242 objectType = objectType->castAs<PointerType>()->getPointeeType();
15243 Qualifiers objectQuals = objectType.getQualifiers();
15244
15245 Qualifiers difference = objectQuals - funcQuals;
15246 difference.removeObjCGCAttr();
15247 difference.removeAddressSpace();
15248 if (difference) {
15249 std::string qualsString = difference.getAsString();
15250 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
15251 << fnType.getUnqualifiedType()
15252 << qualsString
15253 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
15254 }
15255
15256 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
15257 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
15258 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
15259
15260 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
15261 CE: call, FD: nullptr))
15262 return ExprError();
15263
15264 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
15265 return ExprError();
15266
15267 if (CheckOtherCall(TheCall: call, Proto: proto))
15268 return ExprError();
15269
15270 return MaybeBindToTemporary(E: call);
15271 }
15272
15273 // We only try to build a recovery expr at this level if we can preserve
15274 // the return type, otherwise we return ExprError() and let the caller
15275 // recover.
15276 auto BuildRecoveryExpr = [&](QualType Type) {
15277 if (!AllowRecovery)
15278 return ExprError();
15279 std::vector<Expr *> SubExprs = {MemExprE};
15280 llvm::append_range(C&: SubExprs, R&: Args);
15281 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
15282 T: Type);
15283 };
15284 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
15285 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
15286 RParenLoc, FPFeatures: CurFPFeatureOverrides());
15287
15288 UnbridgedCastsSet UnbridgedCasts;
15289 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
15290 return ExprError();
15291
15292 MemberExpr *MemExpr;
15293 CXXMethodDecl *Method = nullptr;
15294 bool HadMultipleCandidates = false;
15295 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
15296 NestedNameSpecifier *Qualifier = nullptr;
15297 if (isa<MemberExpr>(Val: NakedMemExpr)) {
15298 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
15299 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
15300 FoundDecl = MemExpr->getFoundDecl();
15301 Qualifier = MemExpr->getQualifier();
15302 UnbridgedCasts.restore();
15303 } else {
15304 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
15305 Qualifier = UnresExpr->getQualifier();
15306
15307 QualType ObjectType = UnresExpr->getBaseType();
15308 Expr::Classification ObjectClassification
15309 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
15310 : UnresExpr->getBase()->Classify(Ctx&: Context);
15311
15312 // Add overload candidates
15313 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15314 OverloadCandidateSet::CSK_Normal);
15315
15316 // FIXME: avoid copy.
15317 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15318 if (UnresExpr->hasExplicitTemplateArgs()) {
15319 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
15320 TemplateArgs = &TemplateArgsBuffer;
15321 }
15322
15323 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
15324 E = UnresExpr->decls_end(); I != E; ++I) {
15325
15326 QualType ExplicitObjectType = ObjectType;
15327
15328 NamedDecl *Func = *I;
15329 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
15330 if (isa<UsingShadowDecl>(Val: Func))
15331 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
15332
15333 bool HasExplicitParameter = false;
15334 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
15335 M && M->hasCXXExplicitFunctionObjectParameter())
15336 HasExplicitParameter = true;
15337 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
15338 M &&
15339 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15340 HasExplicitParameter = true;
15341
15342 if (HasExplicitParameter)
15343 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
15344
15345 // Microsoft supports direct constructor calls.
15346 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
15347 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
15348 CandidateSet,
15349 /*SuppressUserConversions*/ false);
15350 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
15351 // If explicit template arguments were provided, we can't call a
15352 // non-template member function.
15353 if (TemplateArgs)
15354 continue;
15355
15356 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
15357 ObjectClassification, Args, CandidateSet,
15358 /*SuppressUserConversions=*/false);
15359 } else {
15360 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
15361 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
15362 ObjectType: ExplicitObjectType, ObjectClassification,
15363 Args, CandidateSet,
15364 /*SuppressUserConversions=*/false);
15365 }
15366 }
15367
15368 HadMultipleCandidates = (CandidateSet.size() > 1);
15369
15370 DeclarationName DeclName = UnresExpr->getMemberName();
15371
15372 UnbridgedCasts.restore();
15373
15374 OverloadCandidateSet::iterator Best;
15375 bool Succeeded = false;
15376 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
15377 Best)) {
15378 case OR_Success:
15379 Method = cast<CXXMethodDecl>(Val: Best->Function);
15380 FoundDecl = Best->FoundDecl;
15381 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
15382 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
15383 break;
15384 // If FoundDecl is different from Method (such as if one is a template
15385 // and the other a specialization), make sure DiagnoseUseOfDecl is
15386 // called on both.
15387 // FIXME: This would be more comprehensively addressed by modifying
15388 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15389 // being used.
15390 if (Method != FoundDecl.getDecl() &&
15391 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
15392 break;
15393 Succeeded = true;
15394 break;
15395
15396 case OR_No_Viable_Function:
15397 CandidateSet.NoteCandidates(
15398 PD: PartialDiagnosticAt(
15399 UnresExpr->getMemberLoc(),
15400 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
15401 << DeclName << MemExprE->getSourceRange()),
15402 S&: *this, OCD: OCD_AllCandidates, Args);
15403 break;
15404 case OR_Ambiguous:
15405 CandidateSet.NoteCandidates(
15406 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15407 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
15408 << DeclName << MemExprE->getSourceRange()),
15409 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
15410 break;
15411 case OR_Deleted:
15412 DiagnoseUseOfDeletedFunction(
15413 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
15414 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
15415 break;
15416 }
15417 // Overload resolution fails, try to recover.
15418 if (!Succeeded)
15419 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
15420
15421 ExprResult Res =
15422 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
15423 if (Res.isInvalid())
15424 return ExprError();
15425 MemExprE = Res.get();
15426
15427 // If overload resolution picked a static member
15428 // build a non-member call based on that function.
15429 if (Method->isStatic()) {
15430 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
15431 Config: ExecConfig, IsExecConfig);
15432 }
15433
15434 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
15435 }
15436
15437 QualType ResultType = Method->getReturnType();
15438 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15439 ResultType = ResultType.getNonLValueExprType(Context);
15440
15441 assert(Method && "Member call to something that isn't a method?");
15442 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15443
15444 CallExpr *TheCall = nullptr;
15445 llvm::SmallVector<Expr *, 8> NewArgs;
15446 if (Method->isExplicitObjectMemberFunction()) {
15447 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
15448 NewArgs))
15449 return ExprError();
15450
15451 // Build the actual expression node.
15452 ExprResult FnExpr =
15453 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
15454 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
15455 if (FnExpr.isInvalid())
15456 return ExprError();
15457
15458 TheCall =
15459 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
15460 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
15461 } else {
15462 // Convert the object argument (for a non-static member function call).
15463 // We only need to do this if there was actually an overload; otherwise
15464 // it was done at lookup.
15465 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15466 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
15467 if (ObjectArg.isInvalid())
15468 return ExprError();
15469 MemExpr->setBase(ObjectArg.get());
15470 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
15471 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
15472 MinNumArgs: Proto->getNumParams());
15473 }
15474
15475 // Check for a valid return type.
15476 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
15477 CE: TheCall, FD: Method))
15478 return BuildRecoveryExpr(ResultType);
15479
15480 // Convert the rest of the arguments
15481 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
15482 RParenLoc))
15483 return BuildRecoveryExpr(ResultType);
15484
15485 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
15486
15487 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
15488 return ExprError();
15489
15490 // In the case the method to call was not selected by the overloading
15491 // resolution process, we still need to handle the enable_if attribute. Do
15492 // that here, so it will not hide previous -- and more relevant -- errors.
15493 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
15494 if (const EnableIfAttr *Attr =
15495 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
15496 Diag(Loc: MemE->getMemberLoc(),
15497 DiagID: diag::err_ovl_no_viable_member_function_in_call)
15498 << Method << Method->getSourceRange();
15499 Diag(Loc: Method->getLocation(),
15500 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
15501 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15502 return ExprError();
15503 }
15504 }
15505
15506 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
15507 TheCall->getDirectCallee()->isPureVirtual()) {
15508 const FunctionDecl *MD = TheCall->getDirectCallee();
15509
15510 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
15511 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
15512 Diag(Loc: MemExpr->getBeginLoc(),
15513 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15514 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
15515 << MD->getParent();
15516
15517 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
15518 if (getLangOpts().AppleKext)
15519 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
15520 << MD->getParent() << MD->getDeclName();
15521 }
15522 }
15523
15524 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
15525 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15526 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15527 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
15528 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15529 DtorLoc: MemExpr->getMemberLoc());
15530 }
15531
15532 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
15533 Decl: TheCall->getDirectCallee());
15534}
15535
15536ExprResult
15537Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
15538 SourceLocation LParenLoc,
15539 MultiExprArg Args,
15540 SourceLocation RParenLoc) {
15541 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
15542 return ExprError();
15543 ExprResult Object = Obj;
15544
15545 UnbridgedCastsSet UnbridgedCasts;
15546 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
15547 return ExprError();
15548
15549 assert(Object.get()->getType()->isRecordType() &&
15550 "Requires object type argument");
15551
15552 // C++ [over.call.object]p1:
15553 // If the primary-expression E in the function call syntax
15554 // evaluates to a class object of type "cv T", then the set of
15555 // candidate functions includes at least the function call
15556 // operators of T. The function call operators of T are obtained by
15557 // ordinary lookup of the name operator() in the context of
15558 // (E).operator().
15559 OverloadCandidateSet CandidateSet(LParenLoc,
15560 OverloadCandidateSet::CSK_Operator);
15561 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
15562
15563 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
15564 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
15565 return true;
15566
15567 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15568 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15569 LookupQualifiedName(R, LookupCtx: Record->getDecl());
15570 R.suppressAccessDiagnostics();
15571
15572 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15573 Oper != OperEnd; ++Oper) {
15574 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
15575 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
15576 /*SuppressUserConversion=*/SuppressUserConversions: false);
15577 }
15578
15579 // When calling a lambda, both the call operator, and
15580 // the conversion operator to function pointer
15581 // are considered. But when constraint checking
15582 // on the call operator fails, it will also fail on the
15583 // conversion operator as the constraints are always the same.
15584 // As the user probably does not intend to perform a surrogate call,
15585 // we filter them out to produce better error diagnostics, ie to avoid
15586 // showing 2 failed overloads instead of one.
15587 bool IgnoreSurrogateFunctions = false;
15588 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15589 const OverloadCandidate &Candidate = *CandidateSet.begin();
15590 if (!Candidate.Viable &&
15591 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
15592 IgnoreSurrogateFunctions = true;
15593 }
15594
15595 // C++ [over.call.object]p2:
15596 // In addition, for each (non-explicit in C++0x) conversion function
15597 // declared in T of the form
15598 //
15599 // operator conversion-type-id () cv-qualifier;
15600 //
15601 // where cv-qualifier is the same cv-qualification as, or a
15602 // greater cv-qualification than, cv, and where conversion-type-id
15603 // denotes the type "pointer to function of (P1,...,Pn) returning
15604 // R", or the type "reference to pointer to function of
15605 // (P1,...,Pn) returning R", or the type "reference to function
15606 // of (P1,...,Pn) returning R", a surrogate call function [...]
15607 // is also considered as a candidate function. Similarly,
15608 // surrogate call functions are added to the set of candidate
15609 // functions for each conversion function declared in an
15610 // accessible base class provided the function is not hidden
15611 // within T by another intervening declaration.
15612 const auto &Conversions =
15613 cast<CXXRecordDecl>(Val: Record->getDecl())->getVisibleConversionFunctions();
15614 for (auto I = Conversions.begin(), E = Conversions.end();
15615 !IgnoreSurrogateFunctions && I != E; ++I) {
15616 NamedDecl *D = *I;
15617 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
15618 if (isa<UsingShadowDecl>(Val: D))
15619 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
15620
15621 // Skip over templated conversion functions; they aren't
15622 // surrogates.
15623 if (isa<FunctionTemplateDecl>(Val: D))
15624 continue;
15625
15626 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
15627 if (!Conv->isExplicit()) {
15628 // Strip the reference type (if any) and then the pointer type (if
15629 // any) to get down to what might be a function type.
15630 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15631 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15632 ConvType = ConvPtrType->getPointeeType();
15633
15634 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15635 {
15636 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
15637 Object: Object.get(), Args, CandidateSet);
15638 }
15639 }
15640 }
15641
15642 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15643
15644 // Perform overload resolution.
15645 OverloadCandidateSet::iterator Best;
15646 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
15647 Best)) {
15648 case OR_Success:
15649 // Overload resolution succeeded; we'll build the appropriate call
15650 // below.
15651 break;
15652
15653 case OR_No_Viable_Function: {
15654 PartialDiagnostic PD =
15655 CandidateSet.empty()
15656 ? (PDiag(DiagID: diag::err_ovl_no_oper)
15657 << Object.get()->getType() << /*call*/ 1
15658 << Object.get()->getSourceRange())
15659 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
15660 << Object.get()->getType() << Object.get()->getSourceRange());
15661 CandidateSet.NoteCandidates(
15662 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
15663 OCD: OCD_AllCandidates, Args);
15664 break;
15665 }
15666 case OR_Ambiguous:
15667 if (!R.isAmbiguous())
15668 CandidateSet.NoteCandidates(
15669 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
15670 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
15671 << Object.get()->getType()
15672 << Object.get()->getSourceRange()),
15673 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
15674 break;
15675
15676 case OR_Deleted: {
15677 // FIXME: Is this diagnostic here really necessary? It seems that
15678 // 1. we don't have any tests for this diagnostic, and
15679 // 2. we already issue err_deleted_function_use for this later on anyway.
15680 StringLiteral *Msg = Best->Function->getDeletedMessage();
15681 CandidateSet.NoteCandidates(
15682 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
15683 PDiag(DiagID: diag::err_ovl_deleted_object_call)
15684 << Object.get()->getType() << (Msg != nullptr)
15685 << (Msg ? Msg->getString() : StringRef())
15686 << Object.get()->getSourceRange()),
15687 S&: *this, OCD: OCD_AllCandidates, Args);
15688 break;
15689 }
15690 }
15691
15692 if (Best == CandidateSet.end())
15693 return true;
15694
15695 UnbridgedCasts.restore();
15696
15697 if (Best->Function == nullptr) {
15698 // Since there is no function declaration, this is one of the
15699 // surrogate candidates. Dig out the conversion function.
15700 CXXConversionDecl *Conv
15701 = cast<CXXConversionDecl>(
15702 Val: Best->Conversions[0].UserDefined.ConversionFunction);
15703
15704 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
15705 FoundDecl: Best->FoundDecl);
15706 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
15707 return ExprError();
15708 assert(Conv == Best->FoundDecl.getDecl() &&
15709 "Found Decl & conversion-to-functionptr should be same, right?!");
15710 // We selected one of the surrogate functions that converts the
15711 // object parameter to a function pointer. Perform the conversion
15712 // on the object argument, then let BuildCallExpr finish the job.
15713
15714 // Create an implicit member expr to refer to the conversion operator.
15715 // and then call it.
15716 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
15717 Method: Conv, HadMultipleCandidates);
15718 if (Call.isInvalid())
15719 return ExprError();
15720 // Record usage of conversion in an implicit cast.
15721 Call = ImplicitCastExpr::Create(
15722 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
15723 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
15724
15725 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
15726 }
15727
15728 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15729
15730 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15731 // that calls this method, using Object for the implicit object
15732 // parameter and passing along the remaining arguments.
15733 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
15734
15735 // An error diagnostic has already been printed when parsing the declaration.
15736 if (Method->isInvalidDecl())
15737 return ExprError();
15738
15739 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15740 unsigned NumParams = Proto->getNumParams();
15741
15742 DeclarationNameInfo OpLocInfo(
15743 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
15744 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15745 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
15746 Base: Obj, HadMultipleCandidates,
15747 Loc: OpLocInfo.getLoc(),
15748 LocInfo: OpLocInfo.getInfo());
15749 if (NewFn.isInvalid())
15750 return true;
15751
15752 SmallVector<Expr *, 8> MethodArgs;
15753 MethodArgs.reserve(N: NumParams + 1);
15754
15755 bool IsError = false;
15756
15757 // Initialize the object parameter.
15758 llvm::SmallVector<Expr *, 8> NewArgs;
15759 if (Method->isExplicitObjectMemberFunction()) {
15760 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
15761 } else {
15762 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15763 From: Object.get(), /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15764 if (ObjRes.isInvalid())
15765 IsError = true;
15766 else
15767 Object = ObjRes;
15768 MethodArgs.push_back(Elt: Object.get());
15769 }
15770
15771 IsError |= PrepareArgumentsForCallToObjectOfClassType(
15772 S&: *this, MethodArgs, Method, Args, LParenLoc);
15773
15774 // If this is a variadic call, handle args passed through "...".
15775 if (Proto->isVariadic()) {
15776 // Promote the arguments (C99 6.5.2.2p7).
15777 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15778 ExprResult Arg = DefaultVariadicArgumentPromotion(E: Args[i], CT: VariadicMethod,
15779 FDecl: nullptr);
15780 IsError |= Arg.isInvalid();
15781 MethodArgs.push_back(Elt: Arg.get());
15782 }
15783 }
15784
15785 if (IsError)
15786 return true;
15787
15788 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
15789
15790 // Once we've built TheCall, all of the expressions are properly owned.
15791 QualType ResultTy = Method->getReturnType();
15792 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15793 ResultTy = ResultTy.getNonLValueExprType(Context);
15794
15795 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15796 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
15797 FPFeatures: CurFPFeatureOverrides());
15798
15799 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
15800 return true;
15801
15802 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
15803 return true;
15804
15805 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
15806}
15807
15808ExprResult
15809Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
15810 bool *NoArrowOperatorFound) {
15811 assert(Base->getType()->isRecordType() &&
15812 "left-hand side must have class type");
15813
15814 if (checkPlaceholderForOverload(S&: *this, E&: Base))
15815 return ExprError();
15816
15817 SourceLocation Loc = Base->getExprLoc();
15818
15819 // C++ [over.ref]p1:
15820 //
15821 // [...] An expression x->m is interpreted as (x.operator->())->m
15822 // for a class object x of type T if T::operator->() exists and if
15823 // the operator is selected as the best match function by the
15824 // overload resolution mechanism (13.3).
15825 DeclarationName OpName =
15826 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
15827 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
15828
15829 if (RequireCompleteType(Loc, T: Base->getType(),
15830 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
15831 return ExprError();
15832
15833 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15834 LookupQualifiedName(R, LookupCtx: Base->getType()->castAs<RecordType>()->getDecl());
15835 R.suppressAccessDiagnostics();
15836
15837 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15838 Oper != OperEnd; ++Oper) {
15839 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
15840 Args: std::nullopt, CandidateSet,
15841 /*SuppressUserConversion=*/SuppressUserConversions: false);
15842 }
15843
15844 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15845
15846 // Perform overload resolution.
15847 OverloadCandidateSet::iterator Best;
15848 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15849 case OR_Success:
15850 // Overload resolution succeeded; we'll build the call below.
15851 break;
15852
15853 case OR_No_Viable_Function: {
15854 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
15855 if (CandidateSet.empty()) {
15856 QualType BaseType = Base->getType();
15857 if (NoArrowOperatorFound) {
15858 // Report this specific error to the caller instead of emitting a
15859 // diagnostic, as requested.
15860 *NoArrowOperatorFound = true;
15861 return ExprError();
15862 }
15863 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
15864 << BaseType << Base->getSourceRange();
15865 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15866 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
15867 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
15868 }
15869 } else
15870 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15871 << "operator->" << Base->getSourceRange();
15872 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
15873 return ExprError();
15874 }
15875 case OR_Ambiguous:
15876 if (!R.isAmbiguous())
15877 CandidateSet.NoteCandidates(
15878 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15879 << "->" << Base->getType()
15880 << Base->getSourceRange()),
15881 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
15882 return ExprError();
15883
15884 case OR_Deleted: {
15885 StringLiteral *Msg = Best->Function->getDeletedMessage();
15886 CandidateSet.NoteCandidates(
15887 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15888 << "->" << (Msg != nullptr)
15889 << (Msg ? Msg->getString() : StringRef())
15890 << Base->getSourceRange()),
15891 S&: *this, OCD: OCD_AllCandidates, Args: Base);
15892 return ExprError();
15893 }
15894 }
15895
15896 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15897
15898 // Convert the object parameter.
15899 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
15900
15901 if (Method->isExplicitObjectMemberFunction()) {
15902 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
15903 if (R.isInvalid())
15904 return ExprError();
15905 Base = R.get();
15906 } else {
15907 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
15908 From: Base, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15909 if (BaseResult.isInvalid())
15910 return ExprError();
15911 Base = BaseResult.get();
15912 }
15913
15914 // Build the operator call.
15915 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
15916 Base, HadMultipleCandidates, Loc: OpLoc);
15917 if (FnExpr.isInvalid())
15918 return ExprError();
15919
15920 QualType ResultTy = Method->getReturnType();
15921 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15922 ResultTy = ResultTy.getNonLValueExprType(Context);
15923
15924 CallExpr *TheCall =
15925 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
15926 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15927
15928 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
15929 return ExprError();
15930
15931 if (CheckFunctionCall(FDecl: Method, TheCall,
15932 Proto: Method->getType()->castAs<FunctionProtoType>()))
15933 return ExprError();
15934
15935 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
15936}
15937
15938ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15939 DeclarationNameInfo &SuffixInfo,
15940 ArrayRef<Expr*> Args,
15941 SourceLocation LitEndLoc,
15942 TemplateArgumentListInfo *TemplateArgs) {
15943 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15944
15945 OverloadCandidateSet CandidateSet(UDSuffixLoc,
15946 OverloadCandidateSet::CSK_Normal);
15947 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
15948 ExplicitTemplateArgs: TemplateArgs);
15949
15950 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15951
15952 // Perform overload resolution. This will usually be trivial, but might need
15953 // to perform substitutions for a literal operator template.
15954 OverloadCandidateSet::iterator Best;
15955 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
15956 case OR_Success:
15957 case OR_Deleted:
15958 break;
15959
15960 case OR_No_Viable_Function:
15961 CandidateSet.NoteCandidates(
15962 PD: PartialDiagnosticAt(UDSuffixLoc,
15963 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
15964 << R.getLookupName()),
15965 S&: *this, OCD: OCD_AllCandidates, Args);
15966 return ExprError();
15967
15968 case OR_Ambiguous:
15969 CandidateSet.NoteCandidates(
15970 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
15971 << R.getLookupName()),
15972 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
15973 return ExprError();
15974 }
15975
15976 FunctionDecl *FD = Best->Function;
15977 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
15978 Base: nullptr, HadMultipleCandidates,
15979 Loc: SuffixInfo.getLoc(),
15980 LocInfo: SuffixInfo.getInfo());
15981 if (Fn.isInvalid())
15982 return true;
15983
15984 // Check the argument types. This should almost always be a no-op, except
15985 // that array-to-pointer decay is applied to string literals.
15986 Expr *ConvArgs[2];
15987 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15988 ExprResult InputInit = PerformCopyInitialization(
15989 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
15990 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
15991 if (InputInit.isInvalid())
15992 return true;
15993 ConvArgs[ArgIdx] = InputInit.get();
15994 }
15995
15996 QualType ResultTy = FD->getReturnType();
15997 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15998 ResultTy = ResultTy.getNonLValueExprType(Context);
15999
16000 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16001 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
16002 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
16003
16004 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
16005 return ExprError();
16006
16007 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
16008 return ExprError();
16009
16010 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
16011}
16012
16013Sema::ForRangeStatus
16014Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16015 SourceLocation RangeLoc,
16016 const DeclarationNameInfo &NameInfo,
16017 LookupResult &MemberLookup,
16018 OverloadCandidateSet *CandidateSet,
16019 Expr *Range, ExprResult *CallExpr) {
16020 Scope *S = nullptr;
16021
16022 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
16023 if (!MemberLookup.empty()) {
16024 ExprResult MemberRef =
16025 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
16026 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
16027 /*TemplateKWLoc=*/SourceLocation(),
16028 /*FirstQualifierInScope=*/nullptr,
16029 R&: MemberLookup,
16030 /*TemplateArgs=*/nullptr, S);
16031 if (MemberRef.isInvalid()) {
16032 *CallExpr = ExprError();
16033 return FRS_DiagnosticIssued;
16034 }
16035 *CallExpr =
16036 BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: std::nullopt, RParenLoc: Loc, ExecConfig: nullptr);
16037 if (CallExpr->isInvalid()) {
16038 *CallExpr = ExprError();
16039 return FRS_DiagnosticIssued;
16040 }
16041 } else {
16042 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16043 NNSLoc: NestedNameSpecifierLoc(),
16044 DNI: NameInfo, Fns: UnresolvedSet<0>());
16045 if (FnR.isInvalid())
16046 return FRS_DiagnosticIssued;
16047 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
16048
16049 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
16050 CandidateSet, Result: CallExpr);
16051 if (CandidateSet->empty() || CandidateSetError) {
16052 *CallExpr = ExprError();
16053 return FRS_NoViableFunction;
16054 }
16055 OverloadCandidateSet::iterator Best;
16056 OverloadingResult OverloadResult =
16057 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
16058
16059 if (OverloadResult == OR_No_Viable_Function) {
16060 *CallExpr = ExprError();
16061 return FRS_NoViableFunction;
16062 }
16063 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
16064 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
16065 OverloadResult,
16066 /*AllowTypoCorrection=*/false);
16067 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16068 *CallExpr = ExprError();
16069 return FRS_DiagnosticIssued;
16070 }
16071 }
16072 return FRS_Success;
16073}
16074
16075ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16076 FunctionDecl *Fn) {
16077 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
16078 ExprResult SubExpr =
16079 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
16080 if (SubExpr.isInvalid())
16081 return ExprError();
16082 if (SubExpr.get() == PE->getSubExpr())
16083 return PE;
16084
16085 return new (Context)
16086 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16087 }
16088
16089 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
16090 ExprResult SubExpr =
16091 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
16092 if (SubExpr.isInvalid())
16093 return ExprError();
16094 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16095 SubExpr.get()->getType()) &&
16096 "Implicit cast type cannot be determined from overload");
16097 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16098 if (SubExpr.get() == ICE->getSubExpr())
16099 return ICE;
16100
16101 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
16102 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
16103 FPO: CurFPFeatureOverrides());
16104 }
16105
16106 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
16107 if (!GSE->isResultDependent()) {
16108 ExprResult SubExpr =
16109 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
16110 if (SubExpr.isInvalid())
16111 return ExprError();
16112 if (SubExpr.get() == GSE->getResultExpr())
16113 return GSE;
16114
16115 // Replace the resulting type information before rebuilding the generic
16116 // selection expression.
16117 ArrayRef<Expr *> A = GSE->getAssocExprs();
16118 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16119 unsigned ResultIdx = GSE->getResultIndex();
16120 AssocExprs[ResultIdx] = SubExpr.get();
16121
16122 if (GSE->isExprPredicate())
16123 return GenericSelectionExpr::Create(
16124 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
16125 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
16126 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
16127 ResultIndex: ResultIdx);
16128 return GenericSelectionExpr::Create(
16129 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
16130 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
16131 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
16132 ResultIndex: ResultIdx);
16133 }
16134 // Rather than fall through to the unreachable, return the original generic
16135 // selection expression.
16136 return GSE;
16137 }
16138
16139 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
16140 assert(UnOp->getOpcode() == UO_AddrOf &&
16141 "Can only take the address of an overloaded function");
16142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
16143 if (!Method->isImplicitObjectMemberFunction()) {
16144 // Do nothing: the address of static and
16145 // explicit object member functions is a (non-member) function pointer.
16146 } else {
16147 // Fix the subexpression, which really has to be an
16148 // UnresolvedLookupExpr holding an overloaded member function
16149 // or template.
16150 ExprResult SubExpr =
16151 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
16152 if (SubExpr.isInvalid())
16153 return ExprError();
16154 if (SubExpr.get() == UnOp->getSubExpr())
16155 return UnOp;
16156
16157 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
16158 Op: SubExpr.get(), MD: Method))
16159 return ExprError();
16160
16161 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16162 "fixed to something other than a decl ref");
16163 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16164 "fixed to a member ref with no nested name qualifier");
16165
16166 // We have taken the address of a pointer to member
16167 // function. Perform the computation here so that we get the
16168 // appropriate pointer to member type.
16169 QualType ClassType
16170 = Context.getTypeDeclType(Decl: cast<RecordDecl>(Val: Method->getDeclContext()));
16171 QualType MemPtrType
16172 = Context.getMemberPointerType(T: Fn->getType(), Cls: ClassType.getTypePtr());
16173 // Under the MS ABI, lock down the inheritance model now.
16174 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16175 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
16176
16177 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
16178 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
16179 l: UnOp->getOperatorLoc(), CanOverflow: false,
16180 FPFeatures: CurFPFeatureOverrides());
16181 }
16182 }
16183 ExprResult SubExpr =
16184 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
16185 if (SubExpr.isInvalid())
16186 return ExprError();
16187 if (SubExpr.get() == UnOp->getSubExpr())
16188 return UnOp;
16189
16190 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
16191 InputExpr: SubExpr.get());
16192 }
16193
16194 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16195 // FIXME: avoid copy.
16196 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16197 if (ULE->hasExplicitTemplateArgs()) {
16198 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16199 TemplateArgs = &TemplateArgsBuffer;
16200 }
16201
16202 QualType Type = Fn->getType();
16203 ExprValueKind ValueKind =
16204 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16205 ? VK_LValue
16206 : VK_PRValue;
16207
16208 // FIXME: Duplicated from BuildDeclarationNameExpr.
16209 if (unsigned BID = Fn->getBuiltinID()) {
16210 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
16211 Type = Context.BuiltinFnTy;
16212 ValueKind = VK_PRValue;
16213 }
16214 }
16215
16216 DeclRefExpr *DRE = BuildDeclRefExpr(
16217 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
16218 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
16219 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16220 return DRE;
16221 }
16222
16223 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
16224 // FIXME: avoid copy.
16225 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16226 if (MemExpr->hasExplicitTemplateArgs()) {
16227 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16228 TemplateArgs = &TemplateArgsBuffer;
16229 }
16230
16231 Expr *Base;
16232
16233 // If we're filling in a static method where we used to have an
16234 // implicit member access, rewrite to a simple decl ref.
16235 if (MemExpr->isImplicitAccess()) {
16236 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
16237 DeclRefExpr *DRE = BuildDeclRefExpr(
16238 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
16239 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
16240 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16241 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16242 return DRE;
16243 } else {
16244 SourceLocation Loc = MemExpr->getMemberLoc();
16245 if (MemExpr->getQualifier())
16246 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16247 Base =
16248 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
16249 }
16250 } else
16251 Base = MemExpr->getBase();
16252
16253 ExprValueKind valueKind;
16254 QualType type;
16255 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
16256 valueKind = VK_LValue;
16257 type = Fn->getType();
16258 } else {
16259 valueKind = VK_PRValue;
16260 type = Context.BoundMemberTy;
16261 }
16262
16263 return BuildMemberExpr(
16264 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
16265 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
16266 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
16267 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
16268 }
16269
16270 llvm_unreachable("Invalid reference to overloaded function");
16271}
16272
16273ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
16274 DeclAccessPair Found,
16275 FunctionDecl *Fn) {
16276 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
16277}
16278
16279bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16280 FunctionDecl *Function) {
16281 if (!PartialOverloading || !Function)
16282 return true;
16283 if (Function->isVariadic())
16284 return false;
16285 if (const auto *Proto =
16286 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
16287 if (Proto->isTemplateVariadic())
16288 return false;
16289 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16290 if (const auto *Proto =
16291 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
16292 if (Proto->isTemplateVariadic())
16293 return false;
16294 return true;
16295}
16296
16297void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
16298 DeclarationName Name,
16299 OverloadCandidateSet &CandidateSet,
16300 FunctionDecl *Fn, MultiExprArg Args,
16301 bool IsMember) {
16302 StringLiteral *Msg = Fn->getDeletedMessage();
16303 CandidateSet.NoteCandidates(
16304 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
16305 << IsMember << Name << (Msg != nullptr)
16306 << (Msg ? Msg->getString() : StringRef())
16307 << Range),
16308 S&: *this, OCD: OCD_AllCandidates, Args);
16309}
16310