1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file provides Sema routines for C++ overloading.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DependenceFlags.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeOrdering.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/OperatorKinds.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/Support/Casting.h"
48 using namespace clang
;
51 using AllowedExplicit
= Sema::AllowedExplicit
;
53 static bool functionHasPassObjectSizeParams(const FunctionDecl
*FD
) {
54 return llvm::any_of(FD
->parameters(), [](const ParmVarDecl
*P
) {
55 return P
->hasAttr
<PassObjectSizeAttr
>();
59 /// A convenience routine for creating a decayed reference to a function.
60 static ExprResult
CreateFunctionRefExpr(
61 Sema
&S
, FunctionDecl
*Fn
, NamedDecl
*FoundDecl
, const Expr
*Base
,
62 bool HadMultipleCandidates
, SourceLocation Loc
= SourceLocation(),
63 const DeclarationNameLoc
&LocInfo
= DeclarationNameLoc()) {
64 if (S
.DiagnoseUseOfDecl(FoundDecl
, Loc
))
66 // If FoundDecl is different from Fn (such as if one is a template
67 // and the other a specialization), make sure DiagnoseUseOfDecl is
69 // FIXME: This would be more comprehensively addressed by modifying
70 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
72 if (FoundDecl
!= Fn
&& S
.DiagnoseUseOfDecl(Fn
, Loc
))
74 DeclRefExpr
*DRE
= new (S
.Context
)
75 DeclRefExpr(S
.Context
, Fn
, false, Fn
->getType(), VK_LValue
, Loc
, LocInfo
);
76 if (HadMultipleCandidates
)
77 DRE
->setHadMultipleCandidates(true);
79 S
.MarkDeclRefReferenced(DRE
, Base
);
80 if (auto *FPT
= DRE
->getType()->getAs
<FunctionProtoType
>()) {
81 if (isUnresolvedExceptionSpec(FPT
->getExceptionSpecType())) {
82 S
.ResolveExceptionSpec(Loc
, FPT
);
83 DRE
->setType(Fn
->getType());
86 return S
.ImpCastExprToType(DRE
, S
.Context
.getPointerType(DRE
->getType()),
87 CK_FunctionToPointerDecay
);
90 static bool IsStandardConversion(Sema
&S
, Expr
* From
, QualType ToType
,
91 bool InOverloadResolution
,
92 StandardConversionSequence
&SCS
,
94 bool AllowObjCWritebackConversion
);
96 static bool IsTransparentUnionStandardConversion(Sema
&S
, Expr
* From
,
98 bool InOverloadResolution
,
99 StandardConversionSequence
&SCS
,
101 static OverloadingResult
102 IsUserDefinedConversion(Sema
&S
, Expr
*From
, QualType ToType
,
103 UserDefinedConversionSequence
& User
,
104 OverloadCandidateSet
& Conversions
,
105 AllowedExplicit AllowExplicit
,
106 bool AllowObjCConversionOnExplicit
);
108 static ImplicitConversionSequence::CompareKind
109 CompareStandardConversionSequences(Sema
&S
, SourceLocation Loc
,
110 const StandardConversionSequence
& SCS1
,
111 const StandardConversionSequence
& SCS2
);
113 static ImplicitConversionSequence::CompareKind
114 CompareQualificationConversions(Sema
&S
,
115 const StandardConversionSequence
& SCS1
,
116 const StandardConversionSequence
& SCS2
);
118 static ImplicitConversionSequence::CompareKind
119 CompareDerivedToBaseConversions(Sema
&S
, SourceLocation Loc
,
120 const StandardConversionSequence
& SCS1
,
121 const StandardConversionSequence
& SCS2
);
123 /// GetConversionRank - Retrieve the implicit conversion rank
124 /// corresponding to the given implicit conversion kind.
125 ImplicitConversionRank
clang::GetConversionRank(ImplicitConversionKind Kind
) {
126 static const ImplicitConversionRank
149 ICR_OCL_Scalar_Widening
,
150 ICR_Complex_Real_Conversion
,
153 ICR_Writeback_Conversion
,
154 ICR_Exact_Match
, // NOTE(gbiv): This may not be completely right --
155 // it was omitted by the patch that added
156 // ICK_Zero_Event_Conversion
157 ICR_Exact_Match
, // NOTE(ctopper): This may not be completely right --
158 // it was omitted by the patch that added
159 // ICK_Zero_Queue_Conversion
161 ICR_C_Conversion_Extension
163 static_assert(std::size(Rank
) == (int)ICK_Num_Conversion_Kinds
);
164 return Rank
[(int)Kind
];
167 /// GetImplicitConversionName - Return the name of this kind of
168 /// implicit conversion.
169 static const char* GetImplicitConversionName(ImplicitConversionKind Kind
) {
170 static const char* const Name
[] = {
174 "Function-to-pointer",
175 "Function pointer conversion",
177 "Integral promotion",
178 "Floating point promotion",
180 "Integral conversion",
181 "Floating conversion",
182 "Complex conversion",
183 "Floating-integral conversion",
184 "Pointer conversion",
185 "Pointer-to-member conversion",
186 "Boolean conversion",
187 "Compatible-types conversion",
188 "Derived-to-base conversion",
190 "SVE Vector conversion",
191 "RVV Vector conversion",
193 "Complex-real conversion",
194 "Block Pointer conversion",
195 "Transparent Union Conversion",
196 "Writeback conversion",
197 "OpenCL Zero Event Conversion",
198 "OpenCL Zero Queue Conversion",
199 "C specific type conversion",
200 "Incompatible pointer conversion"
202 static_assert(std::size(Name
) == (int)ICK_Num_Conversion_Kinds
);
206 /// StandardConversionSequence - Set the standard conversion
207 /// sequence to the identity conversion.
208 void StandardConversionSequence::setAsIdentityConversion() {
209 First
= ICK_Identity
;
210 Second
= ICK_Identity
;
211 Third
= ICK_Identity
;
212 DeprecatedStringLiteralToCharPtr
= false;
213 QualificationIncludesObjCLifetime
= false;
214 ReferenceBinding
= false;
215 DirectBinding
= false;
216 IsLvalueReference
= true;
217 BindsToFunctionLvalue
= false;
218 BindsToRvalue
= false;
219 BindsImplicitObjectArgumentWithoutRefQualifier
= false;
220 ObjCLifetimeConversionBinding
= false;
221 CopyConstructor
= nullptr;
224 /// getRank - Retrieve the rank of this standard conversion sequence
225 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
226 /// implicit conversions.
227 ImplicitConversionRank
StandardConversionSequence::getRank() const {
228 ImplicitConversionRank Rank
= ICR_Exact_Match
;
229 if (GetConversionRank(First
) > Rank
)
230 Rank
= GetConversionRank(First
);
231 if (GetConversionRank(Second
) > Rank
)
232 Rank
= GetConversionRank(Second
);
233 if (GetConversionRank(Third
) > Rank
)
234 Rank
= GetConversionRank(Third
);
238 /// isPointerConversionToBool - Determines whether this conversion is
239 /// a conversion of a pointer or pointer-to-member to bool. This is
240 /// used as part of the ranking of standard conversion sequences
241 /// (C++ 13.3.3.2p4).
242 bool StandardConversionSequence::isPointerConversionToBool() const {
243 // Note that FromType has not necessarily been transformed by the
244 // array-to-pointer or function-to-pointer implicit conversions, so
245 // check for their presence as well as checking whether FromType is
247 if (getToType(1)->isBooleanType() &&
248 (getFromType()->isPointerType() ||
249 getFromType()->isMemberPointerType() ||
250 getFromType()->isObjCObjectPointerType() ||
251 getFromType()->isBlockPointerType() ||
252 First
== ICK_Array_To_Pointer
|| First
== ICK_Function_To_Pointer
))
258 /// isPointerConversionToVoidPointer - Determines whether this
259 /// conversion is a conversion of a pointer to a void pointer. This is
260 /// used as part of the ranking of standard conversion sequences (C++
263 StandardConversionSequence::
264 isPointerConversionToVoidPointer(ASTContext
& Context
) const {
265 QualType FromType
= getFromType();
266 QualType ToType
= getToType(1);
268 // Note that FromType has not necessarily been transformed by the
269 // array-to-pointer implicit conversion, so check for its presence
270 // and redo the conversion to get a pointer.
271 if (First
== ICK_Array_To_Pointer
)
272 FromType
= Context
.getArrayDecayedType(FromType
);
274 if (Second
== ICK_Pointer_Conversion
&& FromType
->isAnyPointerType())
275 if (const PointerType
* ToPtrType
= ToType
->getAs
<PointerType
>())
276 return ToPtrType
->getPointeeType()->isVoidType();
281 /// Skip any implicit casts which could be either part of a narrowing conversion
282 /// or after one in an implicit conversion.
283 static const Expr
*IgnoreNarrowingConversion(ASTContext
&Ctx
,
284 const Expr
*Converted
) {
285 // We can have cleanups wrapping the converted expression; these need to be
286 // preserved so that destructors run if necessary.
287 if (auto *EWC
= dyn_cast
<ExprWithCleanups
>(Converted
)) {
289 const_cast<Expr
*>(IgnoreNarrowingConversion(Ctx
, EWC
->getSubExpr()));
290 return ExprWithCleanups::Create(Ctx
, Inner
, EWC
->cleanupsHaveSideEffects(),
294 while (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(Converted
)) {
295 switch (ICE
->getCastKind()) {
297 case CK_IntegralCast
:
298 case CK_IntegralToBoolean
:
299 case CK_IntegralToFloating
:
300 case CK_BooleanToSignedIntegral
:
301 case CK_FloatingToIntegral
:
302 case CK_FloatingToBoolean
:
303 case CK_FloatingCast
:
304 Converted
= ICE
->getSubExpr();
315 /// Check if this standard conversion sequence represents a narrowing
316 /// conversion, according to C++11 [dcl.init.list]p7.
318 /// \param Ctx The AST context.
319 /// \param Converted The result of applying this standard conversion sequence.
320 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
321 /// value of the expression prior to the narrowing conversion.
322 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
323 /// type of the expression prior to the narrowing conversion.
324 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
325 /// from floating point types to integral types should be ignored.
326 NarrowingKind
StandardConversionSequence::getNarrowingKind(
327 ASTContext
&Ctx
, const Expr
*Converted
, APValue
&ConstantValue
,
328 QualType
&ConstantType
, bool IgnoreFloatToIntegralConversion
) const {
329 assert(Ctx
.getLangOpts().CPlusPlus
&& "narrowing check outside C++");
331 // C++11 [dcl.init.list]p7:
332 // A narrowing conversion is an implicit conversion ...
333 QualType FromType
= getToType(0);
334 QualType ToType
= getToType(1);
336 // A conversion to an enumeration type is narrowing if the conversion to
337 // the underlying type is narrowing. This only arises for expressions of
338 // the form 'Enum{init}'.
339 if (auto *ET
= ToType
->getAs
<EnumType
>())
340 ToType
= ET
->getDecl()->getIntegerType();
343 // 'bool' is an integral type; dispatch to the right place to handle it.
344 case ICK_Boolean_Conversion
:
345 if (FromType
->isRealFloatingType())
346 goto FloatingIntegralConversion
;
347 if (FromType
->isIntegralOrUnscopedEnumerationType())
348 goto IntegralConversion
;
349 // -- from a pointer type or pointer-to-member type to bool, or
350 return NK_Type_Narrowing
;
352 // -- from a floating-point type to an integer type, or
354 // -- from an integer type or unscoped enumeration type to a floating-point
355 // type, except where the source is a constant expression and the actual
356 // value after conversion will fit into the target type and will produce
357 // the original value when converted back to the original type, or
358 case ICK_Floating_Integral
:
359 FloatingIntegralConversion
:
360 if (FromType
->isRealFloatingType() && ToType
->isIntegralType(Ctx
)) {
361 return NK_Type_Narrowing
;
362 } else if (FromType
->isIntegralOrUnscopedEnumerationType() &&
363 ToType
->isRealFloatingType()) {
364 if (IgnoreFloatToIntegralConversion
)
365 return NK_Not_Narrowing
;
366 const Expr
*Initializer
= IgnoreNarrowingConversion(Ctx
, Converted
);
367 assert(Initializer
&& "Unknown conversion expression");
369 // If it's value-dependent, we can't tell whether it's narrowing.
370 if (Initializer
->isValueDependent())
371 return NK_Dependent_Narrowing
;
373 if (std::optional
<llvm::APSInt
> IntConstantValue
=
374 Initializer
->getIntegerConstantExpr(Ctx
)) {
375 // Convert the integer to the floating type.
376 llvm::APFloat
Result(Ctx
.getFloatTypeSemantics(ToType
));
377 Result
.convertFromAPInt(*IntConstantValue
, IntConstantValue
->isSigned(),
378 llvm::APFloat::rmNearestTiesToEven
);
380 llvm::APSInt ConvertedValue
= *IntConstantValue
;
382 Result
.convertToInteger(ConvertedValue
,
383 llvm::APFloat::rmTowardZero
, &ignored
);
384 // If the resulting value is different, this was a narrowing conversion.
385 if (*IntConstantValue
!= ConvertedValue
) {
386 ConstantValue
= APValue(*IntConstantValue
);
387 ConstantType
= Initializer
->getType();
388 return NK_Constant_Narrowing
;
391 // Variables are always narrowings.
392 return NK_Variable_Narrowing
;
395 return NK_Not_Narrowing
;
397 // -- from long double to double or float, or from double to float, except
398 // where the source is a constant expression and the actual value after
399 // conversion is within the range of values that can be represented (even
400 // if it cannot be represented exactly), or
401 case ICK_Floating_Conversion
:
402 if (FromType
->isRealFloatingType() && ToType
->isRealFloatingType() &&
403 Ctx
.getFloatingTypeOrder(FromType
, ToType
) == 1) {
404 // FromType is larger than ToType.
405 const Expr
*Initializer
= IgnoreNarrowingConversion(Ctx
, Converted
);
407 // If it's value-dependent, we can't tell whether it's narrowing.
408 if (Initializer
->isValueDependent())
409 return NK_Dependent_Narrowing
;
411 if (Initializer
->isCXX11ConstantExpr(Ctx
, &ConstantValue
)) {
413 assert(ConstantValue
.isFloat());
414 llvm::APFloat FloatVal
= ConstantValue
.getFloat();
415 // Convert the source value into the target type.
417 llvm::APFloat::opStatus ConvertStatus
= FloatVal
.convert(
418 Ctx
.getFloatTypeSemantics(ToType
),
419 llvm::APFloat::rmNearestTiesToEven
, &ignored
);
420 // If there was no overflow, the source value is within the range of
421 // values that can be represented.
422 if (ConvertStatus
& llvm::APFloat::opOverflow
) {
423 ConstantType
= Initializer
->getType();
424 return NK_Constant_Narrowing
;
427 return NK_Variable_Narrowing
;
430 return NK_Not_Narrowing
;
432 // -- from an integer type or unscoped enumeration type to an integer type
433 // that cannot represent all the values of the original type, except where
434 // the source is a constant expression and the actual value after
435 // conversion will fit into the target type and will produce the original
436 // value when converted back to the original type.
437 case ICK_Integral_Conversion
:
438 IntegralConversion
: {
439 assert(FromType
->isIntegralOrUnscopedEnumerationType());
440 assert(ToType
->isIntegralOrUnscopedEnumerationType());
441 const bool FromSigned
= FromType
->isSignedIntegerOrEnumerationType();
442 const unsigned FromWidth
= Ctx
.getIntWidth(FromType
);
443 const bool ToSigned
= ToType
->isSignedIntegerOrEnumerationType();
444 const unsigned ToWidth
= Ctx
.getIntWidth(ToType
);
446 if (FromWidth
> ToWidth
||
447 (FromWidth
== ToWidth
&& FromSigned
!= ToSigned
) ||
448 (FromSigned
&& !ToSigned
)) {
449 // Not all values of FromType can be represented in ToType.
450 const Expr
*Initializer
= IgnoreNarrowingConversion(Ctx
, Converted
);
452 // If it's value-dependent, we can't tell whether it's narrowing.
453 if (Initializer
->isValueDependent())
454 return NK_Dependent_Narrowing
;
456 std::optional
<llvm::APSInt
> OptInitializerValue
;
457 if (!(OptInitializerValue
= Initializer
->getIntegerConstantExpr(Ctx
))) {
458 // Such conversions on variables are always narrowing.
459 return NK_Variable_Narrowing
;
461 llvm::APSInt
&InitializerValue
= *OptInitializerValue
;
462 bool Narrowing
= false;
463 if (FromWidth
< ToWidth
) {
464 // Negative -> unsigned is narrowing. Otherwise, more bits is never
466 if (InitializerValue
.isSigned() && InitializerValue
.isNegative())
469 // Add a bit to the InitializerValue so we don't have to worry about
470 // signed vs. unsigned comparisons.
471 InitializerValue
= InitializerValue
.extend(
472 InitializerValue
.getBitWidth() + 1);
473 // Convert the initializer to and from the target width and signed-ness.
474 llvm::APSInt ConvertedValue
= InitializerValue
;
475 ConvertedValue
= ConvertedValue
.trunc(ToWidth
);
476 ConvertedValue
.setIsSigned(ToSigned
);
477 ConvertedValue
= ConvertedValue
.extend(InitializerValue
.getBitWidth());
478 ConvertedValue
.setIsSigned(InitializerValue
.isSigned());
479 // If the result is different, this was a narrowing conversion.
480 if (ConvertedValue
!= InitializerValue
)
484 ConstantType
= Initializer
->getType();
485 ConstantValue
= APValue(InitializerValue
);
486 return NK_Constant_Narrowing
;
489 return NK_Not_Narrowing
;
493 // Other kinds of conversions are not narrowings.
494 return NK_Not_Narrowing
;
498 /// dump - Print this standard conversion sequence to standard
499 /// error. Useful for debugging overloading issues.
500 LLVM_DUMP_METHOD
void StandardConversionSequence::dump() const {
501 raw_ostream
&OS
= llvm::errs();
502 bool PrintedSomething
= false;
503 if (First
!= ICK_Identity
) {
504 OS
<< GetImplicitConversionName(First
);
505 PrintedSomething
= true;
508 if (Second
!= ICK_Identity
) {
509 if (PrintedSomething
) {
512 OS
<< GetImplicitConversionName(Second
);
514 if (CopyConstructor
) {
515 OS
<< " (by copy constructor)";
516 } else if (DirectBinding
) {
517 OS
<< " (direct reference binding)";
518 } else if (ReferenceBinding
) {
519 OS
<< " (reference binding)";
521 PrintedSomething
= true;
524 if (Third
!= ICK_Identity
) {
525 if (PrintedSomething
) {
528 OS
<< GetImplicitConversionName(Third
);
529 PrintedSomething
= true;
532 if (!PrintedSomething
) {
533 OS
<< "No conversions required";
537 /// dump - Print this user-defined conversion sequence to standard
538 /// error. Useful for debugging overloading issues.
539 void UserDefinedConversionSequence::dump() const {
540 raw_ostream
&OS
= llvm::errs();
541 if (Before
.First
|| Before
.Second
|| Before
.Third
) {
545 if (ConversionFunction
)
546 OS
<< '\'' << *ConversionFunction
<< '\'';
548 OS
<< "aggregate initialization";
549 if (After
.First
|| After
.Second
|| After
.Third
) {
555 /// dump - Print this implicit conversion sequence to standard
556 /// error. Useful for debugging overloading issues.
557 void ImplicitConversionSequence::dump() const {
558 raw_ostream
&OS
= llvm::errs();
559 if (hasInitializerListContainerType())
560 OS
<< "Worst list element conversion: ";
561 switch (ConversionKind
) {
562 case StandardConversion
:
563 OS
<< "Standard conversion: ";
566 case UserDefinedConversion
:
567 OS
<< "User-defined conversion: ";
570 case EllipsisConversion
:
571 OS
<< "Ellipsis conversion";
573 case AmbiguousConversion
:
574 OS
<< "Ambiguous conversion";
577 OS
<< "Bad conversion";
584 void AmbiguousConversionSequence::construct() {
585 new (&conversions()) ConversionSet();
588 void AmbiguousConversionSequence::destruct() {
589 conversions().~ConversionSet();
593 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence
&O
) {
594 FromTypePtr
= O
.FromTypePtr
;
595 ToTypePtr
= O
.ToTypePtr
;
596 new (&conversions()) ConversionSet(O
.conversions());
600 // Structure used by DeductionFailureInfo to store
601 // template argument information.
602 struct DFIArguments
{
603 TemplateArgument FirstArg
;
604 TemplateArgument SecondArg
;
606 // Structure used by DeductionFailureInfo to store
607 // template parameter and template argument information.
608 struct DFIParamWithArguments
: DFIArguments
{
609 TemplateParameter Param
;
611 // Structure used by DeductionFailureInfo to store template argument
612 // information and the index of the problematic call argument.
613 struct DFIDeducedMismatchArgs
: DFIArguments
{
614 TemplateArgumentList
*TemplateArgs
;
615 unsigned CallArgIndex
;
617 // Structure used by DeductionFailureInfo to store information about
618 // unsatisfied constraints.
620 TemplateArgumentList
*TemplateArgs
;
621 ConstraintSatisfaction Satisfaction
;
625 /// Convert from Sema's representation of template deduction information
626 /// to the form used in overload-candidate information.
628 clang::MakeDeductionFailureInfo(ASTContext
&Context
,
629 Sema::TemplateDeductionResult TDK
,
630 TemplateDeductionInfo
&Info
) {
631 DeductionFailureInfo Result
;
632 Result
.Result
= static_cast<unsigned>(TDK
);
633 Result
.HasDiagnostic
= false;
635 case Sema::TDK_Invalid
:
636 case Sema::TDK_InstantiationDepth
:
637 case Sema::TDK_TooManyArguments
:
638 case Sema::TDK_TooFewArguments
:
639 case Sema::TDK_MiscellaneousDeductionFailure
:
640 case Sema::TDK_CUDATargetMismatch
:
641 Result
.Data
= nullptr;
644 case Sema::TDK_Incomplete
:
645 case Sema::TDK_InvalidExplicitArguments
:
646 Result
.Data
= Info
.Param
.getOpaqueValue();
649 case Sema::TDK_DeducedMismatch
:
650 case Sema::TDK_DeducedMismatchNested
: {
651 // FIXME: Should allocate from normal heap so that we can free this later.
652 auto *Saved
= new (Context
) DFIDeducedMismatchArgs
;
653 Saved
->FirstArg
= Info
.FirstArg
;
654 Saved
->SecondArg
= Info
.SecondArg
;
655 Saved
->TemplateArgs
= Info
.takeSugared();
656 Saved
->CallArgIndex
= Info
.CallArgIndex
;
661 case Sema::TDK_NonDeducedMismatch
: {
662 // FIXME: Should allocate from normal heap so that we can free this later.
663 DFIArguments
*Saved
= new (Context
) DFIArguments
;
664 Saved
->FirstArg
= Info
.FirstArg
;
665 Saved
->SecondArg
= Info
.SecondArg
;
670 case Sema::TDK_IncompletePack
:
671 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
672 case Sema::TDK_Inconsistent
:
673 case Sema::TDK_Underqualified
: {
674 // FIXME: Should allocate from normal heap so that we can free this later.
675 DFIParamWithArguments
*Saved
= new (Context
) DFIParamWithArguments
;
676 Saved
->Param
= Info
.Param
;
677 Saved
->FirstArg
= Info
.FirstArg
;
678 Saved
->SecondArg
= Info
.SecondArg
;
683 case Sema::TDK_SubstitutionFailure
:
684 Result
.Data
= Info
.takeSugared();
685 if (Info
.hasSFINAEDiagnostic()) {
686 PartialDiagnosticAt
*Diag
= new (Result
.Diagnostic
) PartialDiagnosticAt(
687 SourceLocation(), PartialDiagnostic::NullDiagnostic());
688 Info
.takeSFINAEDiagnostic(*Diag
);
689 Result
.HasDiagnostic
= true;
693 case Sema::TDK_ConstraintsNotSatisfied
: {
694 CNSInfo
*Saved
= new (Context
) CNSInfo
;
695 Saved
->TemplateArgs
= Info
.takeSugared();
696 Saved
->Satisfaction
= Info
.AssociatedConstraintsSatisfaction
;
701 case Sema::TDK_Success
:
702 case Sema::TDK_NonDependentConversionFailure
:
703 case Sema::TDK_AlreadyDiagnosed
:
704 llvm_unreachable("not a deduction failure");
710 void DeductionFailureInfo::Destroy() {
711 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
712 case Sema::TDK_Success
:
713 case Sema::TDK_Invalid
:
714 case Sema::TDK_InstantiationDepth
:
715 case Sema::TDK_Incomplete
:
716 case Sema::TDK_TooManyArguments
:
717 case Sema::TDK_TooFewArguments
:
718 case Sema::TDK_InvalidExplicitArguments
:
719 case Sema::TDK_CUDATargetMismatch
:
720 case Sema::TDK_NonDependentConversionFailure
:
723 case Sema::TDK_IncompletePack
:
724 case Sema::TDK_Inconsistent
:
725 case Sema::TDK_Underqualified
:
726 case Sema::TDK_DeducedMismatch
:
727 case Sema::TDK_DeducedMismatchNested
:
728 case Sema::TDK_NonDeducedMismatch
:
729 // FIXME: Destroy the data?
733 case Sema::TDK_SubstitutionFailure
:
734 // FIXME: Destroy the template argument list?
736 if (PartialDiagnosticAt
*Diag
= getSFINAEDiagnostic()) {
737 Diag
->~PartialDiagnosticAt();
738 HasDiagnostic
= false;
742 case Sema::TDK_ConstraintsNotSatisfied
:
743 // FIXME: Destroy the template argument list?
745 if (PartialDiagnosticAt
*Diag
= getSFINAEDiagnostic()) {
746 Diag
->~PartialDiagnosticAt();
747 HasDiagnostic
= false;
752 case Sema::TDK_MiscellaneousDeductionFailure
:
753 case Sema::TDK_AlreadyDiagnosed
:
758 PartialDiagnosticAt
*DeductionFailureInfo::getSFINAEDiagnostic() {
760 return static_cast<PartialDiagnosticAt
*>(static_cast<void*>(Diagnostic
));
764 TemplateParameter
DeductionFailureInfo::getTemplateParameter() {
765 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
766 case Sema::TDK_Success
:
767 case Sema::TDK_Invalid
:
768 case Sema::TDK_InstantiationDepth
:
769 case Sema::TDK_TooManyArguments
:
770 case Sema::TDK_TooFewArguments
:
771 case Sema::TDK_SubstitutionFailure
:
772 case Sema::TDK_DeducedMismatch
:
773 case Sema::TDK_DeducedMismatchNested
:
774 case Sema::TDK_NonDeducedMismatch
:
775 case Sema::TDK_CUDATargetMismatch
:
776 case Sema::TDK_NonDependentConversionFailure
:
777 case Sema::TDK_ConstraintsNotSatisfied
:
778 return TemplateParameter();
780 case Sema::TDK_Incomplete
:
781 case Sema::TDK_InvalidExplicitArguments
:
782 return TemplateParameter::getFromOpaqueValue(Data
);
784 case Sema::TDK_IncompletePack
:
785 case Sema::TDK_Inconsistent
:
786 case Sema::TDK_Underqualified
:
787 return static_cast<DFIParamWithArguments
*>(Data
)->Param
;
790 case Sema::TDK_MiscellaneousDeductionFailure
:
791 case Sema::TDK_AlreadyDiagnosed
:
795 return TemplateParameter();
798 TemplateArgumentList
*DeductionFailureInfo::getTemplateArgumentList() {
799 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
800 case Sema::TDK_Success
:
801 case Sema::TDK_Invalid
:
802 case Sema::TDK_InstantiationDepth
:
803 case Sema::TDK_TooManyArguments
:
804 case Sema::TDK_TooFewArguments
:
805 case Sema::TDK_Incomplete
:
806 case Sema::TDK_IncompletePack
:
807 case Sema::TDK_InvalidExplicitArguments
:
808 case Sema::TDK_Inconsistent
:
809 case Sema::TDK_Underqualified
:
810 case Sema::TDK_NonDeducedMismatch
:
811 case Sema::TDK_CUDATargetMismatch
:
812 case Sema::TDK_NonDependentConversionFailure
:
815 case Sema::TDK_DeducedMismatch
:
816 case Sema::TDK_DeducedMismatchNested
:
817 return static_cast<DFIDeducedMismatchArgs
*>(Data
)->TemplateArgs
;
819 case Sema::TDK_SubstitutionFailure
:
820 return static_cast<TemplateArgumentList
*>(Data
);
822 case Sema::TDK_ConstraintsNotSatisfied
:
823 return static_cast<CNSInfo
*>(Data
)->TemplateArgs
;
826 case Sema::TDK_MiscellaneousDeductionFailure
:
827 case Sema::TDK_AlreadyDiagnosed
:
834 const TemplateArgument
*DeductionFailureInfo::getFirstArg() {
835 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
836 case Sema::TDK_Success
:
837 case Sema::TDK_Invalid
:
838 case Sema::TDK_InstantiationDepth
:
839 case Sema::TDK_Incomplete
:
840 case Sema::TDK_TooManyArguments
:
841 case Sema::TDK_TooFewArguments
:
842 case Sema::TDK_InvalidExplicitArguments
:
843 case Sema::TDK_SubstitutionFailure
:
844 case Sema::TDK_CUDATargetMismatch
:
845 case Sema::TDK_NonDependentConversionFailure
:
846 case Sema::TDK_ConstraintsNotSatisfied
:
849 case Sema::TDK_IncompletePack
:
850 case Sema::TDK_Inconsistent
:
851 case Sema::TDK_Underqualified
:
852 case Sema::TDK_DeducedMismatch
:
853 case Sema::TDK_DeducedMismatchNested
:
854 case Sema::TDK_NonDeducedMismatch
:
855 return &static_cast<DFIArguments
*>(Data
)->FirstArg
;
858 case Sema::TDK_MiscellaneousDeductionFailure
:
859 case Sema::TDK_AlreadyDiagnosed
:
866 const TemplateArgument
*DeductionFailureInfo::getSecondArg() {
867 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
868 case Sema::TDK_Success
:
869 case Sema::TDK_Invalid
:
870 case Sema::TDK_InstantiationDepth
:
871 case Sema::TDK_Incomplete
:
872 case Sema::TDK_IncompletePack
:
873 case Sema::TDK_TooManyArguments
:
874 case Sema::TDK_TooFewArguments
:
875 case Sema::TDK_InvalidExplicitArguments
:
876 case Sema::TDK_SubstitutionFailure
:
877 case Sema::TDK_CUDATargetMismatch
:
878 case Sema::TDK_NonDependentConversionFailure
:
879 case Sema::TDK_ConstraintsNotSatisfied
:
882 case Sema::TDK_Inconsistent
:
883 case Sema::TDK_Underqualified
:
884 case Sema::TDK_DeducedMismatch
:
885 case Sema::TDK_DeducedMismatchNested
:
886 case Sema::TDK_NonDeducedMismatch
:
887 return &static_cast<DFIArguments
*>(Data
)->SecondArg
;
890 case Sema::TDK_MiscellaneousDeductionFailure
:
891 case Sema::TDK_AlreadyDiagnosed
:
898 std::optional
<unsigned> DeductionFailureInfo::getCallArgIndex() {
899 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
900 case Sema::TDK_DeducedMismatch
:
901 case Sema::TDK_DeducedMismatchNested
:
902 return static_cast<DFIDeducedMismatchArgs
*>(Data
)->CallArgIndex
;
909 static bool FunctionsCorrespond(ASTContext
&Ctx
, const FunctionDecl
*X
,
910 const FunctionDecl
*Y
) {
913 if (X
->getNumParams() != Y
->getNumParams())
915 // FIXME: when do rewritten comparison operators
916 // with explicit object parameters correspond?
917 // https://cplusplus.github.io/CWG/issues/2797.html
918 for (unsigned I
= 0; I
< X
->getNumParams(); ++I
)
919 if (!Ctx
.hasSameUnqualifiedType(X
->getParamDecl(I
)->getType(),
920 Y
->getParamDecl(I
)->getType()))
922 if (auto *FTX
= X
->getDescribedFunctionTemplate()) {
923 auto *FTY
= Y
->getDescribedFunctionTemplate();
926 if (!Ctx
.isSameTemplateParameterList(FTX
->getTemplateParameters(),
927 FTY
->getTemplateParameters()))
933 static bool shouldAddReversedEqEq(Sema
&S
, SourceLocation OpLoc
,
934 Expr
*FirstOperand
, FunctionDecl
*EqFD
) {
935 assert(EqFD
->getOverloadedOperator() ==
936 OverloadedOperatorKind::OO_EqualEqual
);
937 // C++2a [over.match.oper]p4:
938 // A non-template function or function template F named operator== is a
939 // rewrite target with first operand o unless a search for the name operator!=
940 // in the scope S from the instantiation context of the operator expression
941 // finds a function or function template that would correspond
942 // ([basic.scope.scope]) to F if its name were operator==, where S is the
943 // scope of the class type of o if F is a class member, and the namespace
944 // scope of which F is a member otherwise. A function template specialization
945 // named operator== is a rewrite target if its function template is a rewrite
947 DeclarationName NotEqOp
= S
.Context
.DeclarationNames
.getCXXOperatorName(
948 OverloadedOperatorKind::OO_ExclaimEqual
);
949 if (isa
<CXXMethodDecl
>(EqFD
)) {
950 // If F is a class member, search scope is class type of first operand.
951 QualType RHS
= FirstOperand
->getType();
952 auto *RHSRec
= RHS
->getAs
<RecordType
>();
955 LookupResult
Members(S
, NotEqOp
, OpLoc
,
956 Sema::LookupNameKind::LookupMemberName
);
957 S
.LookupQualifiedName(Members
, RHSRec
->getDecl());
958 Members
.suppressAccessDiagnostics();
959 for (NamedDecl
*Op
: Members
)
960 if (FunctionsCorrespond(S
.Context
, EqFD
, Op
->getAsFunction()))
964 // Otherwise the search scope is the namespace scope of which F is a member.
965 for (NamedDecl
*Op
: EqFD
->getEnclosingNamespaceContext()->lookup(NotEqOp
)) {
966 auto *NotEqFD
= Op
->getAsFunction();
967 if (auto *UD
= dyn_cast
<UsingShadowDecl
>(Op
))
968 NotEqFD
= UD
->getUnderlyingDecl()->getAsFunction();
969 if (FunctionsCorrespond(S
.Context
, EqFD
, NotEqFD
) && S
.isVisible(NotEqFD
) &&
970 declaresSameEntity(cast
<Decl
>(EqFD
->getEnclosingNamespaceContext()),
971 cast
<Decl
>(Op
->getLexicalDeclContext())))
977 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
978 OverloadedOperatorKind Op
) {
979 if (!AllowRewrittenCandidates
)
981 return Op
== OO_EqualEqual
|| Op
== OO_Spaceship
;
984 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
985 Sema
&S
, ArrayRef
<Expr
*> OriginalArgs
, FunctionDecl
*FD
) {
986 auto Op
= FD
->getOverloadedOperator();
987 if (!allowsReversed(Op
))
989 if (Op
== OverloadedOperatorKind::OO_EqualEqual
) {
990 assert(OriginalArgs
.size() == 2);
991 if (!shouldAddReversedEqEq(
992 S
, OpLoc
, /*FirstOperand in reversed args*/ OriginalArgs
[1], FD
))
995 // Don't bother adding a reversed candidate that can never be a better
996 // match than the non-reversed version.
997 return FD
->getNumNonObjectParams() != 2 ||
998 !S
.Context
.hasSameUnqualifiedType(FD
->getParamDecl(0)->getType(),
999 FD
->getParamDecl(1)->getType()) ||
1000 FD
->hasAttr
<EnableIfAttr
>();
1003 void OverloadCandidateSet::destroyCandidates() {
1004 for (iterator i
= begin(), e
= end(); i
!= e
; ++i
) {
1005 for (auto &C
: i
->Conversions
)
1006 C
.~ImplicitConversionSequence();
1007 if (!i
->Viable
&& i
->FailureKind
== ovl_fail_bad_deduction
)
1008 i
->DeductionFailure
.Destroy();
1012 void OverloadCandidateSet::clear(CandidateSetKind CSK
) {
1013 destroyCandidates();
1014 SlabAllocator
.Reset();
1015 NumInlineBytesUsed
= 0;
1022 class UnbridgedCastsSet
{
1027 SmallVector
<Entry
, 2> Entries
;
1030 void save(Sema
&S
, Expr
*&E
) {
1031 assert(E
->hasPlaceholderType(BuiltinType::ARCUnbridgedCast
));
1032 Entry entry
= { &E
, E
};
1033 Entries
.push_back(entry
);
1034 E
= S
.stripARCUnbridgedCast(E
);
1038 for (SmallVectorImpl
<Entry
>::iterator
1039 i
= Entries
.begin(), e
= Entries
.end(); i
!= e
; ++i
)
1040 *i
->Addr
= i
->Saved
;
1045 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1046 /// preprocessing on the given expression.
1048 /// \param unbridgedCasts a collection to which to add unbridged casts;
1049 /// without this, they will be immediately diagnosed as errors
1051 /// Return true on unrecoverable error.
1053 checkPlaceholderForOverload(Sema
&S
, Expr
*&E
,
1054 UnbridgedCastsSet
*unbridgedCasts
= nullptr) {
1055 if (const BuiltinType
*placeholder
= E
->getType()->getAsPlaceholderType()) {
1056 // We can't handle overloaded expressions here because overload
1057 // resolution might reasonably tweak them.
1058 if (placeholder
->getKind() == BuiltinType::Overload
) return false;
1060 // If the context potentially accepts unbridged ARC casts, strip
1061 // the unbridged cast and add it to the collection for later restoration.
1062 if (placeholder
->getKind() == BuiltinType::ARCUnbridgedCast
&&
1064 unbridgedCasts
->save(S
, E
);
1068 // Go ahead and check everything else.
1069 ExprResult result
= S
.CheckPlaceholderExpr(E
);
1070 if (result
.isInvalid())
1081 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1083 static bool checkArgPlaceholdersForOverload(Sema
&S
, MultiExprArg Args
,
1084 UnbridgedCastsSet
&unbridged
) {
1085 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
)
1086 if (checkPlaceholderForOverload(S
, Args
[i
], &unbridged
))
1092 /// Determine whether the given New declaration is an overload of the
1093 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1094 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1095 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1096 /// functions (or function templates) at all. When it does return Ovl_Match or
1097 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1098 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1101 /// Example: Given the following input:
1103 /// void f(int, float); // #1
1104 /// void f(int, int); // #2
1105 /// int f(int, int); // #3
1107 /// When we process #1, there is no previous declaration of "f", so IsOverload
1108 /// will not be used.
1110 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1111 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1112 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1115 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1116 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1117 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1118 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1119 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1121 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1122 /// by a using declaration. The rules for whether to hide shadow declarations
1123 /// ignore some properties which otherwise figure into a function template's
1126 Sema::CheckOverload(Scope
*S
, FunctionDecl
*New
, const LookupResult
&Old
,
1127 NamedDecl
*&Match
, bool NewIsUsingDecl
) {
1128 for (LookupResult::iterator I
= Old
.begin(), E
= Old
.end();
1130 NamedDecl
*OldD
= *I
;
1132 bool OldIsUsingDecl
= false;
1133 if (isa
<UsingShadowDecl
>(OldD
)) {
1134 OldIsUsingDecl
= true;
1136 // We can always introduce two using declarations into the same
1137 // context, even if they have identical signatures.
1138 if (NewIsUsingDecl
) continue;
1140 OldD
= cast
<UsingShadowDecl
>(OldD
)->getTargetDecl();
1143 // A using-declaration does not conflict with another declaration
1144 // if one of them is hidden.
1145 if ((OldIsUsingDecl
|| NewIsUsingDecl
) && !isVisible(*I
))
1148 // If either declaration was introduced by a using declaration,
1149 // we'll need to use slightly different rules for matching.
1150 // Essentially, these rules are the normal rules, except that
1151 // function templates hide function templates with different
1152 // return types or template parameter lists.
1153 bool UseMemberUsingDeclRules
=
1154 (OldIsUsingDecl
|| NewIsUsingDecl
) && CurContext
->isRecord() &&
1155 !New
->getFriendObjectKind();
1157 if (FunctionDecl
*OldF
= OldD
->getAsFunction()) {
1158 if (!IsOverload(New
, OldF
, UseMemberUsingDeclRules
)) {
1159 if (UseMemberUsingDeclRules
&& OldIsUsingDecl
) {
1160 HideUsingShadowDecl(S
, cast
<UsingShadowDecl
>(*I
));
1164 if (!isa
<FunctionTemplateDecl
>(OldD
) &&
1165 !shouldLinkPossiblyHiddenDecl(*I
, New
))
1172 // Builtins that have custom typechecking or have a reference should
1173 // not be overloadable or redeclarable.
1174 if (!getASTContext().canBuiltinBeRedeclared(OldF
)) {
1176 return Ovl_NonFunction
;
1178 } else if (isa
<UsingDecl
>(OldD
) || isa
<UsingPackDecl
>(OldD
)) {
1179 // We can overload with these, which can show up when doing
1180 // redeclaration checks for UsingDecls.
1181 assert(Old
.getLookupKind() == LookupUsingDeclName
);
1182 } else if (isa
<TagDecl
>(OldD
)) {
1183 // We can always overload with tags by hiding them.
1184 } else if (auto *UUD
= dyn_cast
<UnresolvedUsingValueDecl
>(OldD
)) {
1185 // Optimistically assume that an unresolved using decl will
1186 // overload; if it doesn't, we'll have to diagnose during
1187 // template instantiation.
1189 // Exception: if the scope is dependent and this is not a class
1190 // member, the using declaration can only introduce an enumerator.
1191 if (UUD
->getQualifier()->isDependent() && !UUD
->isCXXClassMember()) {
1193 return Ovl_NonFunction
;
1197 // Only function declarations can be overloaded; object and type
1198 // declarations cannot be overloaded.
1200 return Ovl_NonFunction
;
1204 // C++ [temp.friend]p1:
1205 // For a friend function declaration that is not a template declaration:
1206 // -- if the name of the friend is a qualified or unqualified template-id,
1208 // -- if the name of the friend is a qualified-id and a matching
1209 // non-template function is found in the specified class or namespace,
1210 // the friend declaration refers to that function, otherwise,
1211 // -- if the name of the friend is a qualified-id and a matching function
1212 // template is found in the specified class or namespace, the friend
1213 // declaration refers to the deduced specialization of that function
1214 // template, otherwise
1215 // -- the name shall be an unqualified-id [...]
1216 // If we get here for a qualified friend declaration, we've just reached the
1217 // third bullet. If the type of the friend is dependent, skip this lookup
1218 // until instantiation.
1219 if (New
->getFriendObjectKind() && New
->getQualifier() &&
1220 !New
->getDescribedFunctionTemplate() &&
1221 !New
->getDependentSpecializationInfo() &&
1222 !New
->getType()->isDependentType()) {
1223 LookupResult
TemplateSpecResult(LookupResult::Temporary
, Old
);
1224 TemplateSpecResult
.addAllDecls(Old
);
1225 if (CheckFunctionTemplateSpecialization(New
, nullptr, TemplateSpecResult
,
1226 /*QualifiedFriend*/true)) {
1227 New
->setInvalidDecl();
1228 return Ovl_Overload
;
1231 Match
= TemplateSpecResult
.getAsSingle
<FunctionDecl
>();
1235 return Ovl_Overload
;
1238 static bool IsOverloadOrOverrideImpl(Sema
&SemaRef
, FunctionDecl
*New
,
1240 bool UseMemberUsingDeclRules
,
1241 bool ConsiderCudaAttrs
,
1242 bool UseOverrideRules
= false) {
1243 // C++ [basic.start.main]p2: This function shall not be overloaded.
1247 // MSVCRT user defined entry points cannot be overloaded.
1248 if (New
->isMSVCRTEntryPoint())
1251 FunctionTemplateDecl
*OldTemplate
= Old
->getDescribedFunctionTemplate();
1252 FunctionTemplateDecl
*NewTemplate
= New
->getDescribedFunctionTemplate();
1254 // C++ [temp.fct]p2:
1255 // A function template can be overloaded with other function templates
1256 // and with normal (non-template) functions.
1257 if ((OldTemplate
== nullptr) != (NewTemplate
== nullptr))
1260 // Is the function New an overload of the function Old?
1261 QualType OldQType
= SemaRef
.Context
.getCanonicalType(Old
->getType());
1262 QualType NewQType
= SemaRef
.Context
.getCanonicalType(New
->getType());
1264 // Compare the signatures (C++ 1.3.10) of the two functions to
1265 // determine whether they are overloads. If we find any mismatch
1266 // in the signature, they are overloads.
1268 // If either of these functions is a K&R-style function (no
1269 // prototype), then we consider them to have matching signatures.
1270 if (isa
<FunctionNoProtoType
>(OldQType
.getTypePtr()) ||
1271 isa
<FunctionNoProtoType
>(NewQType
.getTypePtr()))
1274 const FunctionProtoType
*OldType
= cast
<FunctionProtoType
>(OldQType
);
1275 const FunctionProtoType
*NewType
= cast
<FunctionProtoType
>(NewQType
);
1277 // The signature of a function includes the types of its
1278 // parameters (C++ 1.3.10), which includes the presence or absence
1279 // of the ellipsis; see C++ DR 357).
1280 if (OldQType
!= NewQType
&& OldType
->isVariadic() != NewType
->isVariadic())
1283 // For member-like friends, the enclosing class is part of the signature.
1284 if ((New
->isMemberLikeConstrainedFriend() ||
1285 Old
->isMemberLikeConstrainedFriend()) &&
1286 !New
->getLexicalDeclContext()->Equals(Old
->getLexicalDeclContext()))
1288 const auto *OldMethod
= dyn_cast
<CXXMethodDecl
>(Old
);
1289 const auto *NewMethod
= dyn_cast
<CXXMethodDecl
>(New
);
1291 int OldParamsOffset
= 0;
1292 int NewParamsOffset
= 0;
1294 // When determining if a method is an overload from a base class, act as if
1295 // the implicit object parameter are of the same type.
1297 auto NormalizeQualifiers
= [&](const CXXMethodDecl
*M
, Qualifiers Q
) {
1298 if (M
->isExplicitObjectMemberFunction())
1301 // We do not allow overloading based off of '__restrict'.
1304 // We may not have applied the implicit const for a constexpr member
1305 // function yet (because we haven't yet resolved whether this is a static
1306 // or non-static member function). Add it now, on the assumption that this
1307 // is a redeclaration of OldMethod.
1308 if (!SemaRef
.getLangOpts().CPlusPlus14
&&
1309 (M
->isConstexpr() || M
->isConsteval()) &&
1310 !isa
<CXXConstructorDecl
>(NewMethod
))
1315 auto CompareType
= [&](QualType Base
, QualType D
) {
1316 auto BS
= Base
.getNonReferenceType().getCanonicalType().split();
1317 BS
.Quals
= NormalizeQualifiers(OldMethod
, BS
.Quals
);
1319 auto DS
= D
.getNonReferenceType().getCanonicalType().split();
1320 DS
.Quals
= NormalizeQualifiers(NewMethod
, DS
.Quals
);
1322 if (BS
.Quals
!= DS
.Quals
)
1325 if (OldMethod
->isImplicitObjectMemberFunction() &&
1326 OldMethod
->getParent() != NewMethod
->getParent()) {
1327 QualType ParentType
=
1328 SemaRef
.Context
.getTypeDeclType(OldMethod
->getParent())
1329 .getCanonicalType();
1330 if (ParentType
.getTypePtr() != BS
.Ty
)
1335 // FIXME: should we ignore some type attributes here?
1339 if (Base
->isLValueReferenceType())
1340 return D
->isLValueReferenceType();
1341 return Base
->isRValueReferenceType() == D
->isRValueReferenceType();
1344 // If the function is a class member, its signature includes the
1345 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1346 auto DiagnoseInconsistentRefQualifiers
= [&]() {
1347 if (SemaRef
.LangOpts
.CPlusPlus23
)
1349 if (OldMethod
->getRefQualifier() == NewMethod
->getRefQualifier())
1351 if (OldMethod
->isExplicitObjectMemberFunction() ||
1352 NewMethod
->isExplicitObjectMemberFunction())
1354 if (!UseMemberUsingDeclRules
&& (OldMethod
->getRefQualifier() == RQ_None
||
1355 NewMethod
->getRefQualifier() == RQ_None
)) {
1356 SemaRef
.Diag(NewMethod
->getLocation(), diag::err_ref_qualifier_overload
)
1357 << NewMethod
->getRefQualifier() << OldMethod
->getRefQualifier();
1358 SemaRef
.Diag(OldMethod
->getLocation(), diag::note_previous_declaration
);
1364 if (OldMethod
&& OldMethod
->isExplicitObjectMemberFunction())
1366 if (NewMethod
&& NewMethod
->isExplicitObjectMemberFunction())
1369 if (OldType
->getNumParams() - OldParamsOffset
!=
1370 NewType
->getNumParams() - NewParamsOffset
||
1371 !SemaRef
.FunctionParamTypesAreEqual(
1372 {OldType
->param_type_begin() + OldParamsOffset
,
1373 OldType
->param_type_end()},
1374 {NewType
->param_type_begin() + NewParamsOffset
,
1375 NewType
->param_type_end()},
1380 if (OldMethod
&& NewMethod
&& !OldMethod
->isStatic() &&
1381 !OldMethod
->isStatic()) {
1382 bool HaveCorrespondingObjectParameters
= [&](const CXXMethodDecl
*Old
,
1383 const CXXMethodDecl
*New
) {
1384 auto NewObjectType
= New
->getFunctionObjectParameterReferenceType();
1385 auto OldObjectType
= Old
->getFunctionObjectParameterReferenceType();
1387 auto IsImplicitWithNoRefQual
= [](const CXXMethodDecl
*F
) {
1388 return F
->getRefQualifier() == RQ_None
&&
1389 !F
->isExplicitObjectMemberFunction();
1392 if (IsImplicitWithNoRefQual(Old
) != IsImplicitWithNoRefQual(New
) &&
1393 CompareType(OldObjectType
.getNonReferenceType(),
1394 NewObjectType
.getNonReferenceType()))
1396 return CompareType(OldObjectType
, NewObjectType
);
1397 }(OldMethod
, NewMethod
);
1399 if (!HaveCorrespondingObjectParameters
) {
1400 if (DiagnoseInconsistentRefQualifiers())
1403 // and, if at least one is an explicit object member function, ignoring
1404 // object parameters
1405 if (!UseOverrideRules
|| (!NewMethod
->isExplicitObjectMemberFunction() &&
1406 !OldMethod
->isExplicitObjectMemberFunction()))
1412 // C++ [temp.over.link]p4:
1413 // The signature of a function template consists of its function
1414 // signature, its return type and its template parameter list. The names
1415 // of the template parameters are significant only for establishing the
1416 // relationship between the template parameters and the rest of the
1419 // We check the return type and template parameter lists for function
1420 // templates first; the remaining checks follow.
1421 bool SameTemplateParameterList
= SemaRef
.TemplateParameterListsAreEqual(
1422 NewTemplate
, NewTemplate
->getTemplateParameters(), OldTemplate
,
1423 OldTemplate
->getTemplateParameters(), false, Sema::TPL_TemplateMatch
);
1424 bool SameReturnType
= SemaRef
.Context
.hasSameType(
1425 Old
->getDeclaredReturnType(), New
->getDeclaredReturnType());
1426 // FIXME(GH58571): Match template parameter list even for non-constrained
1427 // template heads. This currently ensures that the code prior to C++20 is
1428 // not newly broken.
1429 bool ConstraintsInTemplateHead
=
1430 NewTemplate
->getTemplateParameters()->hasAssociatedConstraints() ||
1431 OldTemplate
->getTemplateParameters()->hasAssociatedConstraints();
1432 // C++ [namespace.udecl]p11:
1433 // The set of declarations named by a using-declarator that inhabits a
1434 // class C does not include member functions and member function
1435 // templates of a base class that "correspond" to (and thus would
1436 // conflict with) a declaration of a function or function template in
1438 // Comparing return types is not required for the "correspond" check to
1439 // decide whether a member introduced by a shadow declaration is hidden.
1440 if (UseMemberUsingDeclRules
&& ConstraintsInTemplateHead
&&
1441 !SameTemplateParameterList
)
1443 if (!UseMemberUsingDeclRules
&&
1444 (!SameTemplateParameterList
|| !SameReturnType
))
1448 if (!UseOverrideRules
) {
1449 Expr
*NewRC
= New
->getTrailingRequiresClause(),
1450 *OldRC
= Old
->getTrailingRequiresClause();
1451 if ((NewRC
!= nullptr) != (OldRC
!= nullptr))
1454 if (NewRC
&& !SemaRef
.AreConstraintExpressionsEqual(Old
, OldRC
, New
, NewRC
))
1458 if (NewMethod
&& OldMethod
&& OldMethod
->isImplicitObjectMemberFunction() &&
1459 NewMethod
->isImplicitObjectMemberFunction()) {
1460 if (DiagnoseInconsistentRefQualifiers())
1464 // Though pass_object_size is placed on parameters and takes an argument, we
1465 // consider it to be a function-level modifier for the sake of function
1466 // identity. Either the function has one or more parameters with
1467 // pass_object_size or it doesn't.
1468 if (functionHasPassObjectSizeParams(New
) !=
1469 functionHasPassObjectSizeParams(Old
))
1472 // enable_if attributes are an order-sensitive part of the signature.
1473 for (specific_attr_iterator
<EnableIfAttr
>
1474 NewI
= New
->specific_attr_begin
<EnableIfAttr
>(),
1475 NewE
= New
->specific_attr_end
<EnableIfAttr
>(),
1476 OldI
= Old
->specific_attr_begin
<EnableIfAttr
>(),
1477 OldE
= Old
->specific_attr_end
<EnableIfAttr
>();
1478 NewI
!= NewE
|| OldI
!= OldE
; ++NewI
, ++OldI
) {
1479 if (NewI
== NewE
|| OldI
== OldE
)
1481 llvm::FoldingSetNodeID NewID
, OldID
;
1482 NewI
->getCond()->Profile(NewID
, SemaRef
.Context
, true);
1483 OldI
->getCond()->Profile(OldID
, SemaRef
.Context
, true);
1488 if (SemaRef
.getLangOpts().CUDA
&& ConsiderCudaAttrs
) {
1489 // Don't allow overloading of destructors. (In theory we could, but it
1490 // would be a giant change to clang.)
1491 if (!isa
<CXXDestructorDecl
>(New
)) {
1492 Sema::CUDAFunctionTarget NewTarget
= SemaRef
.IdentifyCUDATarget(New
),
1493 OldTarget
= SemaRef
.IdentifyCUDATarget(Old
);
1494 if (NewTarget
!= Sema::CFT_InvalidTarget
) {
1495 assert((OldTarget
!= Sema::CFT_InvalidTarget
) &&
1496 "Unexpected invalid target.");
1498 // Allow overloading of functions with same signature and different CUDA
1499 // target attributes.
1500 if (NewTarget
!= OldTarget
)
1506 // The signatures match; this is not an overload.
1510 bool Sema::IsOverload(FunctionDecl
*New
, FunctionDecl
*Old
,
1511 bool UseMemberUsingDeclRules
, bool ConsiderCudaAttrs
) {
1512 return IsOverloadOrOverrideImpl(*this, New
, Old
, UseMemberUsingDeclRules
,
1516 bool Sema::IsOverride(FunctionDecl
*MD
, FunctionDecl
*BaseMD
,
1517 bool UseMemberUsingDeclRules
, bool ConsiderCudaAttrs
) {
1518 return IsOverloadOrOverrideImpl(*this, MD
, BaseMD
,
1519 /*UseMemberUsingDeclRules=*/false,
1520 /*ConsiderCudaAttrs=*/true,
1521 /*UseOverrideRules=*/true);
1524 /// Tries a user-defined conversion from From to ToType.
1526 /// Produces an implicit conversion sequence for when a standard conversion
1527 /// is not an option. See TryImplicitConversion for more information.
1528 static ImplicitConversionSequence
1529 TryUserDefinedConversion(Sema
&S
, Expr
*From
, QualType ToType
,
1530 bool SuppressUserConversions
,
1531 AllowedExplicit AllowExplicit
,
1532 bool InOverloadResolution
,
1534 bool AllowObjCWritebackConversion
,
1535 bool AllowObjCConversionOnExplicit
) {
1536 ImplicitConversionSequence ICS
;
1538 if (SuppressUserConversions
) {
1539 // We're not in the case above, so there is no conversion that
1541 ICS
.setBad(BadConversionSequence::no_conversion
, From
, ToType
);
1545 // Attempt user-defined conversion.
1546 OverloadCandidateSet
Conversions(From
->getExprLoc(),
1547 OverloadCandidateSet::CSK_Normal
);
1548 switch (IsUserDefinedConversion(S
, From
, ToType
, ICS
.UserDefined
,
1549 Conversions
, AllowExplicit
,
1550 AllowObjCConversionOnExplicit
)) {
1553 ICS
.setUserDefined();
1554 // C++ [over.ics.user]p4:
1555 // A conversion of an expression of class type to the same class
1556 // type is given Exact Match rank, and a conversion of an
1557 // expression of class type to a base class of that type is
1558 // given Conversion rank, in spite of the fact that a copy
1559 // constructor (i.e., a user-defined conversion function) is
1560 // called for those cases.
1561 if (CXXConstructorDecl
*Constructor
1562 = dyn_cast
<CXXConstructorDecl
>(ICS
.UserDefined
.ConversionFunction
)) {
1564 = S
.Context
.getCanonicalType(From
->getType().getUnqualifiedType());
1566 = S
.Context
.getCanonicalType(ToType
).getUnqualifiedType();
1567 if (Constructor
->isCopyConstructor() &&
1568 (FromCanon
== ToCanon
||
1569 S
.IsDerivedFrom(From
->getBeginLoc(), FromCanon
, ToCanon
))) {
1570 // Turn this into a "standard" conversion sequence, so that it
1571 // gets ranked with standard conversion sequences.
1572 DeclAccessPair Found
= ICS
.UserDefined
.FoundConversionFunction
;
1574 ICS
.Standard
.setAsIdentityConversion();
1575 ICS
.Standard
.setFromType(From
->getType());
1576 ICS
.Standard
.setAllToTypes(ToType
);
1577 ICS
.Standard
.CopyConstructor
= Constructor
;
1578 ICS
.Standard
.FoundCopyConstructor
= Found
;
1579 if (ToCanon
!= FromCanon
)
1580 ICS
.Standard
.Second
= ICK_Derived_To_Base
;
1587 ICS
.Ambiguous
.setFromType(From
->getType());
1588 ICS
.Ambiguous
.setToType(ToType
);
1589 for (OverloadCandidateSet::iterator Cand
= Conversions
.begin();
1590 Cand
!= Conversions
.end(); ++Cand
)
1592 ICS
.Ambiguous
.addConversion(Cand
->FoundDecl
, Cand
->Function
);
1596 case OR_No_Viable_Function
:
1597 ICS
.setBad(BadConversionSequence::no_conversion
, From
, ToType
);
1604 /// TryImplicitConversion - Attempt to perform an implicit conversion
1605 /// from the given expression (Expr) to the given type (ToType). This
1606 /// function returns an implicit conversion sequence that can be used
1607 /// to perform the initialization. Given
1609 /// void f(float f);
1610 /// void g(int i) { f(i); }
1612 /// this routine would produce an implicit conversion sequence to
1613 /// describe the initialization of f from i, which will be a standard
1614 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1615 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1617 /// Note that this routine only determines how the conversion can be
1618 /// performed; it does not actually perform the conversion. As such,
1619 /// it will not produce any diagnostics if no conversion is available,
1620 /// but will instead return an implicit conversion sequence of kind
1621 /// "BadConversion".
1623 /// If @p SuppressUserConversions, then user-defined conversions are
1625 /// If @p AllowExplicit, then explicit user-defined conversions are
1628 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1629 /// writeback conversion, which allows __autoreleasing id* parameters to
1630 /// be initialized with __strong id* or __weak id* arguments.
1631 static ImplicitConversionSequence
1632 TryImplicitConversion(Sema
&S
, Expr
*From
, QualType ToType
,
1633 bool SuppressUserConversions
,
1634 AllowedExplicit AllowExplicit
,
1635 bool InOverloadResolution
,
1637 bool AllowObjCWritebackConversion
,
1638 bool AllowObjCConversionOnExplicit
) {
1639 ImplicitConversionSequence ICS
;
1640 if (IsStandardConversion(S
, From
, ToType
, InOverloadResolution
,
1641 ICS
.Standard
, CStyle
, AllowObjCWritebackConversion
)){
1646 if (!S
.getLangOpts().CPlusPlus
) {
1647 ICS
.setBad(BadConversionSequence::no_conversion
, From
, ToType
);
1651 // C++ [over.ics.user]p4:
1652 // A conversion of an expression of class type to the same class
1653 // type is given Exact Match rank, and a conversion of an
1654 // expression of class type to a base class of that type is
1655 // given Conversion rank, in spite of the fact that a copy/move
1656 // constructor (i.e., a user-defined conversion function) is
1657 // called for those cases.
1658 QualType FromType
= From
->getType();
1659 if (ToType
->getAs
<RecordType
>() && FromType
->getAs
<RecordType
>() &&
1660 (S
.Context
.hasSameUnqualifiedType(FromType
, ToType
) ||
1661 S
.IsDerivedFrom(From
->getBeginLoc(), FromType
, ToType
))) {
1663 ICS
.Standard
.setAsIdentityConversion();
1664 ICS
.Standard
.setFromType(FromType
);
1665 ICS
.Standard
.setAllToTypes(ToType
);
1667 // We don't actually check at this point whether there is a valid
1668 // copy/move constructor, since overloading just assumes that it
1669 // exists. When we actually perform initialization, we'll find the
1670 // appropriate constructor to copy the returned object, if needed.
1671 ICS
.Standard
.CopyConstructor
= nullptr;
1673 // Determine whether this is considered a derived-to-base conversion.
1674 if (!S
.Context
.hasSameUnqualifiedType(FromType
, ToType
))
1675 ICS
.Standard
.Second
= ICK_Derived_To_Base
;
1680 return TryUserDefinedConversion(S
, From
, ToType
, SuppressUserConversions
,
1681 AllowExplicit
, InOverloadResolution
, CStyle
,
1682 AllowObjCWritebackConversion
,
1683 AllowObjCConversionOnExplicit
);
1686 ImplicitConversionSequence
1687 Sema::TryImplicitConversion(Expr
*From
, QualType ToType
,
1688 bool SuppressUserConversions
,
1689 AllowedExplicit AllowExplicit
,
1690 bool InOverloadResolution
,
1692 bool AllowObjCWritebackConversion
) {
1693 return ::TryImplicitConversion(*this, From
, ToType
, SuppressUserConversions
,
1694 AllowExplicit
, InOverloadResolution
, CStyle
,
1695 AllowObjCWritebackConversion
,
1696 /*AllowObjCConversionOnExplicit=*/false);
1699 /// PerformImplicitConversion - Perform an implicit conversion of the
1700 /// expression From to the type ToType. Returns the
1701 /// converted expression. Flavor is the kind of conversion we're
1702 /// performing, used in the error message. If @p AllowExplicit,
1703 /// explicit user-defined conversions are permitted.
1704 ExprResult
Sema::PerformImplicitConversion(Expr
*From
, QualType ToType
,
1705 AssignmentAction Action
,
1706 bool AllowExplicit
) {
1707 if (checkPlaceholderForOverload(*this, From
))
1710 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1711 bool AllowObjCWritebackConversion
1712 = getLangOpts().ObjCAutoRefCount
&&
1713 (Action
== AA_Passing
|| Action
== AA_Sending
);
1714 if (getLangOpts().ObjC
)
1715 CheckObjCBridgeRelatedConversions(From
->getBeginLoc(), ToType
,
1716 From
->getType(), From
);
1717 ImplicitConversionSequence ICS
= ::TryImplicitConversion(
1718 *this, From
, ToType
,
1719 /*SuppressUserConversions=*/false,
1720 AllowExplicit
? AllowedExplicit::All
: AllowedExplicit::None
,
1721 /*InOverloadResolution=*/false,
1722 /*CStyle=*/false, AllowObjCWritebackConversion
,
1723 /*AllowObjCConversionOnExplicit=*/false);
1724 return PerformImplicitConversion(From
, ToType
, ICS
, Action
);
1727 /// Determine whether the conversion from FromType to ToType is a valid
1728 /// conversion that strips "noexcept" or "noreturn" off the nested function
1730 bool Sema::IsFunctionConversion(QualType FromType
, QualType ToType
,
1731 QualType
&ResultTy
) {
1732 if (Context
.hasSameUnqualifiedType(FromType
, ToType
))
1735 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1736 // or F(t noexcept) -> F(t)
1737 // where F adds one of the following at most once:
1739 // - a member pointer
1740 // - a block pointer
1741 // Changes here need matching changes in FindCompositePointerType.
1742 CanQualType CanTo
= Context
.getCanonicalType(ToType
);
1743 CanQualType CanFrom
= Context
.getCanonicalType(FromType
);
1744 Type::TypeClass TyClass
= CanTo
->getTypeClass();
1745 if (TyClass
!= CanFrom
->getTypeClass()) return false;
1746 if (TyClass
!= Type::FunctionProto
&& TyClass
!= Type::FunctionNoProto
) {
1747 if (TyClass
== Type::Pointer
) {
1748 CanTo
= CanTo
.castAs
<PointerType
>()->getPointeeType();
1749 CanFrom
= CanFrom
.castAs
<PointerType
>()->getPointeeType();
1750 } else if (TyClass
== Type::BlockPointer
) {
1751 CanTo
= CanTo
.castAs
<BlockPointerType
>()->getPointeeType();
1752 CanFrom
= CanFrom
.castAs
<BlockPointerType
>()->getPointeeType();
1753 } else if (TyClass
== Type::MemberPointer
) {
1754 auto ToMPT
= CanTo
.castAs
<MemberPointerType
>();
1755 auto FromMPT
= CanFrom
.castAs
<MemberPointerType
>();
1756 // A function pointer conversion cannot change the class of the function.
1757 if (ToMPT
->getClass() != FromMPT
->getClass())
1759 CanTo
= ToMPT
->getPointeeType();
1760 CanFrom
= FromMPT
->getPointeeType();
1765 TyClass
= CanTo
->getTypeClass();
1766 if (TyClass
!= CanFrom
->getTypeClass()) return false;
1767 if (TyClass
!= Type::FunctionProto
&& TyClass
!= Type::FunctionNoProto
)
1771 const auto *FromFn
= cast
<FunctionType
>(CanFrom
);
1772 FunctionType::ExtInfo FromEInfo
= FromFn
->getExtInfo();
1774 const auto *ToFn
= cast
<FunctionType
>(CanTo
);
1775 FunctionType::ExtInfo ToEInfo
= ToFn
->getExtInfo();
1777 bool Changed
= false;
1779 // Drop 'noreturn' if not present in target type.
1780 if (FromEInfo
.getNoReturn() && !ToEInfo
.getNoReturn()) {
1781 FromFn
= Context
.adjustFunctionType(FromFn
, FromEInfo
.withNoReturn(false));
1785 // Drop the 'arm_preserves_za' if not present in the target type (we can do
1786 // that because it is merely a hint).
1787 if (const auto *FromFPT
= dyn_cast
<FunctionProtoType
>(FromFn
)) {
1788 FunctionProtoType::ExtProtoInfo ExtInfo
= FromFPT
->getExtProtoInfo();
1789 if (ExtInfo
.AArch64SMEAttributes
&
1790 FunctionType::SME_PStateZAPreservedMask
) {
1791 unsigned ToFlags
= 0;
1792 if (const auto *ToFPT
= dyn_cast
<FunctionProtoType
>(ToFn
))
1793 ToFlags
= ToFPT
->getExtProtoInfo().AArch64SMEAttributes
;
1794 if (!(ToFlags
& FunctionType::SME_PStateZAPreservedMask
)) {
1795 ExtInfo
.setArmSMEAttribute(FunctionType::SME_PStateZAPreservedMask
,
1797 QualType QT
= Context
.getFunctionType(
1798 FromFPT
->getReturnType(), FromFPT
->getParamTypes(), ExtInfo
);
1799 FromFn
= QT
->getAs
<FunctionType
>();
1805 // Drop 'noexcept' if not present in target type.
1806 if (const auto *FromFPT
= dyn_cast
<FunctionProtoType
>(FromFn
)) {
1807 const auto *ToFPT
= cast
<FunctionProtoType
>(ToFn
);
1808 if (FromFPT
->isNothrow() && !ToFPT
->isNothrow()) {
1809 FromFn
= cast
<FunctionType
>(
1810 Context
.getFunctionTypeWithExceptionSpec(QualType(FromFPT
, 0),
1816 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1817 // only if the ExtParameterInfo lists of the two function prototypes can be
1818 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1819 SmallVector
<FunctionProtoType::ExtParameterInfo
, 4> NewParamInfos
;
1820 bool CanUseToFPT
, CanUseFromFPT
;
1821 if (Context
.mergeExtParameterInfo(ToFPT
, FromFPT
, CanUseToFPT
,
1822 CanUseFromFPT
, NewParamInfos
) &&
1823 CanUseToFPT
&& !CanUseFromFPT
) {
1824 FunctionProtoType::ExtProtoInfo ExtInfo
= FromFPT
->getExtProtoInfo();
1825 ExtInfo
.ExtParameterInfos
=
1826 NewParamInfos
.empty() ? nullptr : NewParamInfos
.data();
1827 QualType QT
= Context
.getFunctionType(FromFPT
->getReturnType(),
1828 FromFPT
->getParamTypes(), ExtInfo
);
1829 FromFn
= QT
->getAs
<FunctionType
>();
1837 assert(QualType(FromFn
, 0).isCanonical());
1838 if (QualType(FromFn
, 0) != CanTo
) return false;
1844 /// Determine whether the conversion from FromType to ToType is a valid
1845 /// vector conversion.
1847 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1849 static bool IsVectorConversion(Sema
&S
, QualType FromType
, QualType ToType
,
1850 ImplicitConversionKind
&ICK
, Expr
*From
,
1851 bool InOverloadResolution
, bool CStyle
) {
1852 // We need at least one of these types to be a vector type to have a vector
1854 if (!ToType
->isVectorType() && !FromType
->isVectorType())
1857 // Identical types require no conversions.
1858 if (S
.Context
.hasSameUnqualifiedType(FromType
, ToType
))
1861 // There are no conversions between extended vector types, only identity.
1862 if (ToType
->isExtVectorType()) {
1863 // There are no conversions between extended vector types other than the
1864 // identity conversion.
1865 if (FromType
->isExtVectorType())
1868 // Vector splat from any arithmetic type to a vector.
1869 if (FromType
->isArithmeticType()) {
1870 ICK
= ICK_Vector_Splat
;
1875 if (ToType
->isSVESizelessBuiltinType() ||
1876 FromType
->isSVESizelessBuiltinType())
1877 if (S
.Context
.areCompatibleSveTypes(FromType
, ToType
) ||
1878 S
.Context
.areLaxCompatibleSveTypes(FromType
, ToType
)) {
1879 ICK
= ICK_SVE_Vector_Conversion
;
1883 if (ToType
->isRVVSizelessBuiltinType() ||
1884 FromType
->isRVVSizelessBuiltinType())
1885 if (S
.Context
.areCompatibleRVVTypes(FromType
, ToType
) ||
1886 S
.Context
.areLaxCompatibleRVVTypes(FromType
, ToType
)) {
1887 ICK
= ICK_RVV_Vector_Conversion
;
1891 // We can perform the conversion between vector types in the following cases:
1892 // 1)vector types are equivalent AltiVec and GCC vector types
1893 // 2)lax vector conversions are permitted and the vector types are of the
1895 // 3)the destination type does not have the ARM MVE strict-polymorphism
1896 // attribute, which inhibits lax vector conversion for overload resolution
1898 if (ToType
->isVectorType() && FromType
->isVectorType()) {
1899 if (S
.Context
.areCompatibleVectorTypes(FromType
, ToType
) ||
1900 (S
.isLaxVectorConversion(FromType
, ToType
) &&
1901 !ToType
->hasAttr(attr::ArmMveStrictPolymorphism
))) {
1902 if (S
.getASTContext().getTargetInfo().getTriple().isPPC() &&
1903 S
.isLaxVectorConversion(FromType
, ToType
) &&
1904 S
.anyAltivecTypes(FromType
, ToType
) &&
1905 !S
.Context
.areCompatibleVectorTypes(FromType
, ToType
) &&
1906 !InOverloadResolution
&& !CStyle
) {
1907 S
.Diag(From
->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all
)
1908 << FromType
<< ToType
;
1910 ICK
= ICK_Vector_Conversion
;
1918 static bool tryAtomicConversion(Sema
&S
, Expr
*From
, QualType ToType
,
1919 bool InOverloadResolution
,
1920 StandardConversionSequence
&SCS
,
1923 /// IsStandardConversion - Determines whether there is a standard
1924 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1925 /// expression From to the type ToType. Standard conversion sequences
1926 /// only consider non-class types; for conversions that involve class
1927 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1928 /// contain the standard conversion sequence required to perform this
1929 /// conversion and this routine will return true. Otherwise, this
1930 /// routine will return false and the value of SCS is unspecified.
1931 static bool IsStandardConversion(Sema
&S
, Expr
* From
, QualType ToType
,
1932 bool InOverloadResolution
,
1933 StandardConversionSequence
&SCS
,
1935 bool AllowObjCWritebackConversion
) {
1936 QualType FromType
= From
->getType();
1938 // Standard conversions (C++ [conv])
1939 SCS
.setAsIdentityConversion();
1940 SCS
.IncompatibleObjC
= false;
1941 SCS
.setFromType(FromType
);
1942 SCS
.CopyConstructor
= nullptr;
1944 // There are no standard conversions for class types in C++, so
1945 // abort early. When overloading in C, however, we do permit them.
1946 if (S
.getLangOpts().CPlusPlus
&&
1947 (FromType
->isRecordType() || ToType
->isRecordType()))
1950 // The first conversion can be an lvalue-to-rvalue conversion,
1951 // array-to-pointer conversion, or function-to-pointer conversion
1954 if (FromType
== S
.Context
.OverloadTy
) {
1955 DeclAccessPair AccessPair
;
1956 if (FunctionDecl
*Fn
1957 = S
.ResolveAddressOfOverloadedFunction(From
, ToType
, false,
1959 // We were able to resolve the address of the overloaded function,
1960 // so we can convert to the type of that function.
1961 FromType
= Fn
->getType();
1962 SCS
.setFromType(FromType
);
1964 // we can sometimes resolve &foo<int> regardless of ToType, so check
1965 // if the type matches (identity) or we are converting to bool
1966 if (!S
.Context
.hasSameUnqualifiedType(
1967 S
.ExtractUnqualifiedFunctionType(ToType
), FromType
)) {
1969 // if the function type matches except for [[noreturn]], it's ok
1970 if (!S
.IsFunctionConversion(FromType
,
1971 S
.ExtractUnqualifiedFunctionType(ToType
), resultTy
))
1972 // otherwise, only a boolean conversion is standard
1973 if (!ToType
->isBooleanType())
1977 // Check if the "from" expression is taking the address of an overloaded
1978 // function and recompute the FromType accordingly. Take advantage of the
1979 // fact that non-static member functions *must* have such an address-of
1981 CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
);
1982 if (Method
&& !Method
->isStatic() &&
1983 !Method
->isExplicitObjectMemberFunction()) {
1984 assert(isa
<UnaryOperator
>(From
->IgnoreParens()) &&
1985 "Non-unary operator on non-static member address");
1986 assert(cast
<UnaryOperator
>(From
->IgnoreParens())->getOpcode()
1988 "Non-address-of operator on non-static member address");
1989 const Type
*ClassType
1990 = S
.Context
.getTypeDeclType(Method
->getParent()).getTypePtr();
1991 FromType
= S
.Context
.getMemberPointerType(FromType
, ClassType
);
1992 } else if (isa
<UnaryOperator
>(From
->IgnoreParens())) {
1993 assert(cast
<UnaryOperator
>(From
->IgnoreParens())->getOpcode() ==
1995 "Non-address-of operator for overloaded function expression");
1996 FromType
= S
.Context
.getPointerType(FromType
);
2002 // Lvalue-to-rvalue conversion (C++11 4.1):
2003 // A glvalue (3.10) of a non-function, non-array type T can
2004 // be converted to a prvalue.
2005 bool argIsLValue
= From
->isGLValue();
2007 !FromType
->isFunctionType() && !FromType
->isArrayType() &&
2008 S
.Context
.getCanonicalType(FromType
) != S
.Context
.OverloadTy
) {
2009 SCS
.First
= ICK_Lvalue_To_Rvalue
;
2012 // ... if the lvalue has atomic type, the value has the non-atomic version
2013 // of the type of the lvalue ...
2014 if (const AtomicType
*Atomic
= FromType
->getAs
<AtomicType
>())
2015 FromType
= Atomic
->getValueType();
2017 // If T is a non-class type, the type of the rvalue is the
2018 // cv-unqualified version of T. Otherwise, the type of the rvalue
2019 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2020 // just strip the qualifiers because they don't matter.
2021 FromType
= FromType
.getUnqualifiedType();
2022 } else if (FromType
->isArrayType()) {
2023 // Array-to-pointer conversion (C++ 4.2)
2024 SCS
.First
= ICK_Array_To_Pointer
;
2026 // An lvalue or rvalue of type "array of N T" or "array of unknown
2027 // bound of T" can be converted to an rvalue of type "pointer to
2029 FromType
= S
.Context
.getArrayDecayedType(FromType
);
2031 if (S
.IsStringLiteralToNonConstPointerConversion(From
, ToType
)) {
2032 // This conversion is deprecated in C++03 (D.4)
2033 SCS
.DeprecatedStringLiteralToCharPtr
= true;
2035 // For the purpose of ranking in overload resolution
2036 // (13.3.3.1.1), this conversion is considered an
2037 // array-to-pointer conversion followed by a qualification
2038 // conversion (4.4). (C++ 4.2p2)
2039 SCS
.Second
= ICK_Identity
;
2040 SCS
.Third
= ICK_Qualification
;
2041 SCS
.QualificationIncludesObjCLifetime
= false;
2042 SCS
.setAllToTypes(FromType
);
2045 } else if (FromType
->isFunctionType() && argIsLValue
) {
2046 // Function-to-pointer conversion (C++ 4.3).
2047 SCS
.First
= ICK_Function_To_Pointer
;
2049 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(From
->IgnoreParenCasts()))
2050 if (auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl()))
2051 if (!S
.checkAddressOfFunctionIsAvailable(FD
))
2054 // An lvalue of function type T can be converted to an rvalue of
2055 // type "pointer to T." The result is a pointer to the
2056 // function. (C++ 4.3p1).
2057 FromType
= S
.Context
.getPointerType(FromType
);
2059 // We don't require any conversions for the first step.
2060 SCS
.First
= ICK_Identity
;
2062 SCS
.setToType(0, FromType
);
2064 // The second conversion can be an integral promotion, floating
2065 // point promotion, integral conversion, floating point conversion,
2066 // floating-integral conversion, pointer conversion,
2067 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2068 // For overloading in C, this can also be a "compatible-type"
2070 bool IncompatibleObjC
= false;
2071 ImplicitConversionKind SecondICK
= ICK_Identity
;
2072 if (S
.Context
.hasSameUnqualifiedType(FromType
, ToType
)) {
2073 // The unqualified versions of the types are the same: there's no
2074 // conversion to do.
2075 SCS
.Second
= ICK_Identity
;
2076 } else if (S
.IsIntegralPromotion(From
, FromType
, ToType
)) {
2077 // Integral promotion (C++ 4.5).
2078 SCS
.Second
= ICK_Integral_Promotion
;
2079 FromType
= ToType
.getUnqualifiedType();
2080 } else if (S
.IsFloatingPointPromotion(FromType
, ToType
)) {
2081 // Floating point promotion (C++ 4.6).
2082 SCS
.Second
= ICK_Floating_Promotion
;
2083 FromType
= ToType
.getUnqualifiedType();
2084 } else if (S
.IsComplexPromotion(FromType
, ToType
)) {
2085 // Complex promotion (Clang extension)
2086 SCS
.Second
= ICK_Complex_Promotion
;
2087 FromType
= ToType
.getUnqualifiedType();
2088 } else if (ToType
->isBooleanType() &&
2089 (FromType
->isArithmeticType() ||
2090 FromType
->isAnyPointerType() ||
2091 FromType
->isBlockPointerType() ||
2092 FromType
->isMemberPointerType())) {
2093 // Boolean conversions (C++ 4.12).
2094 SCS
.Second
= ICK_Boolean_Conversion
;
2095 FromType
= S
.Context
.BoolTy
;
2096 } else if (FromType
->isIntegralOrUnscopedEnumerationType() &&
2097 ToType
->isIntegralType(S
.Context
)) {
2098 // Integral conversions (C++ 4.7).
2099 SCS
.Second
= ICK_Integral_Conversion
;
2100 FromType
= ToType
.getUnqualifiedType();
2101 } else if (FromType
->isAnyComplexType() && ToType
->isAnyComplexType()) {
2102 // Complex conversions (C99 6.3.1.6)
2103 SCS
.Second
= ICK_Complex_Conversion
;
2104 FromType
= ToType
.getUnqualifiedType();
2105 } else if ((FromType
->isAnyComplexType() && ToType
->isArithmeticType()) ||
2106 (ToType
->isAnyComplexType() && FromType
->isArithmeticType())) {
2107 // Complex-real conversions (C99 6.3.1.7)
2108 SCS
.Second
= ICK_Complex_Real
;
2109 FromType
= ToType
.getUnqualifiedType();
2110 } else if (FromType
->isRealFloatingType() && ToType
->isRealFloatingType()) {
2111 // FIXME: disable conversions between long double, __ibm128 and __float128
2112 // if their representation is different until there is back end support
2113 // We of course allow this conversion if long double is really double.
2115 // Conversions between bfloat16 and float16 are currently not supported.
2116 if ((FromType
->isBFloat16Type() &&
2117 (ToType
->isFloat16Type() || ToType
->isHalfType())) ||
2118 (ToType
->isBFloat16Type() &&
2119 (FromType
->isFloat16Type() || FromType
->isHalfType())))
2122 // Conversions between IEEE-quad and IBM-extended semantics are not
2124 const llvm::fltSemantics
&FromSem
=
2125 S
.Context
.getFloatTypeSemantics(FromType
);
2126 const llvm::fltSemantics
&ToSem
= S
.Context
.getFloatTypeSemantics(ToType
);
2127 if ((&FromSem
== &llvm::APFloat::PPCDoubleDouble() &&
2128 &ToSem
== &llvm::APFloat::IEEEquad()) ||
2129 (&FromSem
== &llvm::APFloat::IEEEquad() &&
2130 &ToSem
== &llvm::APFloat::PPCDoubleDouble()))
2133 // Floating point conversions (C++ 4.8).
2134 SCS
.Second
= ICK_Floating_Conversion
;
2135 FromType
= ToType
.getUnqualifiedType();
2136 } else if ((FromType
->isRealFloatingType() &&
2137 ToType
->isIntegralType(S
.Context
)) ||
2138 (FromType
->isIntegralOrUnscopedEnumerationType() &&
2139 ToType
->isRealFloatingType())) {
2141 // Floating-integral conversions (C++ 4.9).
2142 SCS
.Second
= ICK_Floating_Integral
;
2143 FromType
= ToType
.getUnqualifiedType();
2144 } else if (S
.IsBlockPointerConversion(FromType
, ToType
, FromType
)) {
2145 SCS
.Second
= ICK_Block_Pointer_Conversion
;
2146 } else if (AllowObjCWritebackConversion
&&
2147 S
.isObjCWritebackConversion(FromType
, ToType
, FromType
)) {
2148 SCS
.Second
= ICK_Writeback_Conversion
;
2149 } else if (S
.IsPointerConversion(From
, FromType
, ToType
, InOverloadResolution
,
2150 FromType
, IncompatibleObjC
)) {
2151 // Pointer conversions (C++ 4.10).
2152 SCS
.Second
= ICK_Pointer_Conversion
;
2153 SCS
.IncompatibleObjC
= IncompatibleObjC
;
2154 FromType
= FromType
.getUnqualifiedType();
2155 } else if (S
.IsMemberPointerConversion(From
, FromType
, ToType
,
2156 InOverloadResolution
, FromType
)) {
2157 // Pointer to member conversions (4.11).
2158 SCS
.Second
= ICK_Pointer_Member
;
2159 } else if (IsVectorConversion(S
, FromType
, ToType
, SecondICK
, From
,
2160 InOverloadResolution
, CStyle
)) {
2161 SCS
.Second
= SecondICK
;
2162 FromType
= ToType
.getUnqualifiedType();
2163 } else if (!S
.getLangOpts().CPlusPlus
&&
2164 S
.Context
.typesAreCompatible(ToType
, FromType
)) {
2165 // Compatible conversions (Clang extension for C function overloading)
2166 SCS
.Second
= ICK_Compatible_Conversion
;
2167 FromType
= ToType
.getUnqualifiedType();
2168 } else if (IsTransparentUnionStandardConversion(S
, From
, ToType
,
2169 InOverloadResolution
,
2171 SCS
.Second
= ICK_TransparentUnionConversion
;
2173 } else if (tryAtomicConversion(S
, From
, ToType
, InOverloadResolution
, SCS
,
2175 // tryAtomicConversion has updated the standard conversion sequence
2178 } else if (ToType
->isEventT() &&
2179 From
->isIntegerConstantExpr(S
.getASTContext()) &&
2180 From
->EvaluateKnownConstInt(S
.getASTContext()) == 0) {
2181 SCS
.Second
= ICK_Zero_Event_Conversion
;
2183 } else if (ToType
->isQueueT() &&
2184 From
->isIntegerConstantExpr(S
.getASTContext()) &&
2185 (From
->EvaluateKnownConstInt(S
.getASTContext()) == 0)) {
2186 SCS
.Second
= ICK_Zero_Queue_Conversion
;
2188 } else if (ToType
->isSamplerT() &&
2189 From
->isIntegerConstantExpr(S
.getASTContext())) {
2190 SCS
.Second
= ICK_Compatible_Conversion
;
2193 // No second conversion required.
2194 SCS
.Second
= ICK_Identity
;
2196 SCS
.setToType(1, FromType
);
2198 // The third conversion can be a function pointer conversion or a
2199 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2200 bool ObjCLifetimeConversion
;
2201 if (S
.IsFunctionConversion(FromType
, ToType
, FromType
)) {
2202 // Function pointer conversions (removing 'noexcept') including removal of
2203 // 'noreturn' (Clang extension).
2204 SCS
.Third
= ICK_Function_Conversion
;
2205 } else if (S
.IsQualificationConversion(FromType
, ToType
, CStyle
,
2206 ObjCLifetimeConversion
)) {
2207 SCS
.Third
= ICK_Qualification
;
2208 SCS
.QualificationIncludesObjCLifetime
= ObjCLifetimeConversion
;
2211 // No conversion required
2212 SCS
.Third
= ICK_Identity
;
2215 // C++ [over.best.ics]p6:
2216 // [...] Any difference in top-level cv-qualification is
2217 // subsumed by the initialization itself and does not constitute
2218 // a conversion. [...]
2219 QualType CanonFrom
= S
.Context
.getCanonicalType(FromType
);
2220 QualType CanonTo
= S
.Context
.getCanonicalType(ToType
);
2221 if (CanonFrom
.getLocalUnqualifiedType()
2222 == CanonTo
.getLocalUnqualifiedType() &&
2223 CanonFrom
.getLocalQualifiers() != CanonTo
.getLocalQualifiers()) {
2225 CanonFrom
= CanonTo
;
2228 SCS
.setToType(2, FromType
);
2230 if (CanonFrom
== CanonTo
)
2233 // If we have not converted the argument type to the parameter type,
2234 // this is a bad conversion sequence, unless we're resolving an overload in C.
2235 if (S
.getLangOpts().CPlusPlus
|| !InOverloadResolution
)
2238 ExprResult ER
= ExprResult
{From
};
2239 Sema::AssignConvertType Conv
=
2240 S
.CheckSingleAssignmentConstraints(ToType
, ER
,
2242 /*DiagnoseCFAudited=*/false,
2243 /*ConvertRHS=*/false);
2244 ImplicitConversionKind SecondConv
;
2246 case Sema::Compatible
:
2247 SecondConv
= ICK_C_Only_Conversion
;
2249 // For our purposes, discarding qualifiers is just as bad as using an
2250 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2251 // qualifiers, as well.
2252 case Sema::CompatiblePointerDiscardsQualifiers
:
2253 case Sema::IncompatiblePointer
:
2254 case Sema::IncompatiblePointerSign
:
2255 SecondConv
= ICK_Incompatible_Pointer_Conversion
;
2261 // First can only be an lvalue conversion, so we pretend that this was the
2262 // second conversion. First should already be valid from earlier in the
2264 SCS
.Second
= SecondConv
;
2265 SCS
.setToType(1, ToType
);
2267 // Third is Identity, because Second should rank us worse than any other
2268 // conversion. This could also be ICK_Qualification, but it's simpler to just
2269 // lump everything in with the second conversion, and we don't gain anything
2270 // from making this ICK_Qualification.
2271 SCS
.Third
= ICK_Identity
;
2272 SCS
.setToType(2, ToType
);
2277 IsTransparentUnionStandardConversion(Sema
&S
, Expr
* From
,
2279 bool InOverloadResolution
,
2280 StandardConversionSequence
&SCS
,
2283 const RecordType
*UT
= ToType
->getAsUnionType();
2284 if (!UT
|| !UT
->getDecl()->hasAttr
<TransparentUnionAttr
>())
2286 // The field to initialize within the transparent union.
2287 RecordDecl
*UD
= UT
->getDecl();
2288 // It's compatible if the expression matches any of the fields.
2289 for (const auto *it
: UD
->fields()) {
2290 if (IsStandardConversion(S
, From
, it
->getType(), InOverloadResolution
, SCS
,
2291 CStyle
, /*AllowObjCWritebackConversion=*/false)) {
2292 ToType
= it
->getType();
2299 /// IsIntegralPromotion - Determines whether the conversion from the
2300 /// expression From (whose potentially-adjusted type is FromType) to
2301 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2302 /// sets PromotedType to the promoted type.
2303 bool Sema::IsIntegralPromotion(Expr
*From
, QualType FromType
, QualType ToType
) {
2304 const BuiltinType
*To
= ToType
->getAs
<BuiltinType
>();
2305 // All integers are built-in.
2310 // An rvalue of type char, signed char, unsigned char, short int, or
2311 // unsigned short int can be converted to an rvalue of type int if
2312 // int can represent all the values of the source type; otherwise,
2313 // the source rvalue can be converted to an rvalue of type unsigned
2315 if (Context
.isPromotableIntegerType(FromType
) && !FromType
->isBooleanType() &&
2316 !FromType
->isEnumeralType()) {
2317 if ( // We can promote any signed, promotable integer type to an int
2318 (FromType
->isSignedIntegerType() ||
2319 // We can promote any unsigned integer type whose size is
2320 // less than int to an int.
2321 Context
.getTypeSize(FromType
) < Context
.getTypeSize(ToType
))) {
2322 return To
->getKind() == BuiltinType::Int
;
2325 return To
->getKind() == BuiltinType::UInt
;
2328 // C++11 [conv.prom]p3:
2329 // A prvalue of an unscoped enumeration type whose underlying type is not
2330 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2331 // following types that can represent all the values of the enumeration
2332 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2333 // unsigned int, long int, unsigned long int, long long int, or unsigned
2334 // long long int. If none of the types in that list can represent all the
2335 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2336 // type can be converted to an rvalue a prvalue of the extended integer type
2337 // with lowest integer conversion rank (4.13) greater than the rank of long
2338 // long in which all the values of the enumeration can be represented. If
2339 // there are two such extended types, the signed one is chosen.
2340 // C++11 [conv.prom]p4:
2341 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2342 // can be converted to a prvalue of its underlying type. Moreover, if
2343 // integral promotion can be applied to its underlying type, a prvalue of an
2344 // unscoped enumeration type whose underlying type is fixed can also be
2345 // converted to a prvalue of the promoted underlying type.
2346 if (const EnumType
*FromEnumType
= FromType
->getAs
<EnumType
>()) {
2347 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2348 // provided for a scoped enumeration.
2349 if (FromEnumType
->getDecl()->isScoped())
2352 // We can perform an integral promotion to the underlying type of the enum,
2353 // even if that's not the promoted type. Note that the check for promoting
2354 // the underlying type is based on the type alone, and does not consider
2355 // the bitfield-ness of the actual source expression.
2356 if (FromEnumType
->getDecl()->isFixed()) {
2357 QualType Underlying
= FromEnumType
->getDecl()->getIntegerType();
2358 return Context
.hasSameUnqualifiedType(Underlying
, ToType
) ||
2359 IsIntegralPromotion(nullptr, Underlying
, ToType
);
2362 // We have already pre-calculated the promotion type, so this is trivial.
2363 if (ToType
->isIntegerType() &&
2364 isCompleteType(From
->getBeginLoc(), FromType
))
2365 return Context
.hasSameUnqualifiedType(
2366 ToType
, FromEnumType
->getDecl()->getPromotionType());
2368 // C++ [conv.prom]p5:
2369 // If the bit-field has an enumerated type, it is treated as any other
2370 // value of that type for promotion purposes.
2372 // ... so do not fall through into the bit-field checks below in C++.
2373 if (getLangOpts().CPlusPlus
)
2377 // C++0x [conv.prom]p2:
2378 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2379 // to an rvalue a prvalue of the first of the following types that can
2380 // represent all the values of its underlying type: int, unsigned int,
2381 // long int, unsigned long int, long long int, or unsigned long long int.
2382 // If none of the types in that list can represent all the values of its
2383 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2384 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2386 if (FromType
->isAnyCharacterType() && !FromType
->isCharType() &&
2387 ToType
->isIntegerType()) {
2388 // Determine whether the type we're converting from is signed or
2390 bool FromIsSigned
= FromType
->isSignedIntegerType();
2391 uint64_t FromSize
= Context
.getTypeSize(FromType
);
2393 // The types we'll try to promote to, in the appropriate
2394 // order. Try each of these types.
2395 QualType PromoteTypes
[6] = {
2396 Context
.IntTy
, Context
.UnsignedIntTy
,
2397 Context
.LongTy
, Context
.UnsignedLongTy
,
2398 Context
.LongLongTy
, Context
.UnsignedLongLongTy
2400 for (int Idx
= 0; Idx
< 6; ++Idx
) {
2401 uint64_t ToSize
= Context
.getTypeSize(PromoteTypes
[Idx
]);
2402 if (FromSize
< ToSize
||
2403 (FromSize
== ToSize
&&
2404 FromIsSigned
== PromoteTypes
[Idx
]->isSignedIntegerType())) {
2405 // We found the type that we can promote to. If this is the
2406 // type we wanted, we have a promotion. Otherwise, no
2408 return Context
.hasSameUnqualifiedType(ToType
, PromoteTypes
[Idx
]);
2413 // An rvalue for an integral bit-field (9.6) can be converted to an
2414 // rvalue of type int if int can represent all the values of the
2415 // bit-field; otherwise, it can be converted to unsigned int if
2416 // unsigned int can represent all the values of the bit-field. If
2417 // the bit-field is larger yet, no integral promotion applies to
2418 // it. If the bit-field has an enumerated type, it is treated as any
2419 // other value of that type for promotion purposes (C++ 4.5p3).
2420 // FIXME: We should delay checking of bit-fields until we actually perform the
2423 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2424 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2425 // bit-fields and those whose underlying type is larger than int) for GCC
2428 if (FieldDecl
*MemberDecl
= From
->getSourceBitField()) {
2429 std::optional
<llvm::APSInt
> BitWidth
;
2430 if (FromType
->isIntegralType(Context
) &&
2432 MemberDecl
->getBitWidth()->getIntegerConstantExpr(Context
))) {
2433 llvm::APSInt
ToSize(BitWidth
->getBitWidth(), BitWidth
->isUnsigned());
2434 ToSize
= Context
.getTypeSize(ToType
);
2436 // Are we promoting to an int from a bitfield that fits in an int?
2437 if (*BitWidth
< ToSize
||
2438 (FromType
->isSignedIntegerType() && *BitWidth
<= ToSize
)) {
2439 return To
->getKind() == BuiltinType::Int
;
2442 // Are we promoting to an unsigned int from an unsigned bitfield
2443 // that fits into an unsigned int?
2444 if (FromType
->isUnsignedIntegerType() && *BitWidth
<= ToSize
) {
2445 return To
->getKind() == BuiltinType::UInt
;
2453 // An rvalue of type bool can be converted to an rvalue of type int,
2454 // with false becoming zero and true becoming one (C++ 4.5p4).
2455 if (FromType
->isBooleanType() && To
->getKind() == BuiltinType::Int
) {
2462 /// IsFloatingPointPromotion - Determines whether the conversion from
2463 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2464 /// returns true and sets PromotedType to the promoted type.
2465 bool Sema::IsFloatingPointPromotion(QualType FromType
, QualType ToType
) {
2466 if (const BuiltinType
*FromBuiltin
= FromType
->getAs
<BuiltinType
>())
2467 if (const BuiltinType
*ToBuiltin
= ToType
->getAs
<BuiltinType
>()) {
2468 /// An rvalue of type float can be converted to an rvalue of type
2469 /// double. (C++ 4.6p1).
2470 if (FromBuiltin
->getKind() == BuiltinType::Float
&&
2471 ToBuiltin
->getKind() == BuiltinType::Double
)
2475 // When a float is promoted to double or long double, or a
2476 // double is promoted to long double [...].
2477 if (!getLangOpts().CPlusPlus
&&
2478 (FromBuiltin
->getKind() == BuiltinType::Float
||
2479 FromBuiltin
->getKind() == BuiltinType::Double
) &&
2480 (ToBuiltin
->getKind() == BuiltinType::LongDouble
||
2481 ToBuiltin
->getKind() == BuiltinType::Float128
||
2482 ToBuiltin
->getKind() == BuiltinType::Ibm128
))
2485 // Half can be promoted to float.
2486 if (!getLangOpts().NativeHalfType
&&
2487 FromBuiltin
->getKind() == BuiltinType::Half
&&
2488 ToBuiltin
->getKind() == BuiltinType::Float
)
2495 /// Determine if a conversion is a complex promotion.
2497 /// A complex promotion is defined as a complex -> complex conversion
2498 /// where the conversion between the underlying real types is a
2499 /// floating-point or integral promotion.
2500 bool Sema::IsComplexPromotion(QualType FromType
, QualType ToType
) {
2501 const ComplexType
*FromComplex
= FromType
->getAs
<ComplexType
>();
2505 const ComplexType
*ToComplex
= ToType
->getAs
<ComplexType
>();
2509 return IsFloatingPointPromotion(FromComplex
->getElementType(),
2510 ToComplex
->getElementType()) ||
2511 IsIntegralPromotion(nullptr, FromComplex
->getElementType(),
2512 ToComplex
->getElementType());
2515 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2516 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2517 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2518 /// if non-empty, will be a pointer to ToType that may or may not have
2519 /// the right set of qualifiers on its pointee.
2522 BuildSimilarlyQualifiedPointerType(const Type
*FromPtr
,
2523 QualType ToPointee
, QualType ToType
,
2524 ASTContext
&Context
,
2525 bool StripObjCLifetime
= false) {
2526 assert((FromPtr
->getTypeClass() == Type::Pointer
||
2527 FromPtr
->getTypeClass() == Type::ObjCObjectPointer
) &&
2528 "Invalid similarly-qualified pointer type");
2530 /// Conversions to 'id' subsume cv-qualifier conversions.
2531 if (ToType
->isObjCIdType() || ToType
->isObjCQualifiedIdType())
2532 return ToType
.getUnqualifiedType();
2534 QualType CanonFromPointee
2535 = Context
.getCanonicalType(FromPtr
->getPointeeType());
2536 QualType CanonToPointee
= Context
.getCanonicalType(ToPointee
);
2537 Qualifiers Quals
= CanonFromPointee
.getQualifiers();
2539 if (StripObjCLifetime
)
2540 Quals
.removeObjCLifetime();
2542 // Exact qualifier match -> return the pointer type we're converting to.
2543 if (CanonToPointee
.getLocalQualifiers() == Quals
) {
2544 // ToType is exactly what we need. Return it.
2545 if (!ToType
.isNull())
2546 return ToType
.getUnqualifiedType();
2548 // Build a pointer to ToPointee. It has the right qualifiers
2550 if (isa
<ObjCObjectPointerType
>(ToType
))
2551 return Context
.getObjCObjectPointerType(ToPointee
);
2552 return Context
.getPointerType(ToPointee
);
2555 // Just build a canonical type that has the right qualifiers.
2556 QualType QualifiedCanonToPointee
2557 = Context
.getQualifiedType(CanonToPointee
.getLocalUnqualifiedType(), Quals
);
2559 if (isa
<ObjCObjectPointerType
>(ToType
))
2560 return Context
.getObjCObjectPointerType(QualifiedCanonToPointee
);
2561 return Context
.getPointerType(QualifiedCanonToPointee
);
2564 static bool isNullPointerConstantForConversion(Expr
*Expr
,
2565 bool InOverloadResolution
,
2566 ASTContext
&Context
) {
2567 // Handle value-dependent integral null pointer constants correctly.
2568 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2569 if (Expr
->isValueDependent() && !Expr
->isTypeDependent() &&
2570 Expr
->getType()->isIntegerType() && !Expr
->getType()->isEnumeralType())
2571 return !InOverloadResolution
;
2573 return Expr
->isNullPointerConstant(Context
,
2574 InOverloadResolution
? Expr::NPC_ValueDependentIsNotNull
2575 : Expr::NPC_ValueDependentIsNull
);
2578 /// IsPointerConversion - Determines whether the conversion of the
2579 /// expression From, which has the (possibly adjusted) type FromType,
2580 /// can be converted to the type ToType via a pointer conversion (C++
2581 /// 4.10). If so, returns true and places the converted type (that
2582 /// might differ from ToType in its cv-qualifiers at some level) into
2585 /// This routine also supports conversions to and from block pointers
2586 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2587 /// pointers to interfaces. FIXME: Once we've determined the
2588 /// appropriate overloading rules for Objective-C, we may want to
2589 /// split the Objective-C checks into a different routine; however,
2590 /// GCC seems to consider all of these conversions to be pointer
2591 /// conversions, so for now they live here. IncompatibleObjC will be
2592 /// set if the conversion is an allowed Objective-C conversion that
2593 /// should result in a warning.
2594 bool Sema::IsPointerConversion(Expr
*From
, QualType FromType
, QualType ToType
,
2595 bool InOverloadResolution
,
2596 QualType
& ConvertedType
,
2597 bool &IncompatibleObjC
) {
2598 IncompatibleObjC
= false;
2599 if (isObjCPointerConversion(FromType
, ToType
, ConvertedType
,
2603 // Conversion from a null pointer constant to any Objective-C pointer type.
2604 if (ToType
->isObjCObjectPointerType() &&
2605 isNullPointerConstantForConversion(From
, InOverloadResolution
, Context
)) {
2606 ConvertedType
= ToType
;
2610 // Blocks: Block pointers can be converted to void*.
2611 if (FromType
->isBlockPointerType() && ToType
->isPointerType() &&
2612 ToType
->castAs
<PointerType
>()->getPointeeType()->isVoidType()) {
2613 ConvertedType
= ToType
;
2616 // Blocks: A null pointer constant can be converted to a block
2618 if (ToType
->isBlockPointerType() &&
2619 isNullPointerConstantForConversion(From
, InOverloadResolution
, Context
)) {
2620 ConvertedType
= ToType
;
2624 // If the left-hand-side is nullptr_t, the right side can be a null
2625 // pointer constant.
2626 if (ToType
->isNullPtrType() &&
2627 isNullPointerConstantForConversion(From
, InOverloadResolution
, Context
)) {
2628 ConvertedType
= ToType
;
2632 const PointerType
* ToTypePtr
= ToType
->getAs
<PointerType
>();
2636 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2637 if (isNullPointerConstantForConversion(From
, InOverloadResolution
, Context
)) {
2638 ConvertedType
= ToType
;
2642 // Beyond this point, both types need to be pointers
2643 // , including objective-c pointers.
2644 QualType ToPointeeType
= ToTypePtr
->getPointeeType();
2645 if (FromType
->isObjCObjectPointerType() && ToPointeeType
->isVoidType() &&
2646 !getLangOpts().ObjCAutoRefCount
) {
2647 ConvertedType
= BuildSimilarlyQualifiedPointerType(
2648 FromType
->castAs
<ObjCObjectPointerType
>(), ToPointeeType
, ToType
,
2652 const PointerType
*FromTypePtr
= FromType
->getAs
<PointerType
>();
2656 QualType FromPointeeType
= FromTypePtr
->getPointeeType();
2658 // If the unqualified pointee types are the same, this can't be a
2659 // pointer conversion, so don't do all of the work below.
2660 if (Context
.hasSameUnqualifiedType(FromPointeeType
, ToPointeeType
))
2663 // An rvalue of type "pointer to cv T," where T is an object type,
2664 // can be converted to an rvalue of type "pointer to cv void" (C++
2666 if (FromPointeeType
->isIncompleteOrObjectType() &&
2667 ToPointeeType
->isVoidType()) {
2668 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2671 /*StripObjCLifetime=*/true);
2675 // MSVC allows implicit function to void* type conversion.
2676 if (getLangOpts().MSVCCompat
&& FromPointeeType
->isFunctionType() &&
2677 ToPointeeType
->isVoidType()) {
2678 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2684 // When we're overloading in C, we allow a special kind of pointer
2685 // conversion for compatible-but-not-identical pointee types.
2686 if (!getLangOpts().CPlusPlus
&&
2687 Context
.typesAreCompatible(FromPointeeType
, ToPointeeType
)) {
2688 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2694 // C++ [conv.ptr]p3:
2696 // An rvalue of type "pointer to cv D," where D is a class type,
2697 // can be converted to an rvalue of type "pointer to cv B," where
2698 // B is a base class (clause 10) of D. If B is an inaccessible
2699 // (clause 11) or ambiguous (10.2) base class of D, a program that
2700 // necessitates this conversion is ill-formed. The result of the
2701 // conversion is a pointer to the base class sub-object of the
2702 // derived class object. The null pointer value is converted to
2703 // the null pointer value of the destination type.
2705 // Note that we do not check for ambiguity or inaccessibility
2706 // here. That is handled by CheckPointerConversion.
2707 if (getLangOpts().CPlusPlus
&& FromPointeeType
->isRecordType() &&
2708 ToPointeeType
->isRecordType() &&
2709 !Context
.hasSameUnqualifiedType(FromPointeeType
, ToPointeeType
) &&
2710 IsDerivedFrom(From
->getBeginLoc(), FromPointeeType
, ToPointeeType
)) {
2711 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2717 if (FromPointeeType
->isVectorType() && ToPointeeType
->isVectorType() &&
2718 Context
.areCompatibleVectorTypes(FromPointeeType
, ToPointeeType
)) {
2719 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2728 /// Adopt the given qualifiers for the given type.
2729 static QualType
AdoptQualifiers(ASTContext
&Context
, QualType T
, Qualifiers Qs
){
2730 Qualifiers TQs
= T
.getQualifiers();
2732 // Check whether qualifiers already match.
2736 if (Qs
.compatiblyIncludes(TQs
))
2737 return Context
.getQualifiedType(T
, Qs
);
2739 return Context
.getQualifiedType(T
.getUnqualifiedType(), Qs
);
2742 /// isObjCPointerConversion - Determines whether this is an
2743 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2744 /// with the same arguments and return values.
2745 bool Sema::isObjCPointerConversion(QualType FromType
, QualType ToType
,
2746 QualType
& ConvertedType
,
2747 bool &IncompatibleObjC
) {
2748 if (!getLangOpts().ObjC
)
2751 // The set of qualifiers on the type we're converting from.
2752 Qualifiers FromQualifiers
= FromType
.getQualifiers();
2754 // First, we handle all conversions on ObjC object pointer types.
2755 const ObjCObjectPointerType
* ToObjCPtr
=
2756 ToType
->getAs
<ObjCObjectPointerType
>();
2757 const ObjCObjectPointerType
*FromObjCPtr
=
2758 FromType
->getAs
<ObjCObjectPointerType
>();
2760 if (ToObjCPtr
&& FromObjCPtr
) {
2761 // If the pointee types are the same (ignoring qualifications),
2762 // then this is not a pointer conversion.
2763 if (Context
.hasSameUnqualifiedType(ToObjCPtr
->getPointeeType(),
2764 FromObjCPtr
->getPointeeType()))
2767 // Conversion between Objective-C pointers.
2768 if (Context
.canAssignObjCInterfaces(ToObjCPtr
, FromObjCPtr
)) {
2769 const ObjCInterfaceType
* LHS
= ToObjCPtr
->getInterfaceType();
2770 const ObjCInterfaceType
* RHS
= FromObjCPtr
->getInterfaceType();
2771 if (getLangOpts().CPlusPlus
&& LHS
&& RHS
&&
2772 !ToObjCPtr
->getPointeeType().isAtLeastAsQualifiedAs(
2773 FromObjCPtr
->getPointeeType()))
2775 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromObjCPtr
,
2776 ToObjCPtr
->getPointeeType(),
2778 ConvertedType
= AdoptQualifiers(Context
, ConvertedType
, FromQualifiers
);
2782 if (Context
.canAssignObjCInterfaces(FromObjCPtr
, ToObjCPtr
)) {
2783 // Okay: this is some kind of implicit downcast of Objective-C
2784 // interfaces, which is permitted. However, we're going to
2785 // complain about it.
2786 IncompatibleObjC
= true;
2787 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromObjCPtr
,
2788 ToObjCPtr
->getPointeeType(),
2790 ConvertedType
= AdoptQualifiers(Context
, ConvertedType
, FromQualifiers
);
2794 // Beyond this point, both types need to be C pointers or block pointers.
2795 QualType ToPointeeType
;
2796 if (const PointerType
*ToCPtr
= ToType
->getAs
<PointerType
>())
2797 ToPointeeType
= ToCPtr
->getPointeeType();
2798 else if (const BlockPointerType
*ToBlockPtr
=
2799 ToType
->getAs
<BlockPointerType
>()) {
2800 // Objective C++: We're able to convert from a pointer to any object
2801 // to a block pointer type.
2802 if (FromObjCPtr
&& FromObjCPtr
->isObjCBuiltinType()) {
2803 ConvertedType
= AdoptQualifiers(Context
, ToType
, FromQualifiers
);
2806 ToPointeeType
= ToBlockPtr
->getPointeeType();
2808 else if (FromType
->getAs
<BlockPointerType
>() &&
2809 ToObjCPtr
&& ToObjCPtr
->isObjCBuiltinType()) {
2810 // Objective C++: We're able to convert from a block pointer type to a
2811 // pointer to any object.
2812 ConvertedType
= AdoptQualifiers(Context
, ToType
, FromQualifiers
);
2818 QualType FromPointeeType
;
2819 if (const PointerType
*FromCPtr
= FromType
->getAs
<PointerType
>())
2820 FromPointeeType
= FromCPtr
->getPointeeType();
2821 else if (const BlockPointerType
*FromBlockPtr
=
2822 FromType
->getAs
<BlockPointerType
>())
2823 FromPointeeType
= FromBlockPtr
->getPointeeType();
2827 // If we have pointers to pointers, recursively check whether this
2828 // is an Objective-C conversion.
2829 if (FromPointeeType
->isPointerType() && ToPointeeType
->isPointerType() &&
2830 isObjCPointerConversion(FromPointeeType
, ToPointeeType
, ConvertedType
,
2831 IncompatibleObjC
)) {
2832 // We always complain about this conversion.
2833 IncompatibleObjC
= true;
2834 ConvertedType
= Context
.getPointerType(ConvertedType
);
2835 ConvertedType
= AdoptQualifiers(Context
, ConvertedType
, FromQualifiers
);
2838 // Allow conversion of pointee being objective-c pointer to another one;
2840 if (FromPointeeType
->getAs
<ObjCObjectPointerType
>() &&
2841 ToPointeeType
->getAs
<ObjCObjectPointerType
>() &&
2842 isObjCPointerConversion(FromPointeeType
, ToPointeeType
, ConvertedType
,
2843 IncompatibleObjC
)) {
2845 ConvertedType
= Context
.getPointerType(ConvertedType
);
2846 ConvertedType
= AdoptQualifiers(Context
, ConvertedType
, FromQualifiers
);
2850 // If we have pointers to functions or blocks, check whether the only
2851 // differences in the argument and result types are in Objective-C
2852 // pointer conversions. If so, we permit the conversion (but
2853 // complain about it).
2854 const FunctionProtoType
*FromFunctionType
2855 = FromPointeeType
->getAs
<FunctionProtoType
>();
2856 const FunctionProtoType
*ToFunctionType
2857 = ToPointeeType
->getAs
<FunctionProtoType
>();
2858 if (FromFunctionType
&& ToFunctionType
) {
2859 // If the function types are exactly the same, this isn't an
2860 // Objective-C pointer conversion.
2861 if (Context
.getCanonicalType(FromPointeeType
)
2862 == Context
.getCanonicalType(ToPointeeType
))
2865 // Perform the quick checks that will tell us whether these
2866 // function types are obviously different.
2867 if (FromFunctionType
->getNumParams() != ToFunctionType
->getNumParams() ||
2868 FromFunctionType
->isVariadic() != ToFunctionType
->isVariadic() ||
2869 FromFunctionType
->getMethodQuals() != ToFunctionType
->getMethodQuals())
2872 bool HasObjCConversion
= false;
2873 if (Context
.getCanonicalType(FromFunctionType
->getReturnType()) ==
2874 Context
.getCanonicalType(ToFunctionType
->getReturnType())) {
2875 // Okay, the types match exactly. Nothing to do.
2876 } else if (isObjCPointerConversion(FromFunctionType
->getReturnType(),
2877 ToFunctionType
->getReturnType(),
2878 ConvertedType
, IncompatibleObjC
)) {
2879 // Okay, we have an Objective-C pointer conversion.
2880 HasObjCConversion
= true;
2882 // Function types are too different. Abort.
2886 // Check argument types.
2887 for (unsigned ArgIdx
= 0, NumArgs
= FromFunctionType
->getNumParams();
2888 ArgIdx
!= NumArgs
; ++ArgIdx
) {
2889 QualType FromArgType
= FromFunctionType
->getParamType(ArgIdx
);
2890 QualType ToArgType
= ToFunctionType
->getParamType(ArgIdx
);
2891 if (Context
.getCanonicalType(FromArgType
)
2892 == Context
.getCanonicalType(ToArgType
)) {
2893 // Okay, the types match exactly. Nothing to do.
2894 } else if (isObjCPointerConversion(FromArgType
, ToArgType
,
2895 ConvertedType
, IncompatibleObjC
)) {
2896 // Okay, we have an Objective-C pointer conversion.
2897 HasObjCConversion
= true;
2899 // Argument types are too different. Abort.
2904 if (HasObjCConversion
) {
2905 // We had an Objective-C conversion. Allow this pointer
2906 // conversion, but complain about it.
2907 ConvertedType
= AdoptQualifiers(Context
, ToType
, FromQualifiers
);
2908 IncompatibleObjC
= true;
2916 /// Determine whether this is an Objective-C writeback conversion,
2917 /// used for parameter passing when performing automatic reference counting.
2919 /// \param FromType The type we're converting form.
2921 /// \param ToType The type we're converting to.
2923 /// \param ConvertedType The type that will be produced after applying
2924 /// this conversion.
2925 bool Sema::isObjCWritebackConversion(QualType FromType
, QualType ToType
,
2926 QualType
&ConvertedType
) {
2927 if (!getLangOpts().ObjCAutoRefCount
||
2928 Context
.hasSameUnqualifiedType(FromType
, ToType
))
2931 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2933 if (const PointerType
*ToPointer
= ToType
->getAs
<PointerType
>())
2934 ToPointee
= ToPointer
->getPointeeType();
2938 Qualifiers ToQuals
= ToPointee
.getQualifiers();
2939 if (!ToPointee
->isObjCLifetimeType() ||
2940 ToQuals
.getObjCLifetime() != Qualifiers::OCL_Autoreleasing
||
2941 !ToQuals
.withoutObjCLifetime().empty())
2944 // Argument must be a pointer to __strong to __weak.
2945 QualType FromPointee
;
2946 if (const PointerType
*FromPointer
= FromType
->getAs
<PointerType
>())
2947 FromPointee
= FromPointer
->getPointeeType();
2951 Qualifiers FromQuals
= FromPointee
.getQualifiers();
2952 if (!FromPointee
->isObjCLifetimeType() ||
2953 (FromQuals
.getObjCLifetime() != Qualifiers::OCL_Strong
&&
2954 FromQuals
.getObjCLifetime() != Qualifiers::OCL_Weak
))
2957 // Make sure that we have compatible qualifiers.
2958 FromQuals
.setObjCLifetime(Qualifiers::OCL_Autoreleasing
);
2959 if (!ToQuals
.compatiblyIncludes(FromQuals
))
2962 // Remove qualifiers from the pointee type we're converting from; they
2963 // aren't used in the compatibility check belong, and we'll be adding back
2964 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2965 FromPointee
= FromPointee
.getUnqualifiedType();
2967 // The unqualified form of the pointee types must be compatible.
2968 ToPointee
= ToPointee
.getUnqualifiedType();
2969 bool IncompatibleObjC
;
2970 if (Context
.typesAreCompatible(FromPointee
, ToPointee
))
2971 FromPointee
= ToPointee
;
2972 else if (!isObjCPointerConversion(FromPointee
, ToPointee
, FromPointee
,
2976 /// Construct the type we're converting to, which is a pointer to
2977 /// __autoreleasing pointee.
2978 FromPointee
= Context
.getQualifiedType(FromPointee
, FromQuals
);
2979 ConvertedType
= Context
.getPointerType(FromPointee
);
2983 bool Sema::IsBlockPointerConversion(QualType FromType
, QualType ToType
,
2984 QualType
& ConvertedType
) {
2985 QualType ToPointeeType
;
2986 if (const BlockPointerType
*ToBlockPtr
=
2987 ToType
->getAs
<BlockPointerType
>())
2988 ToPointeeType
= ToBlockPtr
->getPointeeType();
2992 QualType FromPointeeType
;
2993 if (const BlockPointerType
*FromBlockPtr
=
2994 FromType
->getAs
<BlockPointerType
>())
2995 FromPointeeType
= FromBlockPtr
->getPointeeType();
2998 // We have pointer to blocks, check whether the only
2999 // differences in the argument and result types are in Objective-C
3000 // pointer conversions. If so, we permit the conversion.
3002 const FunctionProtoType
*FromFunctionType
3003 = FromPointeeType
->getAs
<FunctionProtoType
>();
3004 const FunctionProtoType
*ToFunctionType
3005 = ToPointeeType
->getAs
<FunctionProtoType
>();
3007 if (!FromFunctionType
|| !ToFunctionType
)
3010 if (Context
.hasSameType(FromPointeeType
, ToPointeeType
))
3013 // Perform the quick checks that will tell us whether these
3014 // function types are obviously different.
3015 if (FromFunctionType
->getNumParams() != ToFunctionType
->getNumParams() ||
3016 FromFunctionType
->isVariadic() != ToFunctionType
->isVariadic())
3019 FunctionType::ExtInfo FromEInfo
= FromFunctionType
->getExtInfo();
3020 FunctionType::ExtInfo ToEInfo
= ToFunctionType
->getExtInfo();
3021 if (FromEInfo
!= ToEInfo
)
3024 bool IncompatibleObjC
= false;
3025 if (Context
.hasSameType(FromFunctionType
->getReturnType(),
3026 ToFunctionType
->getReturnType())) {
3027 // Okay, the types match exactly. Nothing to do.
3029 QualType RHS
= FromFunctionType
->getReturnType();
3030 QualType LHS
= ToFunctionType
->getReturnType();
3031 if ((!getLangOpts().CPlusPlus
|| !RHS
->isRecordType()) &&
3032 !RHS
.hasQualifiers() && LHS
.hasQualifiers())
3033 LHS
= LHS
.getUnqualifiedType();
3035 if (Context
.hasSameType(RHS
,LHS
)) {
3037 } else if (isObjCPointerConversion(RHS
, LHS
,
3038 ConvertedType
, IncompatibleObjC
)) {
3039 if (IncompatibleObjC
)
3041 // Okay, we have an Objective-C pointer conversion.
3047 // Check argument types.
3048 for (unsigned ArgIdx
= 0, NumArgs
= FromFunctionType
->getNumParams();
3049 ArgIdx
!= NumArgs
; ++ArgIdx
) {
3050 IncompatibleObjC
= false;
3051 QualType FromArgType
= FromFunctionType
->getParamType(ArgIdx
);
3052 QualType ToArgType
= ToFunctionType
->getParamType(ArgIdx
);
3053 if (Context
.hasSameType(FromArgType
, ToArgType
)) {
3054 // Okay, the types match exactly. Nothing to do.
3055 } else if (isObjCPointerConversion(ToArgType
, FromArgType
,
3056 ConvertedType
, IncompatibleObjC
)) {
3057 if (IncompatibleObjC
)
3059 // Okay, we have an Objective-C pointer conversion.
3061 // Argument types are too different. Abort.
3065 SmallVector
<FunctionProtoType::ExtParameterInfo
, 4> NewParamInfos
;
3066 bool CanUseToFPT
, CanUseFromFPT
;
3067 if (!Context
.mergeExtParameterInfo(ToFunctionType
, FromFunctionType
,
3068 CanUseToFPT
, CanUseFromFPT
,
3072 ConvertedType
= ToType
;
3080 ft_parameter_mismatch
,
3082 ft_qualifer_mismatch
,
3086 /// Attempts to get the FunctionProtoType from a Type. Handles
3087 /// MemberFunctionPointers properly.
3088 static const FunctionProtoType
*tryGetFunctionProtoType(QualType FromType
) {
3089 if (auto *FPT
= FromType
->getAs
<FunctionProtoType
>())
3092 if (auto *MPT
= FromType
->getAs
<MemberPointerType
>())
3093 return MPT
->getPointeeType()->getAs
<FunctionProtoType
>();
3098 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3099 /// function types. Catches different number of parameter, mismatch in
3100 /// parameter types, and different return types.
3101 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic
&PDiag
,
3102 QualType FromType
, QualType ToType
) {
3103 // If either type is not valid, include no extra info.
3104 if (FromType
.isNull() || ToType
.isNull()) {
3105 PDiag
<< ft_default
;
3109 // Get the function type from the pointers.
3110 if (FromType
->isMemberPointerType() && ToType
->isMemberPointerType()) {
3111 const auto *FromMember
= FromType
->castAs
<MemberPointerType
>(),
3112 *ToMember
= ToType
->castAs
<MemberPointerType
>();
3113 if (!Context
.hasSameType(FromMember
->getClass(), ToMember
->getClass())) {
3114 PDiag
<< ft_different_class
<< QualType(ToMember
->getClass(), 0)
3115 << QualType(FromMember
->getClass(), 0);
3118 FromType
= FromMember
->getPointeeType();
3119 ToType
= ToMember
->getPointeeType();
3122 if (FromType
->isPointerType())
3123 FromType
= FromType
->getPointeeType();
3124 if (ToType
->isPointerType())
3125 ToType
= ToType
->getPointeeType();
3127 // Remove references.
3128 FromType
= FromType
.getNonReferenceType();
3129 ToType
= ToType
.getNonReferenceType();
3131 // Don't print extra info for non-specialized template functions.
3132 if (FromType
->isInstantiationDependentType() &&
3133 !FromType
->getAs
<TemplateSpecializationType
>()) {
3134 PDiag
<< ft_default
;
3138 // No extra info for same types.
3139 if (Context
.hasSameType(FromType
, ToType
)) {
3140 PDiag
<< ft_default
;
3144 const FunctionProtoType
*FromFunction
= tryGetFunctionProtoType(FromType
),
3145 *ToFunction
= tryGetFunctionProtoType(ToType
);
3147 // Both types need to be function types.
3148 if (!FromFunction
|| !ToFunction
) {
3149 PDiag
<< ft_default
;
3153 if (FromFunction
->getNumParams() != ToFunction
->getNumParams()) {
3154 PDiag
<< ft_parameter_arity
<< ToFunction
->getNumParams()
3155 << FromFunction
->getNumParams();
3159 // Handle different parameter types.
3161 if (!FunctionParamTypesAreEqual(FromFunction
, ToFunction
, &ArgPos
)) {
3162 PDiag
<< ft_parameter_mismatch
<< ArgPos
+ 1
3163 << ToFunction
->getParamType(ArgPos
)
3164 << FromFunction
->getParamType(ArgPos
);
3168 // Handle different return type.
3169 if (!Context
.hasSameType(FromFunction
->getReturnType(),
3170 ToFunction
->getReturnType())) {
3171 PDiag
<< ft_return_type
<< ToFunction
->getReturnType()
3172 << FromFunction
->getReturnType();
3176 if (FromFunction
->getMethodQuals() != ToFunction
->getMethodQuals()) {
3177 PDiag
<< ft_qualifer_mismatch
<< ToFunction
->getMethodQuals()
3178 << FromFunction
->getMethodQuals();
3182 // Handle exception specification differences on canonical type (in C++17
3184 if (cast
<FunctionProtoType
>(FromFunction
->getCanonicalTypeUnqualified())
3186 cast
<FunctionProtoType
>(ToFunction
->getCanonicalTypeUnqualified())
3188 PDiag
<< ft_noexcept
;
3192 // Unable to find a difference, so add no extra info.
3193 PDiag
<< ft_default
;
3196 /// FunctionParamTypesAreEqual - This routine checks two function proto types
3197 /// for equality of their parameter types. Caller has already checked that
3198 /// they have same number of parameters. If the parameters are different,
3199 /// ArgPos will have the parameter index of the first different parameter.
3200 /// If `Reversed` is true, the parameters of `NewType` will be compared in
3201 /// reverse order. That's useful if one of the functions is being used as a C++20
3202 /// synthesized operator overload with a reversed parameter order.
3203 bool Sema::FunctionParamTypesAreEqual(ArrayRef
<QualType
> Old
,
3204 ArrayRef
<QualType
> New
, unsigned *ArgPos
,
3206 assert(llvm::size(Old
) == llvm::size(New
) &&
3207 "Can't compare parameters of functions with different number of "
3210 for (auto &&[Idx
, Type
] : llvm::enumerate(Old
)) {
3211 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3212 size_t J
= Reversed
? (llvm::size(New
) - Idx
- 1) : Idx
;
3214 // Ignore address spaces in pointee type. This is to disallow overloading
3215 // on __ptr32/__ptr64 address spaces.
3217 Context
.removePtrSizeAddrSpace(Type
.getUnqualifiedType());
3219 Context
.removePtrSizeAddrSpace((New
.begin() + J
)->getUnqualifiedType());
3221 if (!Context
.hasSameType(OldType
, NewType
)) {
3230 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType
*OldType
,
3231 const FunctionProtoType
*NewType
,
3232 unsigned *ArgPos
, bool Reversed
) {
3233 return FunctionParamTypesAreEqual(OldType
->param_types(),
3234 NewType
->param_types(), ArgPos
, Reversed
);
3237 /// CheckPointerConversion - Check the pointer conversion from the
3238 /// expression From to the type ToType. This routine checks for
3239 /// ambiguous or inaccessible derived-to-base pointer
3240 /// conversions for which IsPointerConversion has already returned
3241 /// true. It returns true and produces a diagnostic if there was an
3242 /// error, or returns false otherwise.
3243 bool Sema::CheckPointerConversion(Expr
*From
, QualType ToType
,
3245 CXXCastPath
& BasePath
,
3246 bool IgnoreBaseAccess
,
3248 QualType FromType
= From
->getType();
3249 bool IsCStyleOrFunctionalCast
= IgnoreBaseAccess
;
3253 if (Diagnose
&& !IsCStyleOrFunctionalCast
&& !FromType
->isAnyPointerType() &&
3254 From
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNotNull
) ==
3255 Expr::NPCK_ZeroExpression
) {
3256 if (Context
.hasSameUnqualifiedType(From
->getType(), Context
.BoolTy
))
3257 DiagRuntimeBehavior(From
->getExprLoc(), From
,
3258 PDiag(diag::warn_impcast_bool_to_null_pointer
)
3259 << ToType
<< From
->getSourceRange());
3260 else if (!isUnevaluatedContext())
3261 Diag(From
->getExprLoc(), diag::warn_non_literal_null_pointer
)
3262 << ToType
<< From
->getSourceRange();
3264 if (const PointerType
*ToPtrType
= ToType
->getAs
<PointerType
>()) {
3265 if (const PointerType
*FromPtrType
= FromType
->getAs
<PointerType
>()) {
3266 QualType FromPointeeType
= FromPtrType
->getPointeeType(),
3267 ToPointeeType
= ToPtrType
->getPointeeType();
3269 if (FromPointeeType
->isRecordType() && ToPointeeType
->isRecordType() &&
3270 !Context
.hasSameUnqualifiedType(FromPointeeType
, ToPointeeType
)) {
3271 // We must have a derived-to-base conversion. Check an
3272 // ambiguous or inaccessible conversion.
3273 unsigned InaccessibleID
= 0;
3274 unsigned AmbiguousID
= 0;
3276 InaccessibleID
= diag::err_upcast_to_inaccessible_base
;
3277 AmbiguousID
= diag::err_ambiguous_derived_to_base_conv
;
3279 if (CheckDerivedToBaseConversion(
3280 FromPointeeType
, ToPointeeType
, InaccessibleID
, AmbiguousID
,
3281 From
->getExprLoc(), From
->getSourceRange(), DeclarationName(),
3282 &BasePath
, IgnoreBaseAccess
))
3285 // The conversion was successful.
3286 Kind
= CK_DerivedToBase
;
3289 if (Diagnose
&& !IsCStyleOrFunctionalCast
&&
3290 FromPointeeType
->isFunctionType() && ToPointeeType
->isVoidType()) {
3291 assert(getLangOpts().MSVCCompat
&&
3292 "this should only be possible with MSVCCompat!");
3293 Diag(From
->getExprLoc(), diag::ext_ms_impcast_fn_obj
)
3294 << From
->getSourceRange();
3297 } else if (const ObjCObjectPointerType
*ToPtrType
=
3298 ToType
->getAs
<ObjCObjectPointerType
>()) {
3299 if (const ObjCObjectPointerType
*FromPtrType
=
3300 FromType
->getAs
<ObjCObjectPointerType
>()) {
3301 // Objective-C++ conversions are always okay.
3302 // FIXME: We should have a different class of conversions for the
3303 // Objective-C++ implicit conversions.
3304 if (FromPtrType
->isObjCBuiltinType() || ToPtrType
->isObjCBuiltinType())
3306 } else if (FromType
->isBlockPointerType()) {
3307 Kind
= CK_BlockPointerToObjCPointerCast
;
3309 Kind
= CK_CPointerToObjCPointerCast
;
3311 } else if (ToType
->isBlockPointerType()) {
3312 if (!FromType
->isBlockPointerType())
3313 Kind
= CK_AnyPointerToBlockPointerCast
;
3316 // We shouldn't fall into this case unless it's valid for other
3318 if (From
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
))
3319 Kind
= CK_NullToPointer
;
3324 /// IsMemberPointerConversion - Determines whether the conversion of the
3325 /// expression From, which has the (possibly adjusted) type FromType, can be
3326 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3327 /// If so, returns true and places the converted type (that might differ from
3328 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3329 bool Sema::IsMemberPointerConversion(Expr
*From
, QualType FromType
,
3331 bool InOverloadResolution
,
3332 QualType
&ConvertedType
) {
3333 const MemberPointerType
*ToTypePtr
= ToType
->getAs
<MemberPointerType
>();
3337 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3338 if (From
->isNullPointerConstant(Context
,
3339 InOverloadResolution
? Expr::NPC_ValueDependentIsNotNull
3340 : Expr::NPC_ValueDependentIsNull
)) {
3341 ConvertedType
= ToType
;
3345 // Otherwise, both types have to be member pointers.
3346 const MemberPointerType
*FromTypePtr
= FromType
->getAs
<MemberPointerType
>();
3350 // A pointer to member of B can be converted to a pointer to member of D,
3351 // where D is derived from B (C++ 4.11p2).
3352 QualType
FromClass(FromTypePtr
->getClass(), 0);
3353 QualType
ToClass(ToTypePtr
->getClass(), 0);
3355 if (!Context
.hasSameUnqualifiedType(FromClass
, ToClass
) &&
3356 IsDerivedFrom(From
->getBeginLoc(), ToClass
, FromClass
)) {
3357 ConvertedType
= Context
.getMemberPointerType(FromTypePtr
->getPointeeType(),
3358 ToClass
.getTypePtr());
3365 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3366 /// expression From to the type ToType. This routine checks for ambiguous or
3367 /// virtual or inaccessible base-to-derived member pointer conversions
3368 /// for which IsMemberPointerConversion has already returned true. It returns
3369 /// true and produces a diagnostic if there was an error, or returns false
3371 bool Sema::CheckMemberPointerConversion(Expr
*From
, QualType ToType
,
3373 CXXCastPath
&BasePath
,
3374 bool IgnoreBaseAccess
) {
3375 QualType FromType
= From
->getType();
3376 const MemberPointerType
*FromPtrType
= FromType
->getAs
<MemberPointerType
>();
3378 // This must be a null pointer to member pointer conversion
3379 assert(From
->isNullPointerConstant(Context
,
3380 Expr::NPC_ValueDependentIsNull
) &&
3381 "Expr must be null pointer constant!");
3382 Kind
= CK_NullToMemberPointer
;
3386 const MemberPointerType
*ToPtrType
= ToType
->getAs
<MemberPointerType
>();
3387 assert(ToPtrType
&& "No member pointer cast has a target type "
3388 "that is not a member pointer.");
3390 QualType FromClass
= QualType(FromPtrType
->getClass(), 0);
3391 QualType ToClass
= QualType(ToPtrType
->getClass(), 0);
3393 // FIXME: What about dependent types?
3394 assert(FromClass
->isRecordType() && "Pointer into non-class.");
3395 assert(ToClass
->isRecordType() && "Pointer into non-class.");
3397 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3398 /*DetectVirtual=*/true);
3399 bool DerivationOkay
=
3400 IsDerivedFrom(From
->getBeginLoc(), ToClass
, FromClass
, Paths
);
3401 assert(DerivationOkay
&&
3402 "Should not have been called if derivation isn't OK.");
3403 (void)DerivationOkay
;
3405 if (Paths
.isAmbiguous(Context
.getCanonicalType(FromClass
).
3406 getUnqualifiedType())) {
3407 std::string PathDisplayStr
= getAmbiguousPathsDisplayString(Paths
);
3408 Diag(From
->getExprLoc(), diag::err_ambiguous_memptr_conv
)
3409 << 0 << FromClass
<< ToClass
<< PathDisplayStr
<< From
->getSourceRange();
3413 if (const RecordType
*VBase
= Paths
.getDetectedVirtual()) {
3414 Diag(From
->getExprLoc(), diag::err_memptr_conv_via_virtual
)
3415 << FromClass
<< ToClass
<< QualType(VBase
, 0)
3416 << From
->getSourceRange();
3420 if (!IgnoreBaseAccess
)
3421 CheckBaseClassAccess(From
->getExprLoc(), FromClass
, ToClass
,
3423 diag::err_downcast_from_inaccessible_base
);
3425 // Must be a base to derived member conversion.
3426 BuildBasePathArray(Paths
, BasePath
);
3427 Kind
= CK_BaseToDerivedMemberPointer
;
3431 /// Determine whether the lifetime conversion between the two given
3432 /// qualifiers sets is nontrivial.
3433 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals
,
3434 Qualifiers ToQuals
) {
3435 // Converting anything to const __unsafe_unretained is trivial.
3436 if (ToQuals
.hasConst() &&
3437 ToQuals
.getObjCLifetime() == Qualifiers::OCL_ExplicitNone
)
3443 /// Perform a single iteration of the loop for checking if a qualification
3444 /// conversion is valid.
3446 /// Specifically, check whether any change between the qualifiers of \p
3447 /// FromType and \p ToType is permissible, given knowledge about whether every
3448 /// outer layer is const-qualified.
3449 static bool isQualificationConversionStep(QualType FromType
, QualType ToType
,
3450 bool CStyle
, bool IsTopLevel
,
3451 bool &PreviousToQualsIncludeConst
,
3452 bool &ObjCLifetimeConversion
) {
3453 Qualifiers FromQuals
= FromType
.getQualifiers();
3454 Qualifiers ToQuals
= ToType
.getQualifiers();
3456 // Ignore __unaligned qualifier.
3457 FromQuals
.removeUnaligned();
3460 // Check Objective-C lifetime conversions.
3461 if (FromQuals
.getObjCLifetime() != ToQuals
.getObjCLifetime()) {
3462 if (ToQuals
.compatiblyIncludesObjCLifetime(FromQuals
)) {
3463 if (isNonTrivialObjCLifetimeConversion(FromQuals
, ToQuals
))
3464 ObjCLifetimeConversion
= true;
3465 FromQuals
.removeObjCLifetime();
3466 ToQuals
.removeObjCLifetime();
3468 // Qualification conversions cannot cast between different
3469 // Objective-C lifetime qualifiers.
3474 // Allow addition/removal of GC attributes but not changing GC attributes.
3475 if (FromQuals
.getObjCGCAttr() != ToQuals
.getObjCGCAttr() &&
3476 (!FromQuals
.hasObjCGCAttr() || !ToQuals
.hasObjCGCAttr())) {
3477 FromQuals
.removeObjCGCAttr();
3478 ToQuals
.removeObjCGCAttr();
3481 // -- for every j > 0, if const is in cv 1,j then const is in cv
3482 // 2,j, and similarly for volatile.
3483 if (!CStyle
&& !ToQuals
.compatiblyIncludes(FromQuals
))
3486 // If address spaces mismatch:
3487 // - in top level it is only valid to convert to addr space that is a
3488 // superset in all cases apart from C-style casts where we allow
3489 // conversions between overlapping address spaces.
3490 // - in non-top levels it is not a valid conversion.
3491 if (ToQuals
.getAddressSpace() != FromQuals
.getAddressSpace() &&
3493 !(ToQuals
.isAddressSpaceSupersetOf(FromQuals
) ||
3494 (CStyle
&& FromQuals
.isAddressSpaceSupersetOf(ToQuals
)))))
3497 // -- if the cv 1,j and cv 2,j are different, then const is in
3498 // every cv for 0 < k < j.
3499 if (!CStyle
&& FromQuals
.getCVRQualifiers() != ToQuals
.getCVRQualifiers() &&
3500 !PreviousToQualsIncludeConst
)
3503 // The following wording is from C++20, where the result of the conversion
3505 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3506 // "array of unknown bound of"
3507 if (FromType
->isIncompleteArrayType() && !ToType
->isIncompleteArrayType())
3510 // -- if the resulting P3,i is different from P1,i [...], then const is
3511 // added to every cv 3_k for 0 < k < i.
3512 if (!CStyle
&& FromType
->isConstantArrayType() &&
3513 ToType
->isIncompleteArrayType() && !PreviousToQualsIncludeConst
)
3516 // Keep track of whether all prior cv-qualifiers in the "to" type
3518 PreviousToQualsIncludeConst
=
3519 PreviousToQualsIncludeConst
&& ToQuals
.hasConst();
3523 /// IsQualificationConversion - Determines whether the conversion from
3524 /// an rvalue of type FromType to ToType is a qualification conversion
3527 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3528 /// when the qualification conversion involves a change in the Objective-C
3529 /// object lifetime.
3531 Sema::IsQualificationConversion(QualType FromType
, QualType ToType
,
3532 bool CStyle
, bool &ObjCLifetimeConversion
) {
3533 FromType
= Context
.getCanonicalType(FromType
);
3534 ToType
= Context
.getCanonicalType(ToType
);
3535 ObjCLifetimeConversion
= false;
3537 // If FromType and ToType are the same type, this is not a
3538 // qualification conversion.
3539 if (FromType
.getUnqualifiedType() == ToType
.getUnqualifiedType())
3543 // A conversion can add cv-qualifiers at levels other than the first
3544 // in multi-level pointers, subject to the following rules: [...]
3545 bool PreviousToQualsIncludeConst
= true;
3546 bool UnwrappedAnyPointer
= false;
3547 while (Context
.UnwrapSimilarTypes(FromType
, ToType
)) {
3548 if (!isQualificationConversionStep(
3549 FromType
, ToType
, CStyle
, !UnwrappedAnyPointer
,
3550 PreviousToQualsIncludeConst
, ObjCLifetimeConversion
))
3552 UnwrappedAnyPointer
= true;
3555 // We are left with FromType and ToType being the pointee types
3556 // after unwrapping the original FromType and ToType the same number
3557 // of times. If we unwrapped any pointers, and if FromType and
3558 // ToType have the same unqualified type (since we checked
3559 // qualifiers above), then this is a qualification conversion.
3560 return UnwrappedAnyPointer
&& Context
.hasSameUnqualifiedType(FromType
,ToType
);
3563 /// - Determine whether this is a conversion from a scalar type to an
3566 /// If successful, updates \c SCS's second and third steps in the conversion
3567 /// sequence to finish the conversion.
3568 static bool tryAtomicConversion(Sema
&S
, Expr
*From
, QualType ToType
,
3569 bool InOverloadResolution
,
3570 StandardConversionSequence
&SCS
,
3572 const AtomicType
*ToAtomic
= ToType
->getAs
<AtomicType
>();
3576 StandardConversionSequence InnerSCS
;
3577 if (!IsStandardConversion(S
, From
, ToAtomic
->getValueType(),
3578 InOverloadResolution
, InnerSCS
,
3579 CStyle
, /*AllowObjCWritebackConversion=*/false))
3582 SCS
.Second
= InnerSCS
.Second
;
3583 SCS
.setToType(1, InnerSCS
.getToType(1));
3584 SCS
.Third
= InnerSCS
.Third
;
3585 SCS
.QualificationIncludesObjCLifetime
3586 = InnerSCS
.QualificationIncludesObjCLifetime
;
3587 SCS
.setToType(2, InnerSCS
.getToType(2));
3591 static bool isFirstArgumentCompatibleWithType(ASTContext
&Context
,
3592 CXXConstructorDecl
*Constructor
,
3594 const auto *CtorType
= Constructor
->getType()->castAs
<FunctionProtoType
>();
3595 if (CtorType
->getNumParams() > 0) {
3596 QualType FirstArg
= CtorType
->getParamType(0);
3597 if (Context
.hasSameUnqualifiedType(Type
, FirstArg
.getNonReferenceType()))
3603 static OverloadingResult
3604 IsInitializerListConstructorConversion(Sema
&S
, Expr
*From
, QualType ToType
,
3606 UserDefinedConversionSequence
&User
,
3607 OverloadCandidateSet
&CandidateSet
,
3608 bool AllowExplicit
) {
3609 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
3610 for (auto *D
: S
.LookupConstructors(To
)) {
3611 auto Info
= getConstructorInfo(D
);
3615 bool Usable
= !Info
.Constructor
->isInvalidDecl() &&
3616 S
.isInitListConstructor(Info
.Constructor
);
3618 bool SuppressUserConversions
= false;
3619 if (Info
.ConstructorTmpl
)
3620 S
.AddTemplateOverloadCandidate(Info
.ConstructorTmpl
, Info
.FoundDecl
,
3621 /*ExplicitArgs*/ nullptr, From
,
3622 CandidateSet
, SuppressUserConversions
,
3623 /*PartialOverloading*/ false,
3626 S
.AddOverloadCandidate(Info
.Constructor
, Info
.FoundDecl
, From
,
3627 CandidateSet
, SuppressUserConversions
,
3628 /*PartialOverloading*/ false, AllowExplicit
);
3632 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
3634 OverloadCandidateSet::iterator Best
;
3635 switch (auto Result
=
3636 CandidateSet
.BestViableFunction(S
, From
->getBeginLoc(), Best
)) {
3639 // Record the standard conversion we used and the conversion function.
3640 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(Best
->Function
);
3641 QualType ThisType
= Constructor
->getFunctionObjectParameterType();
3642 // Initializer lists don't have conversions as such.
3643 User
.Before
.setAsIdentityConversion();
3644 User
.HadMultipleCandidates
= HadMultipleCandidates
;
3645 User
.ConversionFunction
= Constructor
;
3646 User
.FoundConversionFunction
= Best
->FoundDecl
;
3647 User
.After
.setAsIdentityConversion();
3648 User
.After
.setFromType(ThisType
);
3649 User
.After
.setAllToTypes(ToType
);
3653 case OR_No_Viable_Function
:
3654 return OR_No_Viable_Function
;
3656 return OR_Ambiguous
;
3659 llvm_unreachable("Invalid OverloadResult!");
3662 /// Determines whether there is a user-defined conversion sequence
3663 /// (C++ [over.ics.user]) that converts expression From to the type
3664 /// ToType. If such a conversion exists, User will contain the
3665 /// user-defined conversion sequence that performs such a conversion
3666 /// and this routine will return true. Otherwise, this routine returns
3667 /// false and User is unspecified.
3669 /// \param AllowExplicit true if the conversion should consider C++0x
3670 /// "explicit" conversion functions as well as non-explicit conversion
3671 /// functions (C++0x [class.conv.fct]p2).
3673 /// \param AllowObjCConversionOnExplicit true if the conversion should
3674 /// allow an extra Objective-C pointer conversion on uses of explicit
3675 /// constructors. Requires \c AllowExplicit to also be set.
3676 static OverloadingResult
3677 IsUserDefinedConversion(Sema
&S
, Expr
*From
, QualType ToType
,
3678 UserDefinedConversionSequence
&User
,
3679 OverloadCandidateSet
&CandidateSet
,
3680 AllowedExplicit AllowExplicit
,
3681 bool AllowObjCConversionOnExplicit
) {
3682 assert(AllowExplicit
!= AllowedExplicit::None
||
3683 !AllowObjCConversionOnExplicit
);
3684 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
3686 // Whether we will only visit constructors.
3687 bool ConstructorsOnly
= false;
3689 // If the type we are conversion to is a class type, enumerate its
3691 if (const RecordType
*ToRecordType
= ToType
->getAs
<RecordType
>()) {
3692 // C++ [over.match.ctor]p1:
3693 // When objects of class type are direct-initialized (8.5), or
3694 // copy-initialized from an expression of the same or a
3695 // derived class type (8.5), overload resolution selects the
3696 // constructor. [...] For copy-initialization, the candidate
3697 // functions are all the converting constructors (12.3.1) of
3698 // that class. The argument list is the expression-list within
3699 // the parentheses of the initializer.
3700 if (S
.Context
.hasSameUnqualifiedType(ToType
, From
->getType()) ||
3701 (From
->getType()->getAs
<RecordType
>() &&
3702 S
.IsDerivedFrom(From
->getBeginLoc(), From
->getType(), ToType
)))
3703 ConstructorsOnly
= true;
3705 if (!S
.isCompleteType(From
->getExprLoc(), ToType
)) {
3706 // We're not going to find any constructors.
3707 } else if (CXXRecordDecl
*ToRecordDecl
3708 = dyn_cast
<CXXRecordDecl
>(ToRecordType
->getDecl())) {
3710 Expr
**Args
= &From
;
3711 unsigned NumArgs
= 1;
3712 bool ListInitializing
= false;
3713 if (InitListExpr
*InitList
= dyn_cast
<InitListExpr
>(From
)) {
3714 // But first, see if there is an init-list-constructor that will work.
3715 OverloadingResult Result
= IsInitializerListConstructorConversion(
3716 S
, From
, ToType
, ToRecordDecl
, User
, CandidateSet
,
3717 AllowExplicit
== AllowedExplicit::All
);
3718 if (Result
!= OR_No_Viable_Function
)
3722 OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
3724 // If we're list-initializing, we pass the individual elements as
3725 // arguments, not the entire list.
3726 Args
= InitList
->getInits();
3727 NumArgs
= InitList
->getNumInits();
3728 ListInitializing
= true;
3731 for (auto *D
: S
.LookupConstructors(ToRecordDecl
)) {
3732 auto Info
= getConstructorInfo(D
);
3736 bool Usable
= !Info
.Constructor
->isInvalidDecl();
3737 if (!ListInitializing
)
3738 Usable
= Usable
&& Info
.Constructor
->isConvertingConstructor(
3739 /*AllowExplicit*/ true);
3741 bool SuppressUserConversions
= !ConstructorsOnly
;
3742 // C++20 [over.best.ics.general]/4.5:
3743 // if the target is the first parameter of a constructor [of class
3744 // X] and the constructor [...] is a candidate by [...] the second
3745 // phase of [over.match.list] when the initializer list has exactly
3746 // one element that is itself an initializer list, [...] and the
3747 // conversion is to X or reference to cv X, user-defined conversion
3748 // sequences are not cnosidered.
3749 if (SuppressUserConversions
&& ListInitializing
) {
3750 SuppressUserConversions
=
3751 NumArgs
== 1 && isa
<InitListExpr
>(Args
[0]) &&
3752 isFirstArgumentCompatibleWithType(S
.Context
, Info
.Constructor
,
3755 if (Info
.ConstructorTmpl
)
3756 S
.AddTemplateOverloadCandidate(
3757 Info
.ConstructorTmpl
, Info
.FoundDecl
,
3758 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args
, NumArgs
),
3759 CandidateSet
, SuppressUserConversions
,
3760 /*PartialOverloading*/ false,
3761 AllowExplicit
== AllowedExplicit::All
);
3763 // Allow one user-defined conversion when user specifies a
3764 // From->ToType conversion via an static cast (c-style, etc).
3765 S
.AddOverloadCandidate(Info
.Constructor
, Info
.FoundDecl
,
3766 llvm::ArrayRef(Args
, NumArgs
), CandidateSet
,
3767 SuppressUserConversions
,
3768 /*PartialOverloading*/ false,
3769 AllowExplicit
== AllowedExplicit::All
);
3775 // Enumerate conversion functions, if we're allowed to.
3776 if (ConstructorsOnly
|| isa
<InitListExpr
>(From
)) {
3777 } else if (!S
.isCompleteType(From
->getBeginLoc(), From
->getType())) {
3778 // No conversion functions from incomplete types.
3779 } else if (const RecordType
*FromRecordType
=
3780 From
->getType()->getAs
<RecordType
>()) {
3781 if (CXXRecordDecl
*FromRecordDecl
3782 = dyn_cast
<CXXRecordDecl
>(FromRecordType
->getDecl())) {
3783 // Add all of the conversion functions as candidates.
3784 const auto &Conversions
= FromRecordDecl
->getVisibleConversionFunctions();
3785 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
3786 DeclAccessPair FoundDecl
= I
.getPair();
3787 NamedDecl
*D
= FoundDecl
.getDecl();
3788 CXXRecordDecl
*ActingContext
= cast
<CXXRecordDecl
>(D
->getDeclContext());
3789 if (isa
<UsingShadowDecl
>(D
))
3790 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
3792 CXXConversionDecl
*Conv
;
3793 FunctionTemplateDecl
*ConvTemplate
;
3794 if ((ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
)))
3795 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
3797 Conv
= cast
<CXXConversionDecl
>(D
);
3800 S
.AddTemplateConversionCandidate(
3801 ConvTemplate
, FoundDecl
, ActingContext
, From
, ToType
,
3802 CandidateSet
, AllowObjCConversionOnExplicit
,
3803 AllowExplicit
!= AllowedExplicit::None
);
3805 S
.AddConversionCandidate(Conv
, FoundDecl
, ActingContext
, From
, ToType
,
3806 CandidateSet
, AllowObjCConversionOnExplicit
,
3807 AllowExplicit
!= AllowedExplicit::None
);
3812 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
3814 OverloadCandidateSet::iterator Best
;
3815 switch (auto Result
=
3816 CandidateSet
.BestViableFunction(S
, From
->getBeginLoc(), Best
)) {
3819 // Record the standard conversion we used and the conversion function.
3820 if (CXXConstructorDecl
*Constructor
3821 = dyn_cast
<CXXConstructorDecl
>(Best
->Function
)) {
3822 // C++ [over.ics.user]p1:
3823 // If the user-defined conversion is specified by a
3824 // constructor (12.3.1), the initial standard conversion
3825 // sequence converts the source type to the type required by
3826 // the argument of the constructor.
3828 if (isa
<InitListExpr
>(From
)) {
3829 // Initializer lists don't have conversions as such.
3830 User
.Before
.setAsIdentityConversion();
3832 if (Best
->Conversions
[0].isEllipsis())
3833 User
.EllipsisConversion
= true;
3835 User
.Before
= Best
->Conversions
[0].Standard
;
3836 User
.EllipsisConversion
= false;
3839 User
.HadMultipleCandidates
= HadMultipleCandidates
;
3840 User
.ConversionFunction
= Constructor
;
3841 User
.FoundConversionFunction
= Best
->FoundDecl
;
3842 User
.After
.setAsIdentityConversion();
3843 User
.After
.setFromType(Constructor
->getFunctionObjectParameterType());
3844 User
.After
.setAllToTypes(ToType
);
3847 if (CXXConversionDecl
*Conversion
3848 = dyn_cast
<CXXConversionDecl
>(Best
->Function
)) {
3849 // C++ [over.ics.user]p1:
3851 // [...] If the user-defined conversion is specified by a
3852 // conversion function (12.3.2), the initial standard
3853 // conversion sequence converts the source type to the
3854 // implicit object parameter of the conversion function.
3855 User
.Before
= Best
->Conversions
[0].Standard
;
3856 User
.HadMultipleCandidates
= HadMultipleCandidates
;
3857 User
.ConversionFunction
= Conversion
;
3858 User
.FoundConversionFunction
= Best
->FoundDecl
;
3859 User
.EllipsisConversion
= false;
3861 // C++ [over.ics.user]p2:
3862 // The second standard conversion sequence converts the
3863 // result of the user-defined conversion to the target type
3864 // for the sequence. Since an implicit conversion sequence
3865 // is an initialization, the special rules for
3866 // initialization by user-defined conversion apply when
3867 // selecting the best user-defined conversion for a
3868 // user-defined conversion sequence (see 13.3.3 and
3870 User
.After
= Best
->FinalConversion
;
3873 llvm_unreachable("Not a constructor or conversion function?");
3875 case OR_No_Viable_Function
:
3876 return OR_No_Viable_Function
;
3879 return OR_Ambiguous
;
3882 llvm_unreachable("Invalid OverloadResult!");
3886 Sema::DiagnoseMultipleUserDefinedConversion(Expr
*From
, QualType ToType
) {
3887 ImplicitConversionSequence ICS
;
3888 OverloadCandidateSet
CandidateSet(From
->getExprLoc(),
3889 OverloadCandidateSet::CSK_Normal
);
3890 OverloadingResult OvResult
=
3891 IsUserDefinedConversion(*this, From
, ToType
, ICS
.UserDefined
,
3892 CandidateSet
, AllowedExplicit::None
, false);
3894 if (!(OvResult
== OR_Ambiguous
||
3895 (OvResult
== OR_No_Viable_Function
&& !CandidateSet
.empty())))
3898 auto Cands
= CandidateSet
.CompleteCandidates(
3900 OvResult
== OR_Ambiguous
? OCD_AmbiguousCandidates
: OCD_AllCandidates
,
3902 if (OvResult
== OR_Ambiguous
)
3903 Diag(From
->getBeginLoc(), diag::err_typecheck_ambiguous_condition
)
3904 << From
->getType() << ToType
<< From
->getSourceRange();
3905 else { // OR_No_Viable_Function && !CandidateSet.empty()
3906 if (!RequireCompleteType(From
->getBeginLoc(), ToType
,
3907 diag::err_typecheck_nonviable_condition_incomplete
,
3908 From
->getType(), From
->getSourceRange()))
3909 Diag(From
->getBeginLoc(), diag::err_typecheck_nonviable_condition
)
3910 << false << From
->getType() << From
->getSourceRange() << ToType
;
3913 CandidateSet
.NoteCandidates(
3914 *this, From
, Cands
);
3918 // Helper for compareConversionFunctions that gets the FunctionType that the
3919 // conversion-operator return value 'points' to, or nullptr.
3920 static const FunctionType
*
3921 getConversionOpReturnTyAsFunction(CXXConversionDecl
*Conv
) {
3922 const FunctionType
*ConvFuncTy
= Conv
->getType()->castAs
<FunctionType
>();
3923 const PointerType
*RetPtrTy
=
3924 ConvFuncTy
->getReturnType()->getAs
<PointerType
>();
3929 return RetPtrTy
->getPointeeType()->getAs
<FunctionType
>();
3932 /// Compare the user-defined conversion functions or constructors
3933 /// of two user-defined conversion sequences to determine whether any ordering
3935 static ImplicitConversionSequence::CompareKind
3936 compareConversionFunctions(Sema
&S
, FunctionDecl
*Function1
,
3937 FunctionDecl
*Function2
) {
3938 CXXConversionDecl
*Conv1
= dyn_cast_or_null
<CXXConversionDecl
>(Function1
);
3939 CXXConversionDecl
*Conv2
= dyn_cast_or_null
<CXXConversionDecl
>(Function2
);
3940 if (!Conv1
|| !Conv2
)
3941 return ImplicitConversionSequence::Indistinguishable
;
3943 if (!Conv1
->getParent()->isLambda() || !Conv2
->getParent()->isLambda())
3944 return ImplicitConversionSequence::Indistinguishable
;
3947 // If both conversion functions are implicitly-declared conversions from
3948 // a lambda closure type to a function pointer and a block pointer,
3949 // respectively, always prefer the conversion to a function pointer,
3950 // because the function pointer is more lightweight and is more likely
3951 // to keep code working.
3952 if (S
.getLangOpts().ObjC
&& S
.getLangOpts().CPlusPlus11
) {
3953 bool Block1
= Conv1
->getConversionType()->isBlockPointerType();
3954 bool Block2
= Conv2
->getConversionType()->isBlockPointerType();
3955 if (Block1
!= Block2
)
3956 return Block1
? ImplicitConversionSequence::Worse
3957 : ImplicitConversionSequence::Better
;
3960 // In order to support multiple calling conventions for the lambda conversion
3961 // operator (such as when the free and member function calling convention is
3962 // different), prefer the 'free' mechanism, followed by the calling-convention
3963 // of operator(). The latter is in place to support the MSVC-like solution of
3964 // defining ALL of the possible conversions in regards to calling-convention.
3965 const FunctionType
*Conv1FuncRet
= getConversionOpReturnTyAsFunction(Conv1
);
3966 const FunctionType
*Conv2FuncRet
= getConversionOpReturnTyAsFunction(Conv2
);
3968 if (Conv1FuncRet
&& Conv2FuncRet
&&
3969 Conv1FuncRet
->getCallConv() != Conv2FuncRet
->getCallConv()) {
3970 CallingConv Conv1CC
= Conv1FuncRet
->getCallConv();
3971 CallingConv Conv2CC
= Conv2FuncRet
->getCallConv();
3973 CXXMethodDecl
*CallOp
= Conv2
->getParent()->getLambdaCallOperator();
3974 const auto *CallOpProto
= CallOp
->getType()->castAs
<FunctionProtoType
>();
3976 CallingConv CallOpCC
=
3977 CallOp
->getType()->castAs
<FunctionType
>()->getCallConv();
3978 CallingConv DefaultFree
= S
.Context
.getDefaultCallingConvention(
3979 CallOpProto
->isVariadic(), /*IsCXXMethod=*/false);
3980 CallingConv DefaultMember
= S
.Context
.getDefaultCallingConvention(
3981 CallOpProto
->isVariadic(), /*IsCXXMethod=*/true);
3983 CallingConv PrefOrder
[] = {DefaultFree
, DefaultMember
, CallOpCC
};
3984 for (CallingConv CC
: PrefOrder
) {
3986 return ImplicitConversionSequence::Better
;
3988 return ImplicitConversionSequence::Worse
;
3992 return ImplicitConversionSequence::Indistinguishable
;
3995 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3996 const ImplicitConversionSequence
&ICS
) {
3997 return (ICS
.isStandard() && ICS
.Standard
.DeprecatedStringLiteralToCharPtr
) ||
3998 (ICS
.isUserDefined() &&
3999 ICS
.UserDefined
.Before
.DeprecatedStringLiteralToCharPtr
);
4002 /// CompareImplicitConversionSequences - Compare two implicit
4003 /// conversion sequences to determine whether one is better than the
4004 /// other or if they are indistinguishable (C++ 13.3.3.2).
4005 static ImplicitConversionSequence::CompareKind
4006 CompareImplicitConversionSequences(Sema
&S
, SourceLocation Loc
,
4007 const ImplicitConversionSequence
& ICS1
,
4008 const ImplicitConversionSequence
& ICS2
)
4010 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4011 // conversion sequences (as defined in 13.3.3.1)
4012 // -- a standard conversion sequence (13.3.3.1.1) is a better
4013 // conversion sequence than a user-defined conversion sequence or
4014 // an ellipsis conversion sequence, and
4015 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4016 // conversion sequence than an ellipsis conversion sequence
4019 // C++0x [over.best.ics]p10:
4020 // For the purpose of ranking implicit conversion sequences as
4021 // described in 13.3.3.2, the ambiguous conversion sequence is
4022 // treated as a user-defined sequence that is indistinguishable
4023 // from any other user-defined conversion sequence.
4025 // String literal to 'char *' conversion has been deprecated in C++03. It has
4026 // been removed from C++11. We still accept this conversion, if it happens at
4027 // the best viable function. Otherwise, this conversion is considered worse
4028 // than ellipsis conversion. Consider this as an extension; this is not in the
4029 // standard. For example:
4031 // int &f(...); // #1
4032 // void f(char*); // #2
4033 // void g() { int &r = f("foo"); }
4035 // In C++03, we pick #2 as the best viable function.
4036 // In C++11, we pick #1 as the best viable function, because ellipsis
4037 // conversion is better than string-literal to char* conversion (since there
4038 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4039 // convert arguments, #2 would be the best viable function in C++11.
4040 // If the best viable function has this conversion, a warning will be issued
4041 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4043 if (S
.getLangOpts().CPlusPlus11
&& !S
.getLangOpts().WritableStrings
&&
4044 hasDeprecatedStringLiteralToCharPtrConversion(ICS1
) !=
4045 hasDeprecatedStringLiteralToCharPtrConversion(ICS2
) &&
4046 // Ill-formedness must not differ
4047 ICS1
.isBad() == ICS2
.isBad())
4048 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1
)
4049 ? ImplicitConversionSequence::Worse
4050 : ImplicitConversionSequence::Better
;
4052 if (ICS1
.getKindRank() < ICS2
.getKindRank())
4053 return ImplicitConversionSequence::Better
;
4054 if (ICS2
.getKindRank() < ICS1
.getKindRank())
4055 return ImplicitConversionSequence::Worse
;
4057 // The following checks require both conversion sequences to be of
4059 if (ICS1
.getKind() != ICS2
.getKind())
4060 return ImplicitConversionSequence::Indistinguishable
;
4062 ImplicitConversionSequence::CompareKind Result
=
4063 ImplicitConversionSequence::Indistinguishable
;
4065 // Two implicit conversion sequences of the same form are
4066 // indistinguishable conversion sequences unless one of the
4067 // following rules apply: (C++ 13.3.3.2p3):
4069 // List-initialization sequence L1 is a better conversion sequence than
4070 // list-initialization sequence L2 if:
4071 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4073 // — L1 and L2 convert to arrays of the same element type, and either the
4074 // number of elements n_1 initialized by L1 is less than the number of
4075 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4076 // an array of unknown bound and L1 does not,
4077 // even if one of the other rules in this paragraph would otherwise apply.
4078 if (!ICS1
.isBad()) {
4079 bool StdInit1
= false, StdInit2
= false;
4080 if (ICS1
.hasInitializerListContainerType())
4081 StdInit1
= S
.isStdInitializerList(ICS1
.getInitializerListContainerType(),
4083 if (ICS2
.hasInitializerListContainerType())
4084 StdInit2
= S
.isStdInitializerList(ICS2
.getInitializerListContainerType(),
4086 if (StdInit1
!= StdInit2
)
4087 return StdInit1
? ImplicitConversionSequence::Better
4088 : ImplicitConversionSequence::Worse
;
4090 if (ICS1
.hasInitializerListContainerType() &&
4091 ICS2
.hasInitializerListContainerType())
4092 if (auto *CAT1
= S
.Context
.getAsConstantArrayType(
4093 ICS1
.getInitializerListContainerType()))
4094 if (auto *CAT2
= S
.Context
.getAsConstantArrayType(
4095 ICS2
.getInitializerListContainerType())) {
4096 if (S
.Context
.hasSameUnqualifiedType(CAT1
->getElementType(),
4097 CAT2
->getElementType())) {
4098 // Both to arrays of the same element type
4099 if (CAT1
->getSize() != CAT2
->getSize())
4100 // Different sized, the smaller wins
4101 return CAT1
->getSize().ult(CAT2
->getSize())
4102 ? ImplicitConversionSequence::Better
4103 : ImplicitConversionSequence::Worse
;
4104 if (ICS1
.isInitializerListOfIncompleteArray() !=
4105 ICS2
.isInitializerListOfIncompleteArray())
4106 // One is incomplete, it loses
4107 return ICS2
.isInitializerListOfIncompleteArray()
4108 ? ImplicitConversionSequence::Better
4109 : ImplicitConversionSequence::Worse
;
4114 if (ICS1
.isStandard())
4115 // Standard conversion sequence S1 is a better conversion sequence than
4116 // standard conversion sequence S2 if [...]
4117 Result
= CompareStandardConversionSequences(S
, Loc
,
4118 ICS1
.Standard
, ICS2
.Standard
);
4119 else if (ICS1
.isUserDefined()) {
4120 // User-defined conversion sequence U1 is a better conversion
4121 // sequence than another user-defined conversion sequence U2 if
4122 // they contain the same user-defined conversion function or
4123 // constructor and if the second standard conversion sequence of
4124 // U1 is better than the second standard conversion sequence of
4125 // U2 (C++ 13.3.3.2p3).
4126 if (ICS1
.UserDefined
.ConversionFunction
==
4127 ICS2
.UserDefined
.ConversionFunction
)
4128 Result
= CompareStandardConversionSequences(S
, Loc
,
4129 ICS1
.UserDefined
.After
,
4130 ICS2
.UserDefined
.After
);
4132 Result
= compareConversionFunctions(S
,
4133 ICS1
.UserDefined
.ConversionFunction
,
4134 ICS2
.UserDefined
.ConversionFunction
);
4140 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4141 // determine if one is a proper subset of the other.
4142 static ImplicitConversionSequence::CompareKind
4143 compareStandardConversionSubsets(ASTContext
&Context
,
4144 const StandardConversionSequence
& SCS1
,
4145 const StandardConversionSequence
& SCS2
) {
4146 ImplicitConversionSequence::CompareKind Result
4147 = ImplicitConversionSequence::Indistinguishable
;
4149 // the identity conversion sequence is considered to be a subsequence of
4150 // any non-identity conversion sequence
4151 if (SCS1
.isIdentityConversion() && !SCS2
.isIdentityConversion())
4152 return ImplicitConversionSequence::Better
;
4153 else if (!SCS1
.isIdentityConversion() && SCS2
.isIdentityConversion())
4154 return ImplicitConversionSequence::Worse
;
4156 if (SCS1
.Second
!= SCS2
.Second
) {
4157 if (SCS1
.Second
== ICK_Identity
)
4158 Result
= ImplicitConversionSequence::Better
;
4159 else if (SCS2
.Second
== ICK_Identity
)
4160 Result
= ImplicitConversionSequence::Worse
;
4162 return ImplicitConversionSequence::Indistinguishable
;
4163 } else if (!Context
.hasSimilarType(SCS1
.getToType(1), SCS2
.getToType(1)))
4164 return ImplicitConversionSequence::Indistinguishable
;
4166 if (SCS1
.Third
== SCS2
.Third
) {
4167 return Context
.hasSameType(SCS1
.getToType(2), SCS2
.getToType(2))? Result
4168 : ImplicitConversionSequence::Indistinguishable
;
4171 if (SCS1
.Third
== ICK_Identity
)
4172 return Result
== ImplicitConversionSequence::Worse
4173 ? ImplicitConversionSequence::Indistinguishable
4174 : ImplicitConversionSequence::Better
;
4176 if (SCS2
.Third
== ICK_Identity
)
4177 return Result
== ImplicitConversionSequence::Better
4178 ? ImplicitConversionSequence::Indistinguishable
4179 : ImplicitConversionSequence::Worse
;
4181 return ImplicitConversionSequence::Indistinguishable
;
4184 /// Determine whether one of the given reference bindings is better
4185 /// than the other based on what kind of bindings they are.
4187 isBetterReferenceBindingKind(const StandardConversionSequence
&SCS1
,
4188 const StandardConversionSequence
&SCS2
) {
4189 // C++0x [over.ics.rank]p3b4:
4190 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4191 // implicit object parameter of a non-static member function declared
4192 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4193 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4194 // lvalue reference to a function lvalue and S2 binds an rvalue
4197 // FIXME: Rvalue references. We're going rogue with the above edits,
4198 // because the semantics in the current C++0x working paper (N3225 at the
4199 // time of this writing) break the standard definition of std::forward
4200 // and std::reference_wrapper when dealing with references to functions.
4201 // Proposed wording changes submitted to CWG for consideration.
4202 if (SCS1
.BindsImplicitObjectArgumentWithoutRefQualifier
||
4203 SCS2
.BindsImplicitObjectArgumentWithoutRefQualifier
)
4206 return (!SCS1
.IsLvalueReference
&& SCS1
.BindsToRvalue
&&
4207 SCS2
.IsLvalueReference
) ||
4208 (SCS1
.IsLvalueReference
&& SCS1
.BindsToFunctionLvalue
&&
4209 !SCS2
.IsLvalueReference
&& SCS2
.BindsToFunctionLvalue
);
4212 enum class FixedEnumPromotion
{
4215 ToPromotedUnderlyingType
4218 /// Returns kind of fixed enum promotion the \a SCS uses.
4219 static FixedEnumPromotion
4220 getFixedEnumPromtion(Sema
&S
, const StandardConversionSequence
&SCS
) {
4222 if (SCS
.Second
!= ICK_Integral_Promotion
)
4223 return FixedEnumPromotion::None
;
4225 QualType FromType
= SCS
.getFromType();
4226 if (!FromType
->isEnumeralType())
4227 return FixedEnumPromotion::None
;
4229 EnumDecl
*Enum
= FromType
->castAs
<EnumType
>()->getDecl();
4230 if (!Enum
->isFixed())
4231 return FixedEnumPromotion::None
;
4233 QualType UnderlyingType
= Enum
->getIntegerType();
4234 if (S
.Context
.hasSameType(SCS
.getToType(1), UnderlyingType
))
4235 return FixedEnumPromotion::ToUnderlyingType
;
4237 return FixedEnumPromotion::ToPromotedUnderlyingType
;
4240 /// CompareStandardConversionSequences - Compare two standard
4241 /// conversion sequences to determine whether one is better than the
4242 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4243 static ImplicitConversionSequence::CompareKind
4244 CompareStandardConversionSequences(Sema
&S
, SourceLocation Loc
,
4245 const StandardConversionSequence
& SCS1
,
4246 const StandardConversionSequence
& SCS2
)
4248 // Standard conversion sequence S1 is a better conversion sequence
4249 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4251 // -- S1 is a proper subsequence of S2 (comparing the conversion
4252 // sequences in the canonical form defined by 13.3.3.1.1,
4253 // excluding any Lvalue Transformation; the identity conversion
4254 // sequence is considered to be a subsequence of any
4255 // non-identity conversion sequence) or, if not that,
4256 if (ImplicitConversionSequence::CompareKind CK
4257 = compareStandardConversionSubsets(S
.Context
, SCS1
, SCS2
))
4260 // -- the rank of S1 is better than the rank of S2 (by the rules
4261 // defined below), or, if not that,
4262 ImplicitConversionRank Rank1
= SCS1
.getRank();
4263 ImplicitConversionRank Rank2
= SCS2
.getRank();
4265 return ImplicitConversionSequence::Better
;
4266 else if (Rank2
< Rank1
)
4267 return ImplicitConversionSequence::Worse
;
4269 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4270 // are indistinguishable unless one of the following rules
4273 // A conversion that is not a conversion of a pointer, or
4274 // pointer to member, to bool is better than another conversion
4275 // that is such a conversion.
4276 if (SCS1
.isPointerConversionToBool() != SCS2
.isPointerConversionToBool())
4277 return SCS2
.isPointerConversionToBool()
4278 ? ImplicitConversionSequence::Better
4279 : ImplicitConversionSequence::Worse
;
4281 // C++14 [over.ics.rank]p4b2:
4282 // This is retroactively applied to C++11 by CWG 1601.
4284 // A conversion that promotes an enumeration whose underlying type is fixed
4285 // to its underlying type is better than one that promotes to the promoted
4286 // underlying type, if the two are different.
4287 FixedEnumPromotion FEP1
= getFixedEnumPromtion(S
, SCS1
);
4288 FixedEnumPromotion FEP2
= getFixedEnumPromtion(S
, SCS2
);
4289 if (FEP1
!= FixedEnumPromotion::None
&& FEP2
!= FixedEnumPromotion::None
&&
4291 return FEP1
== FixedEnumPromotion::ToUnderlyingType
4292 ? ImplicitConversionSequence::Better
4293 : ImplicitConversionSequence::Worse
;
4295 // C++ [over.ics.rank]p4b2:
4297 // If class B is derived directly or indirectly from class A,
4298 // conversion of B* to A* is better than conversion of B* to
4299 // void*, and conversion of A* to void* is better than conversion
4301 bool SCS1ConvertsToVoid
4302 = SCS1
.isPointerConversionToVoidPointer(S
.Context
);
4303 bool SCS2ConvertsToVoid
4304 = SCS2
.isPointerConversionToVoidPointer(S
.Context
);
4305 if (SCS1ConvertsToVoid
!= SCS2ConvertsToVoid
) {
4306 // Exactly one of the conversion sequences is a conversion to
4307 // a void pointer; it's the worse conversion.
4308 return SCS2ConvertsToVoid
? ImplicitConversionSequence::Better
4309 : ImplicitConversionSequence::Worse
;
4310 } else if (!SCS1ConvertsToVoid
&& !SCS2ConvertsToVoid
) {
4311 // Neither conversion sequence converts to a void pointer; compare
4312 // their derived-to-base conversions.
4313 if (ImplicitConversionSequence::CompareKind DerivedCK
4314 = CompareDerivedToBaseConversions(S
, Loc
, SCS1
, SCS2
))
4316 } else if (SCS1ConvertsToVoid
&& SCS2ConvertsToVoid
&&
4317 !S
.Context
.hasSameType(SCS1
.getFromType(), SCS2
.getFromType())) {
4318 // Both conversion sequences are conversions to void
4319 // pointers. Compare the source types to determine if there's an
4320 // inheritance relationship in their sources.
4321 QualType FromType1
= SCS1
.getFromType();
4322 QualType FromType2
= SCS2
.getFromType();
4324 // Adjust the types we're converting from via the array-to-pointer
4325 // conversion, if we need to.
4326 if (SCS1
.First
== ICK_Array_To_Pointer
)
4327 FromType1
= S
.Context
.getArrayDecayedType(FromType1
);
4328 if (SCS2
.First
== ICK_Array_To_Pointer
)
4329 FromType2
= S
.Context
.getArrayDecayedType(FromType2
);
4331 QualType FromPointee1
= FromType1
->getPointeeType().getUnqualifiedType();
4332 QualType FromPointee2
= FromType2
->getPointeeType().getUnqualifiedType();
4334 if (S
.IsDerivedFrom(Loc
, FromPointee2
, FromPointee1
))
4335 return ImplicitConversionSequence::Better
;
4336 else if (S
.IsDerivedFrom(Loc
, FromPointee1
, FromPointee2
))
4337 return ImplicitConversionSequence::Worse
;
4339 // Objective-C++: If one interface is more specific than the
4340 // other, it is the better one.
4341 const ObjCObjectPointerType
* FromObjCPtr1
4342 = FromType1
->getAs
<ObjCObjectPointerType
>();
4343 const ObjCObjectPointerType
* FromObjCPtr2
4344 = FromType2
->getAs
<ObjCObjectPointerType
>();
4345 if (FromObjCPtr1
&& FromObjCPtr2
) {
4346 bool AssignLeft
= S
.Context
.canAssignObjCInterfaces(FromObjCPtr1
,
4348 bool AssignRight
= S
.Context
.canAssignObjCInterfaces(FromObjCPtr2
,
4350 if (AssignLeft
!= AssignRight
) {
4351 return AssignLeft
? ImplicitConversionSequence::Better
4352 : ImplicitConversionSequence::Worse
;
4357 if (SCS1
.ReferenceBinding
&& SCS2
.ReferenceBinding
) {
4358 // Check for a better reference binding based on the kind of bindings.
4359 if (isBetterReferenceBindingKind(SCS1
, SCS2
))
4360 return ImplicitConversionSequence::Better
;
4361 else if (isBetterReferenceBindingKind(SCS2
, SCS1
))
4362 return ImplicitConversionSequence::Worse
;
4365 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4367 if (ImplicitConversionSequence::CompareKind QualCK
4368 = CompareQualificationConversions(S
, SCS1
, SCS2
))
4371 if (SCS1
.ReferenceBinding
&& SCS2
.ReferenceBinding
) {
4372 // C++ [over.ics.rank]p3b4:
4373 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4374 // which the references refer are the same type except for
4375 // top-level cv-qualifiers, and the type to which the reference
4376 // initialized by S2 refers is more cv-qualified than the type
4377 // to which the reference initialized by S1 refers.
4378 QualType T1
= SCS1
.getToType(2);
4379 QualType T2
= SCS2
.getToType(2);
4380 T1
= S
.Context
.getCanonicalType(T1
);
4381 T2
= S
.Context
.getCanonicalType(T2
);
4382 Qualifiers T1Quals
, T2Quals
;
4383 QualType UnqualT1
= S
.Context
.getUnqualifiedArrayType(T1
, T1Quals
);
4384 QualType UnqualT2
= S
.Context
.getUnqualifiedArrayType(T2
, T2Quals
);
4385 if (UnqualT1
== UnqualT2
) {
4386 // Objective-C++ ARC: If the references refer to objects with different
4387 // lifetimes, prefer bindings that don't change lifetime.
4388 if (SCS1
.ObjCLifetimeConversionBinding
!=
4389 SCS2
.ObjCLifetimeConversionBinding
) {
4390 return SCS1
.ObjCLifetimeConversionBinding
4391 ? ImplicitConversionSequence::Worse
4392 : ImplicitConversionSequence::Better
;
4395 // If the type is an array type, promote the element qualifiers to the
4396 // type for comparison.
4397 if (isa
<ArrayType
>(T1
) && T1Quals
)
4398 T1
= S
.Context
.getQualifiedType(UnqualT1
, T1Quals
);
4399 if (isa
<ArrayType
>(T2
) && T2Quals
)
4400 T2
= S
.Context
.getQualifiedType(UnqualT2
, T2Quals
);
4401 if (T2
.isMoreQualifiedThan(T1
))
4402 return ImplicitConversionSequence::Better
;
4403 if (T1
.isMoreQualifiedThan(T2
))
4404 return ImplicitConversionSequence::Worse
;
4408 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4409 // floating-to-integral conversion if the integral conversion
4410 // is between types of the same size.
4418 // Here, MSVC will call f(int) instead of generating a compile error
4419 // as clang will do in standard mode.
4420 if (S
.getLangOpts().MSVCCompat
&&
4421 !S
.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8
) &&
4422 SCS1
.Second
== ICK_Integral_Conversion
&&
4423 SCS2
.Second
== ICK_Floating_Integral
&&
4424 S
.Context
.getTypeSize(SCS1
.getFromType()) ==
4425 S
.Context
.getTypeSize(SCS1
.getToType(2)))
4426 return ImplicitConversionSequence::Better
;
4428 // Prefer a compatible vector conversion over a lax vector conversion
4431 // typedef float __v4sf __attribute__((__vector_size__(16)));
4432 // void f(vector float);
4433 // void f(vector signed int);
4438 // Here, we'd like to choose f(vector float) and not
4439 // report an ambiguous call error
4440 if (SCS1
.Second
== ICK_Vector_Conversion
&&
4441 SCS2
.Second
== ICK_Vector_Conversion
) {
4442 bool SCS1IsCompatibleVectorConversion
= S
.Context
.areCompatibleVectorTypes(
4443 SCS1
.getFromType(), SCS1
.getToType(2));
4444 bool SCS2IsCompatibleVectorConversion
= S
.Context
.areCompatibleVectorTypes(
4445 SCS2
.getFromType(), SCS2
.getToType(2));
4447 if (SCS1IsCompatibleVectorConversion
!= SCS2IsCompatibleVectorConversion
)
4448 return SCS1IsCompatibleVectorConversion
4449 ? ImplicitConversionSequence::Better
4450 : ImplicitConversionSequence::Worse
;
4453 if (SCS1
.Second
== ICK_SVE_Vector_Conversion
&&
4454 SCS2
.Second
== ICK_SVE_Vector_Conversion
) {
4455 bool SCS1IsCompatibleSVEVectorConversion
=
4456 S
.Context
.areCompatibleSveTypes(SCS1
.getFromType(), SCS1
.getToType(2));
4457 bool SCS2IsCompatibleSVEVectorConversion
=
4458 S
.Context
.areCompatibleSveTypes(SCS2
.getFromType(), SCS2
.getToType(2));
4460 if (SCS1IsCompatibleSVEVectorConversion
!=
4461 SCS2IsCompatibleSVEVectorConversion
)
4462 return SCS1IsCompatibleSVEVectorConversion
4463 ? ImplicitConversionSequence::Better
4464 : ImplicitConversionSequence::Worse
;
4467 if (SCS1
.Second
== ICK_RVV_Vector_Conversion
&&
4468 SCS2
.Second
== ICK_RVV_Vector_Conversion
) {
4469 bool SCS1IsCompatibleRVVVectorConversion
=
4470 S
.Context
.areCompatibleRVVTypes(SCS1
.getFromType(), SCS1
.getToType(2));
4471 bool SCS2IsCompatibleRVVVectorConversion
=
4472 S
.Context
.areCompatibleRVVTypes(SCS2
.getFromType(), SCS2
.getToType(2));
4474 if (SCS1IsCompatibleRVVVectorConversion
!=
4475 SCS2IsCompatibleRVVVectorConversion
)
4476 return SCS1IsCompatibleRVVVectorConversion
4477 ? ImplicitConversionSequence::Better
4478 : ImplicitConversionSequence::Worse
;
4481 return ImplicitConversionSequence::Indistinguishable
;
4484 /// CompareQualificationConversions - Compares two standard conversion
4485 /// sequences to determine whether they can be ranked based on their
4486 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4487 static ImplicitConversionSequence::CompareKind
4488 CompareQualificationConversions(Sema
&S
,
4489 const StandardConversionSequence
& SCS1
,
4490 const StandardConversionSequence
& SCS2
) {
4491 // C++ [over.ics.rank]p3:
4492 // -- S1 and S2 differ only in their qualification conversion and
4493 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4495 // [...] and the cv-qualification signature of type T1 is a proper subset
4496 // of the cv-qualification signature of type T2, and S1 is not the
4497 // deprecated string literal array-to-pointer conversion (4.2).
4499 // [...] where T1 can be converted to T2 by a qualification conversion.
4500 if (SCS1
.First
!= SCS2
.First
|| SCS1
.Second
!= SCS2
.Second
||
4501 SCS1
.Third
!= SCS2
.Third
|| SCS1
.Third
!= ICK_Qualification
)
4502 return ImplicitConversionSequence::Indistinguishable
;
4504 // FIXME: the example in the standard doesn't use a qualification
4506 QualType T1
= SCS1
.getToType(2);
4507 QualType T2
= SCS2
.getToType(2);
4508 T1
= S
.Context
.getCanonicalType(T1
);
4509 T2
= S
.Context
.getCanonicalType(T2
);
4510 assert(!T1
->isReferenceType() && !T2
->isReferenceType());
4511 Qualifiers T1Quals
, T2Quals
;
4512 QualType UnqualT1
= S
.Context
.getUnqualifiedArrayType(T1
, T1Quals
);
4513 QualType UnqualT2
= S
.Context
.getUnqualifiedArrayType(T2
, T2Quals
);
4515 // If the types are the same, we won't learn anything by unwrapping
4517 if (UnqualT1
== UnqualT2
)
4518 return ImplicitConversionSequence::Indistinguishable
;
4520 // Don't ever prefer a standard conversion sequence that uses the deprecated
4521 // string literal array to pointer conversion.
4522 bool CanPick1
= !SCS1
.DeprecatedStringLiteralToCharPtr
;
4523 bool CanPick2
= !SCS2
.DeprecatedStringLiteralToCharPtr
;
4525 // Objective-C++ ARC:
4526 // Prefer qualification conversions not involving a change in lifetime
4527 // to qualification conversions that do change lifetime.
4528 if (SCS1
.QualificationIncludesObjCLifetime
&&
4529 !SCS2
.QualificationIncludesObjCLifetime
)
4531 if (SCS2
.QualificationIncludesObjCLifetime
&&
4532 !SCS1
.QualificationIncludesObjCLifetime
)
4535 bool ObjCLifetimeConversion
;
4537 !S
.IsQualificationConversion(T1
, T2
, false, ObjCLifetimeConversion
))
4539 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4540 // directions, so we can't short-cut this second check in general.
4542 !S
.IsQualificationConversion(T2
, T1
, false, ObjCLifetimeConversion
))
4545 if (CanPick1
!= CanPick2
)
4546 return CanPick1
? ImplicitConversionSequence::Better
4547 : ImplicitConversionSequence::Worse
;
4548 return ImplicitConversionSequence::Indistinguishable
;
4551 /// CompareDerivedToBaseConversions - Compares two standard conversion
4552 /// sequences to determine whether they can be ranked based on their
4553 /// various kinds of derived-to-base conversions (C++
4554 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4555 /// conversions between Objective-C interface types.
4556 static ImplicitConversionSequence::CompareKind
4557 CompareDerivedToBaseConversions(Sema
&S
, SourceLocation Loc
,
4558 const StandardConversionSequence
& SCS1
,
4559 const StandardConversionSequence
& SCS2
) {
4560 QualType FromType1
= SCS1
.getFromType();
4561 QualType ToType1
= SCS1
.getToType(1);
4562 QualType FromType2
= SCS2
.getFromType();
4563 QualType ToType2
= SCS2
.getToType(1);
4565 // Adjust the types we're converting from via the array-to-pointer
4566 // conversion, if we need to.
4567 if (SCS1
.First
== ICK_Array_To_Pointer
)
4568 FromType1
= S
.Context
.getArrayDecayedType(FromType1
);
4569 if (SCS2
.First
== ICK_Array_To_Pointer
)
4570 FromType2
= S
.Context
.getArrayDecayedType(FromType2
);
4572 // Canonicalize all of the types.
4573 FromType1
= S
.Context
.getCanonicalType(FromType1
);
4574 ToType1
= S
.Context
.getCanonicalType(ToType1
);
4575 FromType2
= S
.Context
.getCanonicalType(FromType2
);
4576 ToType2
= S
.Context
.getCanonicalType(ToType2
);
4578 // C++ [over.ics.rank]p4b3:
4580 // If class B is derived directly or indirectly from class A and
4581 // class C is derived directly or indirectly from B,
4583 // Compare based on pointer conversions.
4584 if (SCS1
.Second
== ICK_Pointer_Conversion
&&
4585 SCS2
.Second
== ICK_Pointer_Conversion
&&
4586 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4587 FromType1
->isPointerType() && FromType2
->isPointerType() &&
4588 ToType1
->isPointerType() && ToType2
->isPointerType()) {
4589 QualType FromPointee1
=
4590 FromType1
->castAs
<PointerType
>()->getPointeeType().getUnqualifiedType();
4591 QualType ToPointee1
=
4592 ToType1
->castAs
<PointerType
>()->getPointeeType().getUnqualifiedType();
4593 QualType FromPointee2
=
4594 FromType2
->castAs
<PointerType
>()->getPointeeType().getUnqualifiedType();
4595 QualType ToPointee2
=
4596 ToType2
->castAs
<PointerType
>()->getPointeeType().getUnqualifiedType();
4598 // -- conversion of C* to B* is better than conversion of C* to A*,
4599 if (FromPointee1
== FromPointee2
&& ToPointee1
!= ToPointee2
) {
4600 if (S
.IsDerivedFrom(Loc
, ToPointee1
, ToPointee2
))
4601 return ImplicitConversionSequence::Better
;
4602 else if (S
.IsDerivedFrom(Loc
, ToPointee2
, ToPointee1
))
4603 return ImplicitConversionSequence::Worse
;
4606 // -- conversion of B* to A* is better than conversion of C* to A*,
4607 if (FromPointee1
!= FromPointee2
&& ToPointee1
== ToPointee2
) {
4608 if (S
.IsDerivedFrom(Loc
, FromPointee2
, FromPointee1
))
4609 return ImplicitConversionSequence::Better
;
4610 else if (S
.IsDerivedFrom(Loc
, FromPointee1
, FromPointee2
))
4611 return ImplicitConversionSequence::Worse
;
4613 } else if (SCS1
.Second
== ICK_Pointer_Conversion
&&
4614 SCS2
.Second
== ICK_Pointer_Conversion
) {
4615 const ObjCObjectPointerType
*FromPtr1
4616 = FromType1
->getAs
<ObjCObjectPointerType
>();
4617 const ObjCObjectPointerType
*FromPtr2
4618 = FromType2
->getAs
<ObjCObjectPointerType
>();
4619 const ObjCObjectPointerType
*ToPtr1
4620 = ToType1
->getAs
<ObjCObjectPointerType
>();
4621 const ObjCObjectPointerType
*ToPtr2
4622 = ToType2
->getAs
<ObjCObjectPointerType
>();
4624 if (FromPtr1
&& FromPtr2
&& ToPtr1
&& ToPtr2
) {
4625 // Apply the same conversion ranking rules for Objective-C pointer types
4626 // that we do for C++ pointers to class types. However, we employ the
4627 // Objective-C pseudo-subtyping relationship used for assignment of
4628 // Objective-C pointer types.
4630 = S
.Context
.canAssignObjCInterfaces(FromPtr1
, FromPtr2
);
4631 bool FromAssignRight
4632 = S
.Context
.canAssignObjCInterfaces(FromPtr2
, FromPtr1
);
4634 = S
.Context
.canAssignObjCInterfaces(ToPtr1
, ToPtr2
);
4636 = S
.Context
.canAssignObjCInterfaces(ToPtr2
, ToPtr1
);
4638 // A conversion to an a non-id object pointer type or qualified 'id'
4639 // type is better than a conversion to 'id'.
4640 if (ToPtr1
->isObjCIdType() &&
4641 (ToPtr2
->isObjCQualifiedIdType() || ToPtr2
->getInterfaceDecl()))
4642 return ImplicitConversionSequence::Worse
;
4643 if (ToPtr2
->isObjCIdType() &&
4644 (ToPtr1
->isObjCQualifiedIdType() || ToPtr1
->getInterfaceDecl()))
4645 return ImplicitConversionSequence::Better
;
4647 // A conversion to a non-id object pointer type is better than a
4648 // conversion to a qualified 'id' type
4649 if (ToPtr1
->isObjCQualifiedIdType() && ToPtr2
->getInterfaceDecl())
4650 return ImplicitConversionSequence::Worse
;
4651 if (ToPtr2
->isObjCQualifiedIdType() && ToPtr1
->getInterfaceDecl())
4652 return ImplicitConversionSequence::Better
;
4654 // A conversion to an a non-Class object pointer type or qualified 'Class'
4655 // type is better than a conversion to 'Class'.
4656 if (ToPtr1
->isObjCClassType() &&
4657 (ToPtr2
->isObjCQualifiedClassType() || ToPtr2
->getInterfaceDecl()))
4658 return ImplicitConversionSequence::Worse
;
4659 if (ToPtr2
->isObjCClassType() &&
4660 (ToPtr1
->isObjCQualifiedClassType() || ToPtr1
->getInterfaceDecl()))
4661 return ImplicitConversionSequence::Better
;
4663 // A conversion to a non-Class object pointer type is better than a
4664 // conversion to a qualified 'Class' type.
4665 if (ToPtr1
->isObjCQualifiedClassType() && ToPtr2
->getInterfaceDecl())
4666 return ImplicitConversionSequence::Worse
;
4667 if (ToPtr2
->isObjCQualifiedClassType() && ToPtr1
->getInterfaceDecl())
4668 return ImplicitConversionSequence::Better
;
4670 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4671 if (S
.Context
.hasSameType(FromType1
, FromType2
) &&
4672 !FromPtr1
->isObjCIdType() && !FromPtr1
->isObjCClassType() &&
4673 (ToAssignLeft
!= ToAssignRight
)) {
4674 if (FromPtr1
->isSpecialized()) {
4675 // "conversion of B<A> * to B * is better than conversion of B * to
4678 FromPtr1
->getInterfaceDecl() == ToPtr1
->getInterfaceDecl();
4680 FromPtr1
->getInterfaceDecl() == ToPtr2
->getInterfaceDecl();
4683 return ImplicitConversionSequence::Better
;
4684 } else if (IsSecondSame
)
4685 return ImplicitConversionSequence::Worse
;
4687 return ToAssignLeft
? ImplicitConversionSequence::Worse
4688 : ImplicitConversionSequence::Better
;
4691 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4692 if (S
.Context
.hasSameUnqualifiedType(ToType1
, ToType2
) &&
4693 (FromAssignLeft
!= FromAssignRight
))
4694 return FromAssignLeft
? ImplicitConversionSequence::Better
4695 : ImplicitConversionSequence::Worse
;
4699 // Ranking of member-pointer types.
4700 if (SCS1
.Second
== ICK_Pointer_Member
&& SCS2
.Second
== ICK_Pointer_Member
&&
4701 FromType1
->isMemberPointerType() && FromType2
->isMemberPointerType() &&
4702 ToType1
->isMemberPointerType() && ToType2
->isMemberPointerType()) {
4703 const auto *FromMemPointer1
= FromType1
->castAs
<MemberPointerType
>();
4704 const auto *ToMemPointer1
= ToType1
->castAs
<MemberPointerType
>();
4705 const auto *FromMemPointer2
= FromType2
->castAs
<MemberPointerType
>();
4706 const auto *ToMemPointer2
= ToType2
->castAs
<MemberPointerType
>();
4707 const Type
*FromPointeeType1
= FromMemPointer1
->getClass();
4708 const Type
*ToPointeeType1
= ToMemPointer1
->getClass();
4709 const Type
*FromPointeeType2
= FromMemPointer2
->getClass();
4710 const Type
*ToPointeeType2
= ToMemPointer2
->getClass();
4711 QualType FromPointee1
= QualType(FromPointeeType1
, 0).getUnqualifiedType();
4712 QualType ToPointee1
= QualType(ToPointeeType1
, 0).getUnqualifiedType();
4713 QualType FromPointee2
= QualType(FromPointeeType2
, 0).getUnqualifiedType();
4714 QualType ToPointee2
= QualType(ToPointeeType2
, 0).getUnqualifiedType();
4715 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4716 if (FromPointee1
== FromPointee2
&& ToPointee1
!= ToPointee2
) {
4717 if (S
.IsDerivedFrom(Loc
, ToPointee1
, ToPointee2
))
4718 return ImplicitConversionSequence::Worse
;
4719 else if (S
.IsDerivedFrom(Loc
, ToPointee2
, ToPointee1
))
4720 return ImplicitConversionSequence::Better
;
4722 // conversion of B::* to C::* is better than conversion of A::* to C::*
4723 if (ToPointee1
== ToPointee2
&& FromPointee1
!= FromPointee2
) {
4724 if (S
.IsDerivedFrom(Loc
, FromPointee1
, FromPointee2
))
4725 return ImplicitConversionSequence::Better
;
4726 else if (S
.IsDerivedFrom(Loc
, FromPointee2
, FromPointee1
))
4727 return ImplicitConversionSequence::Worse
;
4731 if (SCS1
.Second
== ICK_Derived_To_Base
) {
4732 // -- conversion of C to B is better than conversion of C to A,
4733 // -- binding of an expression of type C to a reference of type
4734 // B& is better than binding an expression of type C to a
4735 // reference of type A&,
4736 if (S
.Context
.hasSameUnqualifiedType(FromType1
, FromType2
) &&
4737 !S
.Context
.hasSameUnqualifiedType(ToType1
, ToType2
)) {
4738 if (S
.IsDerivedFrom(Loc
, ToType1
, ToType2
))
4739 return ImplicitConversionSequence::Better
;
4740 else if (S
.IsDerivedFrom(Loc
, ToType2
, ToType1
))
4741 return ImplicitConversionSequence::Worse
;
4744 // -- conversion of B to A is better than conversion of C to A.
4745 // -- binding of an expression of type B to a reference of type
4746 // A& is better than binding an expression of type C to a
4747 // reference of type A&,
4748 if (!S
.Context
.hasSameUnqualifiedType(FromType1
, FromType2
) &&
4749 S
.Context
.hasSameUnqualifiedType(ToType1
, ToType2
)) {
4750 if (S
.IsDerivedFrom(Loc
, FromType2
, FromType1
))
4751 return ImplicitConversionSequence::Better
;
4752 else if (S
.IsDerivedFrom(Loc
, FromType1
, FromType2
))
4753 return ImplicitConversionSequence::Worse
;
4757 return ImplicitConversionSequence::Indistinguishable
;
4760 static QualType
withoutUnaligned(ASTContext
&Ctx
, QualType T
) {
4761 if (!T
.getQualifiers().hasUnaligned())
4765 T
= Ctx
.getUnqualifiedArrayType(T
, Q
);
4766 Q
.removeUnaligned();
4767 return Ctx
.getQualifiedType(T
, Q
);
4770 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4771 /// determine whether they are reference-compatible,
4772 /// reference-related, or incompatible, for use in C++ initialization by
4773 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4774 /// type, and the first type (T1) is the pointee type of the reference
4775 /// type being initialized.
4776 Sema::ReferenceCompareResult
4777 Sema::CompareReferenceRelationship(SourceLocation Loc
,
4778 QualType OrigT1
, QualType OrigT2
,
4779 ReferenceConversions
*ConvOut
) {
4780 assert(!OrigT1
->isReferenceType() &&
4781 "T1 must be the pointee type of the reference type");
4782 assert(!OrigT2
->isReferenceType() && "T2 cannot be a reference type");
4784 QualType T1
= Context
.getCanonicalType(OrigT1
);
4785 QualType T2
= Context
.getCanonicalType(OrigT2
);
4786 Qualifiers T1Quals
, T2Quals
;
4787 QualType UnqualT1
= Context
.getUnqualifiedArrayType(T1
, T1Quals
);
4788 QualType UnqualT2
= Context
.getUnqualifiedArrayType(T2
, T2Quals
);
4790 ReferenceConversions ConvTmp
;
4791 ReferenceConversions
&Conv
= ConvOut
? *ConvOut
: ConvTmp
;
4792 Conv
= ReferenceConversions();
4794 // C++2a [dcl.init.ref]p4:
4795 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4796 // reference-related to "cv2 T2" if T1 is similar to T2, or
4797 // T1 is a base class of T2.
4798 // "cv1 T1" is reference-compatible with "cv2 T2" if
4799 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4800 // "pointer to cv1 T1" via a standard conversion sequence.
4802 // Check for standard conversions we can apply to pointers: derived-to-base
4803 // conversions, ObjC pointer conversions, and function pointer conversions.
4804 // (Qualification conversions are checked last.)
4805 QualType ConvertedT2
;
4806 if (UnqualT1
== UnqualT2
) {
4808 } else if (isCompleteType(Loc
, OrigT2
) &&
4809 IsDerivedFrom(Loc
, UnqualT2
, UnqualT1
))
4810 Conv
|= ReferenceConversions::DerivedToBase
;
4811 else if (UnqualT1
->isObjCObjectOrInterfaceType() &&
4812 UnqualT2
->isObjCObjectOrInterfaceType() &&
4813 Context
.canBindObjCObjectType(UnqualT1
, UnqualT2
))
4814 Conv
|= ReferenceConversions::ObjC
;
4815 else if (UnqualT2
->isFunctionType() &&
4816 IsFunctionConversion(UnqualT2
, UnqualT1
, ConvertedT2
)) {
4817 Conv
|= ReferenceConversions::Function
;
4818 // No need to check qualifiers; function types don't have them.
4819 return Ref_Compatible
;
4821 bool ConvertedReferent
= Conv
!= 0;
4823 // We can have a qualification conversion. Compute whether the types are
4824 // similar at the same time.
4825 bool PreviousToQualsIncludeConst
= true;
4826 bool TopLevel
= true;
4831 // We will need a qualification conversion.
4832 Conv
|= ReferenceConversions::Qualification
;
4834 // Track whether we performed a qualification conversion anywhere other
4835 // than the top level. This matters for ranking reference bindings in
4836 // overload resolution.
4838 Conv
|= ReferenceConversions::NestedQualification
;
4840 // MS compiler ignores __unaligned qualifier for references; do the same.
4841 T1
= withoutUnaligned(Context
, T1
);
4842 T2
= withoutUnaligned(Context
, T2
);
4844 // If we find a qualifier mismatch, the types are not reference-compatible,
4845 // but are still be reference-related if they're similar.
4846 bool ObjCLifetimeConversion
= false;
4847 if (!isQualificationConversionStep(T2
, T1
, /*CStyle=*/false, TopLevel
,
4848 PreviousToQualsIncludeConst
,
4849 ObjCLifetimeConversion
))
4850 return (ConvertedReferent
|| Context
.hasSimilarType(T1
, T2
))
4854 // FIXME: Should we track this for any level other than the first?
4855 if (ObjCLifetimeConversion
)
4856 Conv
|= ReferenceConversions::ObjCLifetime
;
4859 } while (Context
.UnwrapSimilarTypes(T1
, T2
));
4861 // At this point, if the types are reference-related, we must either have the
4862 // same inner type (ignoring qualifiers), or must have already worked out how
4863 // to convert the referent.
4864 return (ConvertedReferent
|| Context
.hasSameUnqualifiedType(T1
, T2
))
4869 /// Look for a user-defined conversion to a value reference-compatible
4870 /// with DeclType. Return true if something definite is found.
4872 FindConversionForRefInit(Sema
&S
, ImplicitConversionSequence
&ICS
,
4873 QualType DeclType
, SourceLocation DeclLoc
,
4874 Expr
*Init
, QualType T2
, bool AllowRvalues
,
4875 bool AllowExplicit
) {
4876 assert(T2
->isRecordType() && "Can only find conversions of record types.");
4877 auto *T2RecordDecl
= cast
<CXXRecordDecl
>(T2
->castAs
<RecordType
>()->getDecl());
4879 OverloadCandidateSet
CandidateSet(
4880 DeclLoc
, OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
4881 const auto &Conversions
= T2RecordDecl
->getVisibleConversionFunctions();
4882 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
4884 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
4885 if (isa
<UsingShadowDecl
>(D
))
4886 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
4888 FunctionTemplateDecl
*ConvTemplate
4889 = dyn_cast
<FunctionTemplateDecl
>(D
);
4890 CXXConversionDecl
*Conv
;
4892 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
4894 Conv
= cast
<CXXConversionDecl
>(D
);
4897 // If we are initializing an rvalue reference, don't permit conversion
4898 // functions that return lvalues.
4899 if (!ConvTemplate
&& DeclType
->isRValueReferenceType()) {
4900 const ReferenceType
*RefType
4901 = Conv
->getConversionType()->getAs
<LValueReferenceType
>();
4902 if (RefType
&& !RefType
->getPointeeType()->isFunctionType())
4906 if (!ConvTemplate
&&
4907 S
.CompareReferenceRelationship(
4909 Conv
->getConversionType()
4910 .getNonReferenceType()
4911 .getUnqualifiedType(),
4912 DeclType
.getNonReferenceType().getUnqualifiedType()) ==
4913 Sema::Ref_Incompatible
)
4916 // If the conversion function doesn't return a reference type,
4917 // it can't be considered for this conversion. An rvalue reference
4918 // is only acceptable if its referencee is a function type.
4920 const ReferenceType
*RefType
=
4921 Conv
->getConversionType()->getAs
<ReferenceType
>();
4923 (!RefType
->isLValueReferenceType() &&
4924 !RefType
->getPointeeType()->isFunctionType()))
4929 S
.AddTemplateConversionCandidate(
4930 ConvTemplate
, I
.getPair(), ActingDC
, Init
, DeclType
, CandidateSet
,
4931 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit
);
4933 S
.AddConversionCandidate(
4934 Conv
, I
.getPair(), ActingDC
, Init
, DeclType
, CandidateSet
,
4935 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit
);
4938 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
4940 OverloadCandidateSet::iterator Best
;
4941 switch (CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
)) {
4943 // C++ [over.ics.ref]p1:
4945 // [...] If the parameter binds directly to the result of
4946 // applying a conversion function to the argument
4947 // expression, the implicit conversion sequence is a
4948 // user-defined conversion sequence (13.3.3.1.2), with the
4949 // second standard conversion sequence either an identity
4950 // conversion or, if the conversion function returns an
4951 // entity of a type that is a derived class of the parameter
4952 // type, a derived-to-base Conversion.
4953 if (!Best
->FinalConversion
.DirectBinding
)
4956 ICS
.setUserDefined();
4957 ICS
.UserDefined
.Before
= Best
->Conversions
[0].Standard
;
4958 ICS
.UserDefined
.After
= Best
->FinalConversion
;
4959 ICS
.UserDefined
.HadMultipleCandidates
= HadMultipleCandidates
;
4960 ICS
.UserDefined
.ConversionFunction
= Best
->Function
;
4961 ICS
.UserDefined
.FoundConversionFunction
= Best
->FoundDecl
;
4962 ICS
.UserDefined
.EllipsisConversion
= false;
4963 assert(ICS
.UserDefined
.After
.ReferenceBinding
&&
4964 ICS
.UserDefined
.After
.DirectBinding
&&
4965 "Expected a direct reference binding!");
4970 for (OverloadCandidateSet::iterator Cand
= CandidateSet
.begin();
4971 Cand
!= CandidateSet
.end(); ++Cand
)
4973 ICS
.Ambiguous
.addConversion(Cand
->FoundDecl
, Cand
->Function
);
4976 case OR_No_Viable_Function
:
4978 // There was no suitable conversion, or we found a deleted
4979 // conversion; continue with other checks.
4983 llvm_unreachable("Invalid OverloadResult!");
4986 /// Compute an implicit conversion sequence for reference
4988 static ImplicitConversionSequence
4989 TryReferenceInit(Sema
&S
, Expr
*Init
, QualType DeclType
,
4990 SourceLocation DeclLoc
,
4991 bool SuppressUserConversions
,
4992 bool AllowExplicit
) {
4993 assert(DeclType
->isReferenceType() && "Reference init needs a reference");
4995 // Most paths end in a failed conversion.
4996 ImplicitConversionSequence ICS
;
4997 ICS
.setBad(BadConversionSequence::no_conversion
, Init
, DeclType
);
4999 QualType T1
= DeclType
->castAs
<ReferenceType
>()->getPointeeType();
5000 QualType T2
= Init
->getType();
5002 // If the initializer is the address of an overloaded function, try
5003 // to resolve the overloaded function. If all goes well, T2 is the
5004 // type of the resulting function.
5005 if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
) {
5006 DeclAccessPair Found
;
5007 if (FunctionDecl
*Fn
= S
.ResolveAddressOfOverloadedFunction(Init
, DeclType
,
5012 // Compute some basic properties of the types and the initializer.
5013 bool isRValRef
= DeclType
->isRValueReferenceType();
5014 Expr::Classification InitCategory
= Init
->Classify(S
.Context
);
5016 Sema::ReferenceConversions RefConv
;
5017 Sema::ReferenceCompareResult RefRelationship
=
5018 S
.CompareReferenceRelationship(DeclLoc
, T1
, T2
, &RefConv
);
5020 auto SetAsReferenceBinding
= [&](bool BindsDirectly
) {
5022 ICS
.Standard
.First
= ICK_Identity
;
5023 // FIXME: A reference binding can be a function conversion too. We should
5024 // consider that when ordering reference-to-function bindings.
5025 ICS
.Standard
.Second
= (RefConv
& Sema::ReferenceConversions::DerivedToBase
)
5026 ? ICK_Derived_To_Base
5027 : (RefConv
& Sema::ReferenceConversions::ObjC
)
5028 ? ICK_Compatible_Conversion
5030 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5031 // a reference binding that performs a non-top-level qualification
5032 // conversion as a qualification conversion, not as an identity conversion.
5033 ICS
.Standard
.Third
= (RefConv
&
5034 Sema::ReferenceConversions::NestedQualification
)
5037 ICS
.Standard
.setFromType(T2
);
5038 ICS
.Standard
.setToType(0, T2
);
5039 ICS
.Standard
.setToType(1, T1
);
5040 ICS
.Standard
.setToType(2, T1
);
5041 ICS
.Standard
.ReferenceBinding
= true;
5042 ICS
.Standard
.DirectBinding
= BindsDirectly
;
5043 ICS
.Standard
.IsLvalueReference
= !isRValRef
;
5044 ICS
.Standard
.BindsToFunctionLvalue
= T2
->isFunctionType();
5045 ICS
.Standard
.BindsToRvalue
= InitCategory
.isRValue();
5046 ICS
.Standard
.BindsImplicitObjectArgumentWithoutRefQualifier
= false;
5047 ICS
.Standard
.ObjCLifetimeConversionBinding
=
5048 (RefConv
& Sema::ReferenceConversions::ObjCLifetime
) != 0;
5049 ICS
.Standard
.CopyConstructor
= nullptr;
5050 ICS
.Standard
.DeprecatedStringLiteralToCharPtr
= false;
5053 // C++0x [dcl.init.ref]p5:
5054 // A reference to type "cv1 T1" is initialized by an expression
5055 // of type "cv2 T2" as follows:
5057 // -- If reference is an lvalue reference and the initializer expression
5059 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5060 // reference-compatible with "cv2 T2," or
5062 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5063 if (InitCategory
.isLValue() && RefRelationship
== Sema::Ref_Compatible
) {
5064 // C++ [over.ics.ref]p1:
5065 // When a parameter of reference type binds directly (8.5.3)
5066 // to an argument expression, the implicit conversion sequence
5067 // is the identity conversion, unless the argument expression
5068 // has a type that is a derived class of the parameter type,
5069 // in which case the implicit conversion sequence is a
5070 // derived-to-base Conversion (13.3.3.1).
5071 SetAsReferenceBinding(/*BindsDirectly=*/true);
5073 // Nothing more to do: the inaccessibility/ambiguity check for
5074 // derived-to-base conversions is suppressed when we're
5075 // computing the implicit conversion sequence (C++
5076 // [over.best.ics]p2).
5080 // -- has a class type (i.e., T2 is a class type), where T1 is
5081 // not reference-related to T2, and can be implicitly
5082 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5083 // is reference-compatible with "cv3 T3" 92) (this
5084 // conversion is selected by enumerating the applicable
5085 // conversion functions (13.3.1.6) and choosing the best
5086 // one through overload resolution (13.3)),
5087 if (!SuppressUserConversions
&& T2
->isRecordType() &&
5088 S
.isCompleteType(DeclLoc
, T2
) &&
5089 RefRelationship
== Sema::Ref_Incompatible
) {
5090 if (FindConversionForRefInit(S
, ICS
, DeclType
, DeclLoc
,
5091 Init
, T2
, /*AllowRvalues=*/false,
5097 // -- Otherwise, the reference shall be an lvalue reference to a
5098 // non-volatile const type (i.e., cv1 shall be const), or the reference
5099 // shall be an rvalue reference.
5100 if (!isRValRef
&& (!T1
.isConstQualified() || T1
.isVolatileQualified())) {
5101 if (InitCategory
.isRValue() && RefRelationship
!= Sema::Ref_Incompatible
)
5102 ICS
.setBad(BadConversionSequence::lvalue_ref_to_rvalue
, Init
, DeclType
);
5106 // -- If the initializer expression
5108 // -- is an xvalue, class prvalue, array prvalue or function
5109 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5110 if (RefRelationship
== Sema::Ref_Compatible
&&
5111 (InitCategory
.isXValue() ||
5112 (InitCategory
.isPRValue() &&
5113 (T2
->isRecordType() || T2
->isArrayType())) ||
5114 (InitCategory
.isLValue() && T2
->isFunctionType()))) {
5115 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5116 // binding unless we're binding to a class prvalue.
5117 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5118 // allow the use of rvalue references in C++98/03 for the benefit of
5119 // standard library implementors; therefore, we need the xvalue check here.
5120 SetAsReferenceBinding(/*BindsDirectly=*/S
.getLangOpts().CPlusPlus11
||
5121 !(InitCategory
.isPRValue() || T2
->isRecordType()));
5125 // -- has a class type (i.e., T2 is a class type), where T1 is not
5126 // reference-related to T2, and can be implicitly converted to
5127 // an xvalue, class prvalue, or function lvalue of type
5128 // "cv3 T3", where "cv1 T1" is reference-compatible with
5131 // then the reference is bound to the value of the initializer
5132 // expression in the first case and to the result of the conversion
5133 // in the second case (or, in either case, to an appropriate base
5134 // class subobject).
5135 if (!SuppressUserConversions
&& RefRelationship
== Sema::Ref_Incompatible
&&
5136 T2
->isRecordType() && S
.isCompleteType(DeclLoc
, T2
) &&
5137 FindConversionForRefInit(S
, ICS
, DeclType
, DeclLoc
,
5138 Init
, T2
, /*AllowRvalues=*/true,
5140 // In the second case, if the reference is an rvalue reference
5141 // and the second standard conversion sequence of the
5142 // user-defined conversion sequence includes an lvalue-to-rvalue
5143 // conversion, the program is ill-formed.
5144 if (ICS
.isUserDefined() && isRValRef
&&
5145 ICS
.UserDefined
.After
.First
== ICK_Lvalue_To_Rvalue
)
5146 ICS
.setBad(BadConversionSequence::no_conversion
, Init
, DeclType
);
5151 // A temporary of function type cannot be created; don't even try.
5152 if (T1
->isFunctionType())
5155 // -- Otherwise, a temporary of type "cv1 T1" is created and
5156 // initialized from the initializer expression using the
5157 // rules for a non-reference copy initialization (8.5). The
5158 // reference is then bound to the temporary. If T1 is
5159 // reference-related to T2, cv1 must be the same
5160 // cv-qualification as, or greater cv-qualification than,
5161 // cv2; otherwise, the program is ill-formed.
5162 if (RefRelationship
== Sema::Ref_Related
) {
5163 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5164 // we would be reference-compatible or reference-compatible with
5165 // added qualification. But that wasn't the case, so the reference
5166 // initialization fails.
5168 // Note that we only want to check address spaces and cvr-qualifiers here.
5169 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5170 Qualifiers T1Quals
= T1
.getQualifiers();
5171 Qualifiers T2Quals
= T2
.getQualifiers();
5172 T1Quals
.removeObjCGCAttr();
5173 T1Quals
.removeObjCLifetime();
5174 T2Quals
.removeObjCGCAttr();
5175 T2Quals
.removeObjCLifetime();
5176 // MS compiler ignores __unaligned qualifier for references; do the same.
5177 T1Quals
.removeUnaligned();
5178 T2Quals
.removeUnaligned();
5179 if (!T1Quals
.compatiblyIncludes(T2Quals
))
5183 // If at least one of the types is a class type, the types are not
5184 // related, and we aren't allowed any user conversions, the
5185 // reference binding fails. This case is important for breaking
5186 // recursion, since TryImplicitConversion below will attempt to
5187 // create a temporary through the use of a copy constructor.
5188 if (SuppressUserConversions
&& RefRelationship
== Sema::Ref_Incompatible
&&
5189 (T1
->isRecordType() || T2
->isRecordType()))
5192 // If T1 is reference-related to T2 and the reference is an rvalue
5193 // reference, the initializer expression shall not be an lvalue.
5194 if (RefRelationship
>= Sema::Ref_Related
&& isRValRef
&&
5195 Init
->Classify(S
.Context
).isLValue()) {
5196 ICS
.setBad(BadConversionSequence::rvalue_ref_to_lvalue
, Init
, DeclType
);
5200 // C++ [over.ics.ref]p2:
5201 // When a parameter of reference type is not bound directly to
5202 // an argument expression, the conversion sequence is the one
5203 // required to convert the argument expression to the
5204 // underlying type of the reference according to
5205 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5206 // to copy-initializing a temporary of the underlying type with
5207 // the argument expression. Any difference in top-level
5208 // cv-qualification is subsumed by the initialization itself
5209 // and does not constitute a conversion.
5210 ICS
= TryImplicitConversion(S
, Init
, T1
, SuppressUserConversions
,
5211 AllowedExplicit::None
,
5212 /*InOverloadResolution=*/false,
5214 /*AllowObjCWritebackConversion=*/false,
5215 /*AllowObjCConversionOnExplicit=*/false);
5217 // Of course, that's still a reference binding.
5218 if (ICS
.isStandard()) {
5219 ICS
.Standard
.ReferenceBinding
= true;
5220 ICS
.Standard
.IsLvalueReference
= !isRValRef
;
5221 ICS
.Standard
.BindsToFunctionLvalue
= false;
5222 ICS
.Standard
.BindsToRvalue
= true;
5223 ICS
.Standard
.BindsImplicitObjectArgumentWithoutRefQualifier
= false;
5224 ICS
.Standard
.ObjCLifetimeConversionBinding
= false;
5225 } else if (ICS
.isUserDefined()) {
5226 const ReferenceType
*LValRefType
=
5227 ICS
.UserDefined
.ConversionFunction
->getReturnType()
5228 ->getAs
<LValueReferenceType
>();
5230 // C++ [over.ics.ref]p3:
5231 // Except for an implicit object parameter, for which see 13.3.1, a
5232 // standard conversion sequence cannot be formed if it requires [...]
5233 // binding an rvalue reference to an lvalue other than a function
5235 // Note that the function case is not possible here.
5236 if (isRValRef
&& LValRefType
) {
5237 ICS
.setBad(BadConversionSequence::no_conversion
, Init
, DeclType
);
5241 ICS
.UserDefined
.After
.ReferenceBinding
= true;
5242 ICS
.UserDefined
.After
.IsLvalueReference
= !isRValRef
;
5243 ICS
.UserDefined
.After
.BindsToFunctionLvalue
= false;
5244 ICS
.UserDefined
.After
.BindsToRvalue
= !LValRefType
;
5245 ICS
.UserDefined
.After
.BindsImplicitObjectArgumentWithoutRefQualifier
= false;
5246 ICS
.UserDefined
.After
.ObjCLifetimeConversionBinding
= false;
5252 static ImplicitConversionSequence
5253 TryCopyInitialization(Sema
&S
, Expr
*From
, QualType ToType
,
5254 bool SuppressUserConversions
,
5255 bool InOverloadResolution
,
5256 bool AllowObjCWritebackConversion
,
5257 bool AllowExplicit
= false);
5259 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5260 /// initializer list From.
5261 static ImplicitConversionSequence
5262 TryListConversion(Sema
&S
, InitListExpr
*From
, QualType ToType
,
5263 bool SuppressUserConversions
,
5264 bool InOverloadResolution
,
5265 bool AllowObjCWritebackConversion
) {
5266 // C++11 [over.ics.list]p1:
5267 // When an argument is an initializer list, it is not an expression and
5268 // special rules apply for converting it to a parameter type.
5270 ImplicitConversionSequence Result
;
5271 Result
.setBad(BadConversionSequence::no_conversion
, From
, ToType
);
5273 // We need a complete type for what follows. With one C++20 exception,
5274 // incomplete types can never be initialized from init lists.
5275 QualType InitTy
= ToType
;
5276 const ArrayType
*AT
= S
.Context
.getAsArrayType(ToType
);
5277 if (AT
&& S
.getLangOpts().CPlusPlus20
)
5278 if (const auto *IAT
= dyn_cast
<IncompleteArrayType
>(AT
))
5279 // C++20 allows list initialization of an incomplete array type.
5280 InitTy
= IAT
->getElementType();
5281 if (!S
.isCompleteType(From
->getBeginLoc(), InitTy
))
5284 // C++20 [over.ics.list]/2:
5285 // If the initializer list is a designated-initializer-list, a conversion
5286 // is only possible if the parameter has an aggregate type
5288 // FIXME: The exception for reference initialization here is not part of the
5289 // language rules, but follow other compilers in adding it as a tentative DR
5291 bool IsDesignatedInit
= From
->hasDesignatedInit();
5292 if (!ToType
->isAggregateType() && !ToType
->isReferenceType() &&
5297 // If the parameter type is a class X and the initializer list has a single
5298 // element of type cv U, where U is X or a class derived from X, the
5299 // implicit conversion sequence is the one required to convert the element
5300 // to the parameter type.
5302 // Otherwise, if the parameter type is a character array [... ]
5303 // and the initializer list has a single element that is an
5304 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5305 // implicit conversion sequence is the identity conversion.
5306 if (From
->getNumInits() == 1 && !IsDesignatedInit
) {
5307 if (ToType
->isRecordType()) {
5308 QualType InitType
= From
->getInit(0)->getType();
5309 if (S
.Context
.hasSameUnqualifiedType(InitType
, ToType
) ||
5310 S
.IsDerivedFrom(From
->getBeginLoc(), InitType
, ToType
))
5311 return TryCopyInitialization(S
, From
->getInit(0), ToType
,
5312 SuppressUserConversions
,
5313 InOverloadResolution
,
5314 AllowObjCWritebackConversion
);
5317 if (AT
&& S
.IsStringInit(From
->getInit(0), AT
)) {
5318 InitializedEntity Entity
=
5319 InitializedEntity::InitializeParameter(S
.Context
, ToType
,
5320 /*Consumed=*/false);
5321 if (S
.CanPerformCopyInitialization(Entity
, From
)) {
5322 Result
.setStandard();
5323 Result
.Standard
.setAsIdentityConversion();
5324 Result
.Standard
.setFromType(ToType
);
5325 Result
.Standard
.setAllToTypes(ToType
);
5331 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5332 // C++11 [over.ics.list]p2:
5333 // If the parameter type is std::initializer_list<X> or "array of X" and
5334 // all the elements can be implicitly converted to X, the implicit
5335 // conversion sequence is the worst conversion necessary to convert an
5336 // element of the list to X.
5338 // C++14 [over.ics.list]p3:
5339 // Otherwise, if the parameter type is "array of N X", if the initializer
5340 // list has exactly N elements or if it has fewer than N elements and X is
5341 // default-constructible, and if all the elements of the initializer list
5342 // can be implicitly converted to X, the implicit conversion sequence is
5343 // the worst conversion necessary to convert an element of the list to X.
5344 if ((AT
|| S
.isStdInitializerList(ToType
, &InitTy
)) && !IsDesignatedInit
) {
5345 unsigned e
= From
->getNumInits();
5346 ImplicitConversionSequence DfltElt
;
5347 DfltElt
.setBad(BadConversionSequence::no_conversion
, QualType(),
5349 QualType ContTy
= ToType
;
5350 bool IsUnbounded
= false;
5352 InitTy
= AT
->getElementType();
5353 if (ConstantArrayType
const *CT
= dyn_cast
<ConstantArrayType
>(AT
)) {
5354 if (CT
->getSize().ult(e
)) {
5355 // Too many inits, fatally bad
5356 Result
.setBad(BadConversionSequence::too_many_initializers
, From
,
5358 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5361 if (CT
->getSize().ugt(e
)) {
5362 // Need an init from empty {}, is there one?
5363 InitListExpr
EmptyList(S
.Context
, From
->getEndLoc(), std::nullopt
,
5365 EmptyList
.setType(S
.Context
.VoidTy
);
5366 DfltElt
= TryListConversion(
5367 S
, &EmptyList
, InitTy
, SuppressUserConversions
,
5368 InOverloadResolution
, AllowObjCWritebackConversion
);
5369 if (DfltElt
.isBad()) {
5370 // No {} init, fatally bad
5371 Result
.setBad(BadConversionSequence::too_few_initializers
, From
,
5373 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5378 assert(isa
<IncompleteArrayType
>(AT
) && "Expected incomplete array");
5381 // Cannot convert to zero-sized.
5382 Result
.setBad(BadConversionSequence::too_few_initializers
, From
,
5384 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5387 llvm::APInt
Size(S
.Context
.getTypeSize(S
.Context
.getSizeType()), e
);
5388 ContTy
= S
.Context
.getConstantArrayType(InitTy
, Size
, nullptr,
5389 ArraySizeModifier::Normal
, 0);
5393 Result
.setStandard();
5394 Result
.Standard
.setAsIdentityConversion();
5395 Result
.Standard
.setFromType(InitTy
);
5396 Result
.Standard
.setAllToTypes(InitTy
);
5397 for (unsigned i
= 0; i
< e
; ++i
) {
5398 Expr
*Init
= From
->getInit(i
);
5399 ImplicitConversionSequence ICS
= TryCopyInitialization(
5400 S
, Init
, InitTy
, SuppressUserConversions
, InOverloadResolution
,
5401 AllowObjCWritebackConversion
);
5403 // Keep the worse conversion seen so far.
5404 // FIXME: Sequences are not totally ordered, so 'worse' can be
5405 // ambiguous. CWG has been informed.
5406 if (CompareImplicitConversionSequences(S
, From
->getBeginLoc(), ICS
,
5408 ImplicitConversionSequence::Worse
) {
5410 // Bail as soon as we find something unconvertible.
5411 if (Result
.isBad()) {
5412 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5418 // If we needed any implicit {} initialization, compare that now.
5419 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5420 // has been informed that this might not be the best thing.
5421 if (!DfltElt
.isBad() && CompareImplicitConversionSequences(
5422 S
, From
->getEndLoc(), DfltElt
, Result
) ==
5423 ImplicitConversionSequence::Worse
)
5425 // Record the type being initialized so that we may compare sequences
5426 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5430 // C++14 [over.ics.list]p4:
5431 // C++11 [over.ics.list]p3:
5432 // Otherwise, if the parameter is a non-aggregate class X and overload
5433 // resolution chooses a single best constructor [...] the implicit
5434 // conversion sequence is a user-defined conversion sequence. If multiple
5435 // constructors are viable but none is better than the others, the
5436 // implicit conversion sequence is a user-defined conversion sequence.
5437 if (ToType
->isRecordType() && !ToType
->isAggregateType()) {
5438 // This function can deal with initializer lists.
5439 return TryUserDefinedConversion(S
, From
, ToType
, SuppressUserConversions
,
5440 AllowedExplicit::None
,
5441 InOverloadResolution
, /*CStyle=*/false,
5442 AllowObjCWritebackConversion
,
5443 /*AllowObjCConversionOnExplicit=*/false);
5446 // C++14 [over.ics.list]p5:
5447 // C++11 [over.ics.list]p4:
5448 // Otherwise, if the parameter has an aggregate type which can be
5449 // initialized from the initializer list [...] the implicit conversion
5450 // sequence is a user-defined conversion sequence.
5451 if (ToType
->isAggregateType()) {
5452 // Type is an aggregate, argument is an init list. At this point it comes
5453 // down to checking whether the initialization works.
5454 // FIXME: Find out whether this parameter is consumed or not.
5455 InitializedEntity Entity
=
5456 InitializedEntity::InitializeParameter(S
.Context
, ToType
,
5457 /*Consumed=*/false);
5458 if (S
.CanPerformAggregateInitializationForOverloadResolution(Entity
,
5460 Result
.setUserDefined();
5461 Result
.UserDefined
.Before
.setAsIdentityConversion();
5462 // Initializer lists don't have a type.
5463 Result
.UserDefined
.Before
.setFromType(QualType());
5464 Result
.UserDefined
.Before
.setAllToTypes(QualType());
5466 Result
.UserDefined
.After
.setAsIdentityConversion();
5467 Result
.UserDefined
.After
.setFromType(ToType
);
5468 Result
.UserDefined
.After
.setAllToTypes(ToType
);
5469 Result
.UserDefined
.ConversionFunction
= nullptr;
5474 // C++14 [over.ics.list]p6:
5475 // C++11 [over.ics.list]p5:
5476 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5477 if (ToType
->isReferenceType()) {
5478 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5479 // mention initializer lists in any way. So we go by what list-
5480 // initialization would do and try to extrapolate from that.
5482 QualType T1
= ToType
->castAs
<ReferenceType
>()->getPointeeType();
5484 // If the initializer list has a single element that is reference-related
5485 // to the parameter type, we initialize the reference from that.
5486 if (From
->getNumInits() == 1 && !IsDesignatedInit
) {
5487 Expr
*Init
= From
->getInit(0);
5489 QualType T2
= Init
->getType();
5491 // If the initializer is the address of an overloaded function, try
5492 // to resolve the overloaded function. If all goes well, T2 is the
5493 // type of the resulting function.
5494 if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
) {
5495 DeclAccessPair Found
;
5496 if (FunctionDecl
*Fn
= S
.ResolveAddressOfOverloadedFunction(
5497 Init
, ToType
, false, Found
))
5501 // Compute some basic properties of the types and the initializer.
5502 Sema::ReferenceCompareResult RefRelationship
=
5503 S
.CompareReferenceRelationship(From
->getBeginLoc(), T1
, T2
);
5505 if (RefRelationship
>= Sema::Ref_Related
) {
5506 return TryReferenceInit(S
, Init
, ToType
, /*FIXME*/ From
->getBeginLoc(),
5507 SuppressUserConversions
,
5508 /*AllowExplicit=*/false);
5512 // Otherwise, we bind the reference to a temporary created from the
5513 // initializer list.
5514 Result
= TryListConversion(S
, From
, T1
, SuppressUserConversions
,
5515 InOverloadResolution
,
5516 AllowObjCWritebackConversion
);
5517 if (Result
.isFailure())
5519 assert(!Result
.isEllipsis() &&
5520 "Sub-initialization cannot result in ellipsis conversion.");
5522 // Can we even bind to a temporary?
5523 if (ToType
->isRValueReferenceType() ||
5524 (T1
.isConstQualified() && !T1
.isVolatileQualified())) {
5525 StandardConversionSequence
&SCS
= Result
.isStandard() ? Result
.Standard
:
5526 Result
.UserDefined
.After
;
5527 SCS
.ReferenceBinding
= true;
5528 SCS
.IsLvalueReference
= ToType
->isLValueReferenceType();
5529 SCS
.BindsToRvalue
= true;
5530 SCS
.BindsToFunctionLvalue
= false;
5531 SCS
.BindsImplicitObjectArgumentWithoutRefQualifier
= false;
5532 SCS
.ObjCLifetimeConversionBinding
= false;
5534 Result
.setBad(BadConversionSequence::lvalue_ref_to_rvalue
,
5539 // C++14 [over.ics.list]p7:
5540 // C++11 [over.ics.list]p6:
5541 // Otherwise, if the parameter type is not a class:
5542 if (!ToType
->isRecordType()) {
5543 // - if the initializer list has one element that is not itself an
5544 // initializer list, the implicit conversion sequence is the one
5545 // required to convert the element to the parameter type.
5546 unsigned NumInits
= From
->getNumInits();
5547 if (NumInits
== 1 && !isa
<InitListExpr
>(From
->getInit(0)))
5548 Result
= TryCopyInitialization(S
, From
->getInit(0), ToType
,
5549 SuppressUserConversions
,
5550 InOverloadResolution
,
5551 AllowObjCWritebackConversion
);
5552 // - if the initializer list has no elements, the implicit conversion
5553 // sequence is the identity conversion.
5554 else if (NumInits
== 0) {
5555 Result
.setStandard();
5556 Result
.Standard
.setAsIdentityConversion();
5557 Result
.Standard
.setFromType(ToType
);
5558 Result
.Standard
.setAllToTypes(ToType
);
5563 // C++14 [over.ics.list]p8:
5564 // C++11 [over.ics.list]p7:
5565 // In all cases other than those enumerated above, no conversion is possible
5569 /// TryCopyInitialization - Try to copy-initialize a value of type
5570 /// ToType from the expression From. Return the implicit conversion
5571 /// sequence required to pass this argument, which may be a bad
5572 /// conversion sequence (meaning that the argument cannot be passed to
5573 /// a parameter of this type). If @p SuppressUserConversions, then we
5574 /// do not permit any user-defined conversion sequences.
5575 static ImplicitConversionSequence
5576 TryCopyInitialization(Sema
&S
, Expr
*From
, QualType ToType
,
5577 bool SuppressUserConversions
,
5578 bool InOverloadResolution
,
5579 bool AllowObjCWritebackConversion
,
5580 bool AllowExplicit
) {
5581 if (InitListExpr
*FromInitList
= dyn_cast
<InitListExpr
>(From
))
5582 return TryListConversion(S
, FromInitList
, ToType
, SuppressUserConversions
,
5583 InOverloadResolution
,AllowObjCWritebackConversion
);
5585 if (ToType
->isReferenceType())
5586 return TryReferenceInit(S
, From
, ToType
,
5587 /*FIXME:*/ From
->getBeginLoc(),
5588 SuppressUserConversions
, AllowExplicit
);
5590 return TryImplicitConversion(S
, From
, ToType
,
5591 SuppressUserConversions
,
5592 AllowedExplicit::None
,
5593 InOverloadResolution
,
5595 AllowObjCWritebackConversion
,
5596 /*AllowObjCConversionOnExplicit=*/false);
5599 static bool TryCopyInitialization(const CanQualType FromQTy
,
5600 const CanQualType ToQTy
,
5603 ExprValueKind FromVK
) {
5604 OpaqueValueExpr
TmpExpr(Loc
, FromQTy
, FromVK
);
5605 ImplicitConversionSequence ICS
=
5606 TryCopyInitialization(S
, &TmpExpr
, ToQTy
, true, true, false);
5608 return !ICS
.isBad();
5611 /// TryObjectArgumentInitialization - Try to initialize the object
5612 /// parameter of the given member function (@c Method) from the
5613 /// expression @p From.
5614 static ImplicitConversionSequence
TryObjectArgumentInitialization(
5615 Sema
&S
, SourceLocation Loc
, QualType FromType
,
5616 Expr::Classification FromClassification
, CXXMethodDecl
*Method
,
5617 const CXXRecordDecl
*ActingContext
, bool InOverloadResolution
= false,
5618 QualType ExplicitParameterType
= QualType(),
5619 bool SuppressUserConversion
= false) {
5621 // We need to have an object of class type.
5622 if (const auto *PT
= FromType
->getAs
<PointerType
>()) {
5623 FromType
= PT
->getPointeeType();
5625 // When we had a pointer, it's implicitly dereferenced, so we
5626 // better have an lvalue.
5627 assert(FromClassification
.isLValue());
5630 auto ValueKindFromClassification
= [](Expr::Classification C
) {
5632 return clang::VK_PRValue
;
5635 return clang::VK_LValue
;
5638 if (Method
->isExplicitObjectMemberFunction()) {
5639 if (ExplicitParameterType
.isNull())
5640 ExplicitParameterType
= Method
->getFunctionObjectParameterReferenceType();
5641 OpaqueValueExpr
TmpExpr(Loc
, FromType
.getNonReferenceType(),
5642 ValueKindFromClassification(FromClassification
));
5643 ImplicitConversionSequence ICS
= TryCopyInitialization(
5644 S
, &TmpExpr
, ExplicitParameterType
, SuppressUserConversion
,
5645 /*InOverloadResolution=*/true, false);
5647 ICS
.Bad
.FromExpr
= nullptr;
5651 assert(FromType
->isRecordType());
5653 QualType ClassType
= S
.Context
.getTypeDeclType(ActingContext
);
5654 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5655 // const volatile object.
5656 Qualifiers Quals
= Method
->getMethodQualifiers();
5657 if (isa
<CXXDestructorDecl
>(Method
)) {
5659 Quals
.addVolatile();
5662 QualType ImplicitParamType
= S
.Context
.getQualifiedType(ClassType
, Quals
);
5664 // Set up the conversion sequence as a "bad" conversion, to allow us
5666 ImplicitConversionSequence ICS
;
5668 // C++0x [over.match.funcs]p4:
5669 // For non-static member functions, the type of the implicit object
5672 // - "lvalue reference to cv X" for functions declared without a
5673 // ref-qualifier or with the & ref-qualifier
5674 // - "rvalue reference to cv X" for functions declared with the &&
5677 // where X is the class of which the function is a member and cv is the
5678 // cv-qualification on the member function declaration.
5680 // However, when finding an implicit conversion sequence for the argument, we
5681 // are not allowed to perform user-defined conversions
5682 // (C++ [over.match.funcs]p5). We perform a simplified version of
5683 // reference binding here, that allows class rvalues to bind to
5684 // non-constant references.
5686 // First check the qualifiers.
5687 QualType FromTypeCanon
= S
.Context
.getCanonicalType(FromType
);
5688 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5689 if (ImplicitParamType
.getCVRQualifiers() !=
5690 FromTypeCanon
.getLocalCVRQualifiers() &&
5691 !ImplicitParamType
.isAtLeastAsQualifiedAs(
5692 withoutUnaligned(S
.Context
, FromTypeCanon
))) {
5693 ICS
.setBad(BadConversionSequence::bad_qualifiers
,
5694 FromType
, ImplicitParamType
);
5698 if (FromTypeCanon
.hasAddressSpace()) {
5699 Qualifiers QualsImplicitParamType
= ImplicitParamType
.getQualifiers();
5700 Qualifiers QualsFromType
= FromTypeCanon
.getQualifiers();
5701 if (!QualsImplicitParamType
.isAddressSpaceSupersetOf(QualsFromType
)) {
5702 ICS
.setBad(BadConversionSequence::bad_qualifiers
,
5703 FromType
, ImplicitParamType
);
5708 // Check that we have either the same type or a derived type. It
5709 // affects the conversion rank.
5710 QualType ClassTypeCanon
= S
.Context
.getCanonicalType(ClassType
);
5711 ImplicitConversionKind SecondKind
;
5712 if (ClassTypeCanon
== FromTypeCanon
.getLocalUnqualifiedType()) {
5713 SecondKind
= ICK_Identity
;
5714 } else if (S
.IsDerivedFrom(Loc
, FromType
, ClassType
)) {
5715 SecondKind
= ICK_Derived_To_Base
;
5716 } else if (!Method
->isExplicitObjectMemberFunction()) {
5717 ICS
.setBad(BadConversionSequence::unrelated_class
,
5718 FromType
, ImplicitParamType
);
5722 // Check the ref-qualifier.
5723 switch (Method
->getRefQualifier()) {
5725 // Do nothing; we don't care about lvalueness or rvalueness.
5729 if (!FromClassification
.isLValue() && !Quals
.hasOnlyConst()) {
5730 // non-const lvalue reference cannot bind to an rvalue
5731 ICS
.setBad(BadConversionSequence::lvalue_ref_to_rvalue
, FromType
,
5738 if (!FromClassification
.isRValue()) {
5739 // rvalue reference cannot bind to an lvalue
5740 ICS
.setBad(BadConversionSequence::rvalue_ref_to_lvalue
, FromType
,
5747 // Success. Mark this as a reference binding.
5749 ICS
.Standard
.setAsIdentityConversion();
5750 ICS
.Standard
.Second
= SecondKind
;
5751 ICS
.Standard
.setFromType(FromType
);
5752 ICS
.Standard
.setAllToTypes(ImplicitParamType
);
5753 ICS
.Standard
.ReferenceBinding
= true;
5754 ICS
.Standard
.DirectBinding
= true;
5755 ICS
.Standard
.IsLvalueReference
= Method
->getRefQualifier() != RQ_RValue
;
5756 ICS
.Standard
.BindsToFunctionLvalue
= false;
5757 ICS
.Standard
.BindsToRvalue
= FromClassification
.isRValue();
5758 ICS
.Standard
.BindsImplicitObjectArgumentWithoutRefQualifier
5759 = (Method
->getRefQualifier() == RQ_None
);
5763 /// PerformObjectArgumentInitialization - Perform initialization of
5764 /// the implicit object parameter for the given Method with the given
5766 ExprResult
Sema::PerformImplicitObjectArgumentInitialization(
5767 Expr
*From
, NestedNameSpecifier
*Qualifier
, NamedDecl
*FoundDecl
,
5768 CXXMethodDecl
*Method
) {
5769 QualType FromRecordType
, DestType
;
5770 QualType ImplicitParamRecordType
= Method
->getFunctionObjectParameterType();
5772 Expr::Classification FromClassification
;
5773 if (const PointerType
*PT
= From
->getType()->getAs
<PointerType
>()) {
5774 FromRecordType
= PT
->getPointeeType();
5775 DestType
= Method
->getThisType();
5776 FromClassification
= Expr::Classification::makeSimpleLValue();
5778 FromRecordType
= From
->getType();
5779 DestType
= ImplicitParamRecordType
;
5780 FromClassification
= From
->Classify(Context
);
5782 // When performing member access on a prvalue, materialize a temporary.
5783 if (From
->isPRValue()) {
5784 From
= CreateMaterializeTemporaryExpr(FromRecordType
, From
,
5785 Method
->getRefQualifier() !=
5786 RefQualifierKind::RQ_RValue
);
5790 // Note that we always use the true parent context when performing
5791 // the actual argument initialization.
5792 ImplicitConversionSequence ICS
= TryObjectArgumentInitialization(
5793 *this, From
->getBeginLoc(), From
->getType(), FromClassification
, Method
,
5794 Method
->getParent());
5796 switch (ICS
.Bad
.Kind
) {
5797 case BadConversionSequence::bad_qualifiers
: {
5798 Qualifiers FromQs
= FromRecordType
.getQualifiers();
5799 Qualifiers ToQs
= DestType
.getQualifiers();
5800 unsigned CVR
= FromQs
.getCVRQualifiers() & ~ToQs
.getCVRQualifiers();
5802 Diag(From
->getBeginLoc(), diag::err_member_function_call_bad_cvr
)
5803 << Method
->getDeclName() << FromRecordType
<< (CVR
- 1)
5804 << From
->getSourceRange();
5805 Diag(Method
->getLocation(), diag::note_previous_decl
)
5806 << Method
->getDeclName();
5812 case BadConversionSequence::lvalue_ref_to_rvalue
:
5813 case BadConversionSequence::rvalue_ref_to_lvalue
: {
5814 bool IsRValueQualified
=
5815 Method
->getRefQualifier() == RefQualifierKind::RQ_RValue
;
5816 Diag(From
->getBeginLoc(), diag::err_member_function_call_bad_ref
)
5817 << Method
->getDeclName() << FromClassification
.isRValue()
5818 << IsRValueQualified
;
5819 Diag(Method
->getLocation(), diag::note_previous_decl
)
5820 << Method
->getDeclName();
5824 case BadConversionSequence::no_conversion
:
5825 case BadConversionSequence::unrelated_class
:
5828 case BadConversionSequence::too_few_initializers
:
5829 case BadConversionSequence::too_many_initializers
:
5830 llvm_unreachable("Lists are not objects");
5833 return Diag(From
->getBeginLoc(), diag::err_member_function_call_bad_type
)
5834 << ImplicitParamRecordType
<< FromRecordType
5835 << From
->getSourceRange();
5838 if (ICS
.Standard
.Second
== ICK_Derived_To_Base
) {
5839 ExprResult FromRes
=
5840 PerformObjectMemberConversion(From
, Qualifier
, FoundDecl
, Method
);
5841 if (FromRes
.isInvalid())
5843 From
= FromRes
.get();
5846 if (!Context
.hasSameType(From
->getType(), DestType
)) {
5848 QualType PteeTy
= DestType
->getPointeeType();
5850 PteeTy
.isNull() ? DestType
.getAddressSpace() : PteeTy
.getAddressSpace();
5851 if (FromRecordType
.getAddressSpace() != DestAS
)
5852 CK
= CK_AddressSpaceConversion
;
5855 From
= ImpCastExprToType(From
, DestType
, CK
, From
->getValueKind()).get();
5860 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5861 /// expression From to bool (C++0x [conv]p3).
5862 static ImplicitConversionSequence
5863 TryContextuallyConvertToBool(Sema
&S
, Expr
*From
) {
5864 // C++ [dcl.init]/17.8:
5865 // - Otherwise, if the initialization is direct-initialization, the source
5866 // type is std::nullptr_t, and the destination type is bool, the initial
5867 // value of the object being initialized is false.
5868 if (From
->getType()->isNullPtrType())
5869 return ImplicitConversionSequence::getNullptrToBool(From
->getType(),
5873 // All other direct-initialization of bool is equivalent to an implicit
5874 // conversion to bool in which explicit conversions are permitted.
5875 return TryImplicitConversion(S
, From
, S
.Context
.BoolTy
,
5876 /*SuppressUserConversions=*/false,
5877 AllowedExplicit::Conversions
,
5878 /*InOverloadResolution=*/false,
5880 /*AllowObjCWritebackConversion=*/false,
5881 /*AllowObjCConversionOnExplicit=*/false);
5884 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5885 /// of the expression From to bool (C++0x [conv]p3).
5886 ExprResult
Sema::PerformContextuallyConvertToBool(Expr
*From
) {
5887 if (checkPlaceholderForOverload(*this, From
))
5890 ImplicitConversionSequence ICS
= TryContextuallyConvertToBool(*this, From
);
5892 return PerformImplicitConversion(From
, Context
.BoolTy
, ICS
, AA_Converting
);
5894 if (!DiagnoseMultipleUserDefinedConversion(From
, Context
.BoolTy
))
5895 return Diag(From
->getBeginLoc(), diag::err_typecheck_bool_condition
)
5896 << From
->getType() << From
->getSourceRange();
5900 /// Check that the specified conversion is permitted in a converted constant
5901 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5903 static bool CheckConvertedConstantConversions(Sema
&S
,
5904 StandardConversionSequence
&SCS
) {
5905 // Since we know that the target type is an integral or unscoped enumeration
5906 // type, most conversion kinds are impossible. All possible First and Third
5907 // conversions are fine.
5908 switch (SCS
.Second
) {
5910 case ICK_Integral_Promotion
:
5911 case ICK_Integral_Conversion
: // Narrowing conversions are checked elsewhere.
5912 case ICK_Zero_Queue_Conversion
:
5915 case ICK_Boolean_Conversion
:
5916 // Conversion from an integral or unscoped enumeration type to bool is
5917 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5918 // conversion, so we allow it in a converted constant expression.
5920 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5921 // a lot of popular code. We should at least add a warning for this
5922 // (non-conforming) extension.
5923 return SCS
.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5924 SCS
.getToType(2)->isBooleanType();
5926 case ICK_Pointer_Conversion
:
5927 case ICK_Pointer_Member
:
5928 // C++1z: null pointer conversions and null member pointer conversions are
5929 // only permitted if the source type is std::nullptr_t.
5930 return SCS
.getFromType()->isNullPtrType();
5932 case ICK_Floating_Promotion
:
5933 case ICK_Complex_Promotion
:
5934 case ICK_Floating_Conversion
:
5935 case ICK_Complex_Conversion
:
5936 case ICK_Floating_Integral
:
5937 case ICK_Compatible_Conversion
:
5938 case ICK_Derived_To_Base
:
5939 case ICK_Vector_Conversion
:
5940 case ICK_SVE_Vector_Conversion
:
5941 case ICK_RVV_Vector_Conversion
:
5942 case ICK_Vector_Splat
:
5943 case ICK_Complex_Real
:
5944 case ICK_Block_Pointer_Conversion
:
5945 case ICK_TransparentUnionConversion
:
5946 case ICK_Writeback_Conversion
:
5947 case ICK_Zero_Event_Conversion
:
5948 case ICK_C_Only_Conversion
:
5949 case ICK_Incompatible_Pointer_Conversion
:
5952 case ICK_Lvalue_To_Rvalue
:
5953 case ICK_Array_To_Pointer
:
5954 case ICK_Function_To_Pointer
:
5955 llvm_unreachable("found a first conversion kind in Second");
5957 case ICK_Function_Conversion
:
5958 case ICK_Qualification
:
5959 llvm_unreachable("found a third conversion kind in Second");
5961 case ICK_Num_Conversion_Kinds
:
5965 llvm_unreachable("unknown conversion kind");
5968 /// BuildConvertedConstantExpression - Check that the expression From is a
5969 /// converted constant expression of type T, perform the conversion but
5970 /// does not evaluate the expression
5971 static ExprResult
BuildConvertedConstantExpression(Sema
&S
, Expr
*From
,
5975 APValue
&PreNarrowingValue
) {
5976 assert(S
.getLangOpts().CPlusPlus11
&&
5977 "converted constant expression outside C++11");
5979 if (checkPlaceholderForOverload(S
, From
))
5982 // C++1z [expr.const]p3:
5983 // A converted constant expression of type T is an expression,
5984 // implicitly converted to type T, where the converted
5985 // expression is a constant expression and the implicit conversion
5986 // sequence contains only [... list of conversions ...].
5987 ImplicitConversionSequence ICS
=
5988 (CCE
== Sema::CCEK_ExplicitBool
|| CCE
== Sema::CCEK_Noexcept
)
5989 ? TryContextuallyConvertToBool(S
, From
)
5990 : TryCopyInitialization(S
, From
, T
,
5991 /*SuppressUserConversions=*/false,
5992 /*InOverloadResolution=*/false,
5993 /*AllowObjCWritebackConversion=*/false,
5994 /*AllowExplicit=*/false);
5995 StandardConversionSequence
*SCS
= nullptr;
5996 switch (ICS
.getKind()) {
5997 case ImplicitConversionSequence::StandardConversion
:
5998 SCS
= &ICS
.Standard
;
6000 case ImplicitConversionSequence::UserDefinedConversion
:
6001 if (T
->isRecordType())
6002 SCS
= &ICS
.UserDefined
.Before
;
6004 SCS
= &ICS
.UserDefined
.After
;
6006 case ImplicitConversionSequence::AmbiguousConversion
:
6007 case ImplicitConversionSequence::BadConversion
:
6008 if (!S
.DiagnoseMultipleUserDefinedConversion(From
, T
))
6009 return S
.Diag(From
->getBeginLoc(),
6010 diag::err_typecheck_converted_constant_expression
)
6011 << From
->getType() << From
->getSourceRange() << T
;
6014 case ImplicitConversionSequence::EllipsisConversion
:
6015 case ImplicitConversionSequence::StaticObjectArgumentConversion
:
6016 llvm_unreachable("bad conversion in converted constant expression");
6019 // Check that we would only use permitted conversions.
6020 if (!CheckConvertedConstantConversions(S
, *SCS
)) {
6021 return S
.Diag(From
->getBeginLoc(),
6022 diag::err_typecheck_converted_constant_expression_disallowed
)
6023 << From
->getType() << From
->getSourceRange() << T
;
6025 // [...] and where the reference binding (if any) binds directly.
6026 if (SCS
->ReferenceBinding
&& !SCS
->DirectBinding
) {
6027 return S
.Diag(From
->getBeginLoc(),
6028 diag::err_typecheck_converted_constant_expression_indirect
)
6029 << From
->getType() << From
->getSourceRange() << T
;
6032 // Usually we can simply apply the ImplicitConversionSequence we formed
6033 // earlier, but that's not guaranteed to work when initializing an object of
6036 if (T
->isRecordType()) {
6037 assert(CCE
== Sema::CCEK_TemplateArg
&&
6038 "unexpected class type converted constant expr");
6039 Result
= S
.PerformCopyInitialization(
6040 InitializedEntity::InitializeTemplateParameter(
6041 T
, cast
<NonTypeTemplateParmDecl
>(Dest
)),
6042 SourceLocation(), From
);
6044 Result
= S
.PerformImplicitConversion(From
, T
, ICS
, Sema::AA_Converting
);
6046 if (Result
.isInvalid())
6049 // C++2a [intro.execution]p5:
6050 // A full-expression is [...] a constant-expression [...]
6051 Result
= S
.ActOnFinishFullExpr(Result
.get(), From
->getExprLoc(),
6052 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6053 CCE
== Sema::CCEKind::CCEK_TemplateArg
);
6054 if (Result
.isInvalid())
6057 // Check for a narrowing implicit conversion.
6058 bool ReturnPreNarrowingValue
= false;
6059 QualType PreNarrowingType
;
6060 switch (SCS
->getNarrowingKind(S
.Context
, Result
.get(), PreNarrowingValue
,
6061 PreNarrowingType
)) {
6062 case NK_Dependent_Narrowing
:
6063 // Implicit conversion to a narrower type, but the expression is
6064 // value-dependent so we can't tell whether it's actually narrowing.
6065 case NK_Variable_Narrowing
:
6066 // Implicit conversion to a narrower type, and the value is not a constant
6067 // expression. We'll diagnose this in a moment.
6068 case NK_Not_Narrowing
:
6071 case NK_Constant_Narrowing
:
6072 if (CCE
== Sema::CCEK_ArrayBound
&&
6073 PreNarrowingType
->isIntegralOrEnumerationType() &&
6074 PreNarrowingValue
.isInt()) {
6075 // Don't diagnose array bound narrowing here; we produce more precise
6076 // errors by allowing the un-narrowed value through.
6077 ReturnPreNarrowingValue
= true;
6080 S
.Diag(From
->getBeginLoc(), diag::ext_cce_narrowing
)
6081 << CCE
<< /*Constant*/ 1
6082 << PreNarrowingValue
.getAsString(S
.Context
, PreNarrowingType
) << T
;
6085 case NK_Type_Narrowing
:
6086 // FIXME: It would be better to diagnose that the expression is not a
6087 // constant expression.
6088 S
.Diag(From
->getBeginLoc(), diag::ext_cce_narrowing
)
6089 << CCE
<< /*Constant*/ 0 << From
->getType() << T
;
6092 if (!ReturnPreNarrowingValue
)
6093 PreNarrowingValue
= {};
6098 /// EvaluateConvertedConstantExpression - Evaluate an Expression
6099 /// That is a converted constant expression
6100 /// (which was built with BuildConvertedConstantExpression)
6101 static ExprResult
EvaluateConvertedConstantExpression(
6102 Sema
&S
, Expr
*E
, QualType T
, APValue
&Value
, Sema::CCEKind CCE
,
6103 bool RequireInt
, const APValue
&PreNarrowingValue
) {
6104 ExprResult Result
= E
;
6105 // Check the expression is a constant expression.
6106 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
6107 Expr::EvalResult Eval
;
6110 ConstantExprKind Kind
;
6111 if (CCE
== Sema::CCEK_TemplateArg
&& T
->isRecordType())
6112 Kind
= ConstantExprKind::ClassTemplateArgument
;
6113 else if (CCE
== Sema::CCEK_TemplateArg
)
6114 Kind
= ConstantExprKind::NonClassTemplateArgument
;
6116 Kind
= ConstantExprKind::Normal
;
6118 if (!E
->EvaluateAsConstantExpr(Eval
, S
.Context
, Kind
) ||
6119 (RequireInt
&& !Eval
.Val
.isInt())) {
6120 // The expression can't be folded, so we can't keep it at this position in
6122 Result
= ExprError();
6126 if (Notes
.empty()) {
6127 // It's a constant expression.
6128 Expr
*E
= ConstantExpr::Create(S
.Context
, Result
.get(), Value
);
6129 if (!PreNarrowingValue
.isAbsent())
6130 Value
= std::move(PreNarrowingValue
);
6135 // It's not a constant expression. Produce an appropriate diagnostic.
6136 if (Notes
.size() == 1 &&
6137 Notes
[0].second
.getDiagID() == diag::note_invalid_subexpr_in_const_expr
) {
6138 S
.Diag(Notes
[0].first
, diag::err_expr_not_cce
) << CCE
;
6139 } else if (!Notes
.empty() && Notes
[0].second
.getDiagID() ==
6140 diag::note_constexpr_invalid_template_arg
) {
6141 Notes
[0].second
.setDiagID(diag::err_constexpr_invalid_template_arg
);
6142 for (unsigned I
= 0; I
< Notes
.size(); ++I
)
6143 S
.Diag(Notes
[I
].first
, Notes
[I
].second
);
6145 S
.Diag(E
->getBeginLoc(), diag::err_expr_not_cce
)
6146 << CCE
<< E
->getSourceRange();
6147 for (unsigned I
= 0; I
< Notes
.size(); ++I
)
6148 S
.Diag(Notes
[I
].first
, Notes
[I
].second
);
6153 /// CheckConvertedConstantExpression - Check that the expression From is a
6154 /// converted constant expression of type T, perform the conversion and produce
6155 /// the converted expression, per C++11 [expr.const]p3.
6156 static ExprResult
CheckConvertedConstantExpression(Sema
&S
, Expr
*From
,
6157 QualType T
, APValue
&Value
,
6162 APValue PreNarrowingValue
;
6163 ExprResult Result
= BuildConvertedConstantExpression(S
, From
, T
, CCE
, Dest
,
6165 if (Result
.isInvalid() || Result
.get()->isValueDependent()) {
6169 return EvaluateConvertedConstantExpression(S
, Result
.get(), T
, Value
, CCE
,
6170 RequireInt
, PreNarrowingValue
);
6173 ExprResult
Sema::BuildConvertedConstantExpression(Expr
*From
, QualType T
,
6176 APValue PreNarrowingValue
;
6177 return ::BuildConvertedConstantExpression(*this, From
, T
, CCE
, Dest
,
6181 ExprResult
Sema::CheckConvertedConstantExpression(Expr
*From
, QualType T
,
6182 APValue
&Value
, CCEKind CCE
,
6184 return ::CheckConvertedConstantExpression(*this, From
, T
, Value
, CCE
, false,
6188 ExprResult
Sema::CheckConvertedConstantExpression(Expr
*From
, QualType T
,
6189 llvm::APSInt
&Value
,
6191 assert(T
->isIntegralOrEnumerationType() && "unexpected converted const type");
6194 auto R
= ::CheckConvertedConstantExpression(*this, From
, T
, V
, CCE
, true,
6196 if (!R
.isInvalid() && !R
.get()->isValueDependent())
6202 /// dropPointerConversions - If the given standard conversion sequence
6203 /// involves any pointer conversions, remove them. This may change
6204 /// the result type of the conversion sequence.
6205 static void dropPointerConversion(StandardConversionSequence
&SCS
) {
6206 if (SCS
.Second
== ICK_Pointer_Conversion
) {
6207 SCS
.Second
= ICK_Identity
;
6208 SCS
.Third
= ICK_Identity
;
6209 SCS
.ToTypePtrs
[2] = SCS
.ToTypePtrs
[1] = SCS
.ToTypePtrs
[0];
6213 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6214 /// convert the expression From to an Objective-C pointer type.
6215 static ImplicitConversionSequence
6216 TryContextuallyConvertToObjCPointer(Sema
&S
, Expr
*From
) {
6217 // Do an implicit conversion to 'id'.
6218 QualType Ty
= S
.Context
.getObjCIdType();
6219 ImplicitConversionSequence ICS
6220 = TryImplicitConversion(S
, From
, Ty
,
6221 // FIXME: Are these flags correct?
6222 /*SuppressUserConversions=*/false,
6223 AllowedExplicit::Conversions
,
6224 /*InOverloadResolution=*/false,
6226 /*AllowObjCWritebackConversion=*/false,
6227 /*AllowObjCConversionOnExplicit=*/true);
6229 // Strip off any final conversions to 'id'.
6230 switch (ICS
.getKind()) {
6231 case ImplicitConversionSequence::BadConversion
:
6232 case ImplicitConversionSequence::AmbiguousConversion
:
6233 case ImplicitConversionSequence::EllipsisConversion
:
6234 case ImplicitConversionSequence::StaticObjectArgumentConversion
:
6237 case ImplicitConversionSequence::UserDefinedConversion
:
6238 dropPointerConversion(ICS
.UserDefined
.After
);
6241 case ImplicitConversionSequence::StandardConversion
:
6242 dropPointerConversion(ICS
.Standard
);
6249 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
6250 /// conversion of the expression From to an Objective-C pointer type.
6251 /// Returns a valid but null ExprResult if no conversion sequence exists.
6252 ExprResult
Sema::PerformContextuallyConvertToObjCPointer(Expr
*From
) {
6253 if (checkPlaceholderForOverload(*this, From
))
6256 QualType Ty
= Context
.getObjCIdType();
6257 ImplicitConversionSequence ICS
=
6258 TryContextuallyConvertToObjCPointer(*this, From
);
6260 return PerformImplicitConversion(From
, Ty
, ICS
, AA_Converting
);
6261 return ExprResult();
6264 static QualType
GetExplicitObjectType(Sema
&S
, const Expr
*MemExprE
) {
6265 const Expr
*Base
= nullptr;
6266 assert((isa
<UnresolvedMemberExpr
, MemberExpr
>(MemExprE
)) &&
6267 "expected a member expression");
6269 if (const auto M
= dyn_cast
<UnresolvedMemberExpr
>(MemExprE
);
6270 M
&& !M
->isImplicitAccess())
6271 Base
= M
->getBase();
6272 else if (const auto M
= dyn_cast
<MemberExpr
>(MemExprE
);
6273 M
&& !M
->isImplicitAccess())
6274 Base
= M
->getBase();
6276 QualType T
= Base
? Base
->getType() : S
.getCurrentThisType();
6278 if (T
->isPointerType())
6279 T
= T
->getPointeeType();
6284 static Expr
*GetExplicitObjectExpr(Sema
&S
, Expr
*Obj
,
6285 const FunctionDecl
*Fun
) {
6286 QualType ObjType
= Obj
->getType();
6287 if (ObjType
->isPointerType()) {
6288 ObjType
= ObjType
->getPointeeType();
6289 Obj
= UnaryOperator::Create(S
.getASTContext(), Obj
, UO_Deref
, ObjType
,
6290 VK_LValue
, OK_Ordinary
, SourceLocation(),
6291 /*CanOverflow=*/false, FPOptionsOverride());
6293 if (Obj
->Classify(S
.getASTContext()).isPRValue()) {
6294 Obj
= S
.CreateMaterializeTemporaryExpr(
6296 !Fun
->getParamDecl(0)->getType()->isRValueReferenceType());
6301 ExprResult
Sema::InitializeExplicitObjectArgument(Sema
&S
, Expr
*Obj
,
6302 FunctionDecl
*Fun
) {
6303 Obj
= GetExplicitObjectExpr(S
, Obj
, Fun
);
6304 return S
.PerformCopyInitialization(
6305 InitializedEntity::InitializeParameter(S
.Context
, Fun
->getParamDecl(0)),
6306 Obj
->getExprLoc(), Obj
);
6309 static void PrepareExplicitObjectArgument(Sema
&S
, CXXMethodDecl
*Method
,
6310 Expr
*Object
, MultiExprArg
&Args
,
6311 SmallVectorImpl
<Expr
*> &NewArgs
) {
6312 assert(Method
->isExplicitObjectMemberFunction() &&
6313 "Method is not an explicit member function");
6314 assert(NewArgs
.empty() && "NewArgs should be empty");
6315 NewArgs
.reserve(Args
.size() + 1);
6316 Expr
*This
= GetExplicitObjectExpr(S
, Object
, Method
);
6317 NewArgs
.push_back(This
);
6318 NewArgs
.append(Args
.begin(), Args
.end());
6322 /// Determine whether the provided type is an integral type, or an enumeration
6323 /// type of a permitted flavor.
6324 bool Sema::ICEConvertDiagnoser::match(QualType T
) {
6325 return AllowScopedEnumerations
? T
->isIntegralOrEnumerationType()
6326 : T
->isIntegralOrUnscopedEnumerationType();
6330 diagnoseAmbiguousConversion(Sema
&SemaRef
, SourceLocation Loc
, Expr
*From
,
6331 Sema::ContextualImplicitConverter
&Converter
,
6332 QualType T
, UnresolvedSetImpl
&ViableConversions
) {
6334 if (Converter
.Suppress
)
6337 Converter
.diagnoseAmbiguous(SemaRef
, Loc
, T
) << From
->getSourceRange();
6338 for (unsigned I
= 0, N
= ViableConversions
.size(); I
!= N
; ++I
) {
6339 CXXConversionDecl
*Conv
=
6340 cast
<CXXConversionDecl
>(ViableConversions
[I
]->getUnderlyingDecl());
6341 QualType ConvTy
= Conv
->getConversionType().getNonReferenceType();
6342 Converter
.noteAmbiguous(SemaRef
, Conv
, ConvTy
);
6348 diagnoseNoViableConversion(Sema
&SemaRef
, SourceLocation Loc
, Expr
*&From
,
6349 Sema::ContextualImplicitConverter
&Converter
,
6350 QualType T
, bool HadMultipleCandidates
,
6351 UnresolvedSetImpl
&ExplicitConversions
) {
6352 if (ExplicitConversions
.size() == 1 && !Converter
.Suppress
) {
6353 DeclAccessPair Found
= ExplicitConversions
[0];
6354 CXXConversionDecl
*Conversion
=
6355 cast
<CXXConversionDecl
>(Found
->getUnderlyingDecl());
6357 // The user probably meant to invoke the given explicit
6358 // conversion; use it.
6359 QualType ConvTy
= Conversion
->getConversionType().getNonReferenceType();
6360 std::string TypeStr
;
6361 ConvTy
.getAsStringInternal(TypeStr
, SemaRef
.getPrintingPolicy());
6363 Converter
.diagnoseExplicitConv(SemaRef
, Loc
, T
, ConvTy
)
6364 << FixItHint::CreateInsertion(From
->getBeginLoc(),
6365 "static_cast<" + TypeStr
+ ">(")
6366 << FixItHint::CreateInsertion(
6367 SemaRef
.getLocForEndOfToken(From
->getEndLoc()), ")");
6368 Converter
.noteExplicitConv(SemaRef
, Conversion
, ConvTy
);
6370 // If we aren't in a SFINAE context, build a call to the
6371 // explicit conversion function.
6372 if (SemaRef
.isSFINAEContext())
6375 SemaRef
.CheckMemberOperatorAccess(From
->getExprLoc(), From
, nullptr, Found
);
6376 ExprResult Result
= SemaRef
.BuildCXXMemberCallExpr(From
, Found
, Conversion
,
6377 HadMultipleCandidates
);
6378 if (Result
.isInvalid())
6380 // Record usage of conversion in an implicit cast.
6381 From
= ImplicitCastExpr::Create(SemaRef
.Context
, Result
.get()->getType(),
6382 CK_UserDefinedConversion
, Result
.get(),
6383 nullptr, Result
.get()->getValueKind(),
6384 SemaRef
.CurFPFeatureOverrides());
6389 static bool recordConversion(Sema
&SemaRef
, SourceLocation Loc
, Expr
*&From
,
6390 Sema::ContextualImplicitConverter
&Converter
,
6391 QualType T
, bool HadMultipleCandidates
,
6392 DeclAccessPair
&Found
) {
6393 CXXConversionDecl
*Conversion
=
6394 cast
<CXXConversionDecl
>(Found
->getUnderlyingDecl());
6395 SemaRef
.CheckMemberOperatorAccess(From
->getExprLoc(), From
, nullptr, Found
);
6397 QualType ToType
= Conversion
->getConversionType().getNonReferenceType();
6398 if (!Converter
.SuppressConversion
) {
6399 if (SemaRef
.isSFINAEContext())
6402 Converter
.diagnoseConversion(SemaRef
, Loc
, T
, ToType
)
6403 << From
->getSourceRange();
6406 ExprResult Result
= SemaRef
.BuildCXXMemberCallExpr(From
, Found
, Conversion
,
6407 HadMultipleCandidates
);
6408 if (Result
.isInvalid())
6410 // Record usage of conversion in an implicit cast.
6411 From
= ImplicitCastExpr::Create(SemaRef
.Context
, Result
.get()->getType(),
6412 CK_UserDefinedConversion
, Result
.get(),
6413 nullptr, Result
.get()->getValueKind(),
6414 SemaRef
.CurFPFeatureOverrides());
6418 static ExprResult
finishContextualImplicitConversion(
6419 Sema
&SemaRef
, SourceLocation Loc
, Expr
*From
,
6420 Sema::ContextualImplicitConverter
&Converter
) {
6421 if (!Converter
.match(From
->getType()) && !Converter
.Suppress
)
6422 Converter
.diagnoseNoMatch(SemaRef
, Loc
, From
->getType())
6423 << From
->getSourceRange();
6425 return SemaRef
.DefaultLvalueConversion(From
);
6429 collectViableConversionCandidates(Sema
&SemaRef
, Expr
*From
, QualType ToType
,
6430 UnresolvedSetImpl
&ViableConversions
,
6431 OverloadCandidateSet
&CandidateSet
) {
6432 for (unsigned I
= 0, N
= ViableConversions
.size(); I
!= N
; ++I
) {
6433 DeclAccessPair FoundDecl
= ViableConversions
[I
];
6434 NamedDecl
*D
= FoundDecl
.getDecl();
6435 CXXRecordDecl
*ActingContext
= cast
<CXXRecordDecl
>(D
->getDeclContext());
6436 if (isa
<UsingShadowDecl
>(D
))
6437 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
6439 CXXConversionDecl
*Conv
;
6440 FunctionTemplateDecl
*ConvTemplate
;
6441 if ((ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
)))
6442 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
6444 Conv
= cast
<CXXConversionDecl
>(D
);
6447 SemaRef
.AddTemplateConversionCandidate(
6448 ConvTemplate
, FoundDecl
, ActingContext
, From
, ToType
, CandidateSet
,
6449 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6451 SemaRef
.AddConversionCandidate(Conv
, FoundDecl
, ActingContext
, From
,
6452 ToType
, CandidateSet
,
6453 /*AllowObjCConversionOnExplicit=*/false,
6454 /*AllowExplicit*/ true);
6458 /// Attempt to convert the given expression to a type which is accepted
6459 /// by the given converter.
6461 /// This routine will attempt to convert an expression of class type to a
6462 /// type accepted by the specified converter. In C++11 and before, the class
6463 /// must have a single non-explicit conversion function converting to a matching
6464 /// type. In C++1y, there can be multiple such conversion functions, but only
6465 /// one target type.
6467 /// \param Loc The source location of the construct that requires the
6470 /// \param From The expression we're converting from.
6472 /// \param Converter Used to control and diagnose the conversion process.
6474 /// \returns The expression, converted to an integral or enumeration type if
6476 ExprResult
Sema::PerformContextualImplicitConversion(
6477 SourceLocation Loc
, Expr
*From
, ContextualImplicitConverter
&Converter
) {
6478 // We can't perform any more checking for type-dependent expressions.
6479 if (From
->isTypeDependent())
6482 // Process placeholders immediately.
6483 if (From
->hasPlaceholderType()) {
6484 ExprResult result
= CheckPlaceholderExpr(From
);
6485 if (result
.isInvalid())
6487 From
= result
.get();
6490 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6491 ExprResult Converted
= DefaultLvalueConversion(From
);
6492 QualType T
= Converted
.isUsable() ? Converted
.get()->getType() : QualType();
6493 // If the expression already has a matching type, we're golden.
6494 if (Converter
.match(T
))
6497 // FIXME: Check for missing '()' if T is a function type?
6499 // We can only perform contextual implicit conversions on objects of class
6501 const RecordType
*RecordTy
= T
->getAs
<RecordType
>();
6502 if (!RecordTy
|| !getLangOpts().CPlusPlus
) {
6503 if (!Converter
.Suppress
)
6504 Converter
.diagnoseNoMatch(*this, Loc
, T
) << From
->getSourceRange();
6508 // We must have a complete class type.
6509 struct TypeDiagnoserPartialDiag
: TypeDiagnoser
{
6510 ContextualImplicitConverter
&Converter
;
6513 TypeDiagnoserPartialDiag(ContextualImplicitConverter
&Converter
, Expr
*From
)
6514 : Converter(Converter
), From(From
) {}
6516 void diagnose(Sema
&S
, SourceLocation Loc
, QualType T
) override
{
6517 Converter
.diagnoseIncomplete(S
, Loc
, T
) << From
->getSourceRange();
6519 } IncompleteDiagnoser(Converter
, From
);
6521 if (Converter
.Suppress
? !isCompleteType(Loc
, T
)
6522 : RequireCompleteType(Loc
, T
, IncompleteDiagnoser
))
6525 // Look for a conversion to an integral or enumeration type.
6527 ViableConversions
; // These are *potentially* viable in C++1y.
6528 UnresolvedSet
<4> ExplicitConversions
;
6529 const auto &Conversions
=
6530 cast
<CXXRecordDecl
>(RecordTy
->getDecl())->getVisibleConversionFunctions();
6532 bool HadMultipleCandidates
=
6533 (std::distance(Conversions
.begin(), Conversions
.end()) > 1);
6535 // To check that there is only one target type, in C++1y:
6537 bool HasUniqueTargetType
= true;
6539 // Collect explicit or viable (potentially in C++1y) conversions.
6540 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
6541 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
6542 CXXConversionDecl
*Conversion
;
6543 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
6545 if (getLangOpts().CPlusPlus14
)
6546 Conversion
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
6548 continue; // C++11 does not consider conversion operator templates(?).
6550 Conversion
= cast
<CXXConversionDecl
>(D
);
6552 assert((!ConvTemplate
|| getLangOpts().CPlusPlus14
) &&
6553 "Conversion operator templates are considered potentially "
6556 QualType CurToType
= Conversion
->getConversionType().getNonReferenceType();
6557 if (Converter
.match(CurToType
) || ConvTemplate
) {
6559 if (Conversion
->isExplicit()) {
6560 // FIXME: For C++1y, do we need this restriction?
6561 // cf. diagnoseNoViableConversion()
6563 ExplicitConversions
.addDecl(I
.getDecl(), I
.getAccess());
6565 if (!ConvTemplate
&& getLangOpts().CPlusPlus14
) {
6566 if (ToType
.isNull())
6567 ToType
= CurToType
.getUnqualifiedType();
6568 else if (HasUniqueTargetType
&&
6569 (CurToType
.getUnqualifiedType() != ToType
))
6570 HasUniqueTargetType
= false;
6572 ViableConversions
.addDecl(I
.getDecl(), I
.getAccess());
6577 if (getLangOpts().CPlusPlus14
) {
6579 // ... An expression e of class type E appearing in such a context
6580 // is said to be contextually implicitly converted to a specified
6581 // type T and is well-formed if and only if e can be implicitly
6582 // converted to a type T that is determined as follows: E is searched
6583 // for conversion functions whose return type is cv T or reference to
6584 // cv T such that T is allowed by the context. There shall be
6585 // exactly one such T.
6587 // If no unique T is found:
6588 if (ToType
.isNull()) {
6589 if (diagnoseNoViableConversion(*this, Loc
, From
, Converter
, T
,
6590 HadMultipleCandidates
,
6591 ExplicitConversions
))
6593 return finishContextualImplicitConversion(*this, Loc
, From
, Converter
);
6596 // If more than one unique Ts are found:
6597 if (!HasUniqueTargetType
)
6598 return diagnoseAmbiguousConversion(*this, Loc
, From
, Converter
, T
,
6601 // If one unique T is found:
6602 // First, build a candidate set from the previously recorded
6603 // potentially viable conversions.
6604 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6605 collectViableConversionCandidates(*this, From
, ToType
, ViableConversions
,
6608 // Then, perform overload resolution over the candidate set.
6609 OverloadCandidateSet::iterator Best
;
6610 switch (CandidateSet
.BestViableFunction(*this, Loc
, Best
)) {
6612 // Apply this conversion.
6613 DeclAccessPair Found
=
6614 DeclAccessPair::make(Best
->Function
, Best
->FoundDecl
.getAccess());
6615 if (recordConversion(*this, Loc
, From
, Converter
, T
,
6616 HadMultipleCandidates
, Found
))
6621 return diagnoseAmbiguousConversion(*this, Loc
, From
, Converter
, T
,
6623 case OR_No_Viable_Function
:
6624 if (diagnoseNoViableConversion(*this, Loc
, From
, Converter
, T
,
6625 HadMultipleCandidates
,
6626 ExplicitConversions
))
6630 // We'll complain below about a non-integral condition type.
6634 switch (ViableConversions
.size()) {
6636 if (diagnoseNoViableConversion(*this, Loc
, From
, Converter
, T
,
6637 HadMultipleCandidates
,
6638 ExplicitConversions
))
6641 // We'll complain below about a non-integral condition type.
6645 // Apply this conversion.
6646 DeclAccessPair Found
= ViableConversions
[0];
6647 if (recordConversion(*this, Loc
, From
, Converter
, T
,
6648 HadMultipleCandidates
, Found
))
6653 return diagnoseAmbiguousConversion(*this, Loc
, From
, Converter
, T
,
6658 return finishContextualImplicitConversion(*this, Loc
, From
, Converter
);
6661 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6662 /// an acceptable non-member overloaded operator for a call whose
6663 /// arguments have types T1 (and, if non-empty, T2). This routine
6664 /// implements the check in C++ [over.match.oper]p3b2 concerning
6665 /// enumeration types.
6666 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext
&Context
,
6668 ArrayRef
<Expr
*> Args
) {
6669 QualType T1
= Args
[0]->getType();
6670 QualType T2
= Args
.size() > 1 ? Args
[1]->getType() : QualType();
6672 if (T1
->isDependentType() || (!T2
.isNull() && T2
->isDependentType()))
6675 if (T1
->isRecordType() || (!T2
.isNull() && T2
->isRecordType()))
6678 const auto *Proto
= Fn
->getType()->castAs
<FunctionProtoType
>();
6679 if (Proto
->getNumParams() < 1)
6682 if (T1
->isEnumeralType()) {
6683 QualType ArgType
= Proto
->getParamType(0).getNonReferenceType();
6684 if (Context
.hasSameUnqualifiedType(T1
, ArgType
))
6688 if (Proto
->getNumParams() < 2)
6691 if (!T2
.isNull() && T2
->isEnumeralType()) {
6692 QualType ArgType
= Proto
->getParamType(1).getNonReferenceType();
6693 if (Context
.hasSameUnqualifiedType(T2
, ArgType
))
6700 /// AddOverloadCandidate - Adds the given function to the set of
6701 /// candidate functions, using the given function call arguments. If
6702 /// @p SuppressUserConversions, then don't allow user-defined
6703 /// conversions via constructors or conversion operators.
6705 /// \param PartialOverloading true if we are performing "partial" overloading
6706 /// based on an incomplete set of function arguments. This feature is used by
6707 /// code completion.
6708 void Sema::AddOverloadCandidate(
6709 FunctionDecl
*Function
, DeclAccessPair FoundDecl
, ArrayRef
<Expr
*> Args
,
6710 OverloadCandidateSet
&CandidateSet
, bool SuppressUserConversions
,
6711 bool PartialOverloading
, bool AllowExplicit
, bool AllowExplicitConversions
,
6712 ADLCallKind IsADLCandidate
, ConversionSequenceList EarlyConversions
,
6713 OverloadCandidateParamOrder PO
, bool AggregateCandidateDeduction
) {
6714 const FunctionProtoType
*Proto
6715 = dyn_cast
<FunctionProtoType
>(Function
->getType()->getAs
<FunctionType
>());
6716 assert(Proto
&& "Functions without a prototype cannot be overloaded");
6717 assert(!Function
->getDescribedFunctionTemplate() &&
6718 "Use AddTemplateOverloadCandidate for function templates");
6720 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Function
)) {
6721 if (!isa
<CXXConstructorDecl
>(Method
)) {
6722 // If we get here, it's because we're calling a member function
6723 // that is named without a member access expression (e.g.,
6724 // "this->f") that was either written explicitly or created
6725 // implicitly. This can happen with a qualified call to a member
6726 // function, e.g., X::f(). We use an empty type for the implied
6727 // object argument (C++ [over.call.func]p3), and the acting context
6729 AddMethodCandidate(Method
, FoundDecl
, Method
->getParent(), QualType(),
6730 Expr::Classification::makeSimpleLValue(), Args
,
6731 CandidateSet
, SuppressUserConversions
,
6732 PartialOverloading
, EarlyConversions
, PO
);
6735 // We treat a constructor like a non-member function, since its object
6736 // argument doesn't participate in overload resolution.
6739 if (!CandidateSet
.isNewCandidate(Function
, PO
))
6742 // C++11 [class.copy]p11: [DR1402]
6743 // A defaulted move constructor that is defined as deleted is ignored by
6744 // overload resolution.
6745 CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Function
);
6746 if (Constructor
&& Constructor
->isDefaulted() && Constructor
->isDeleted() &&
6747 Constructor
->isMoveConstructor())
6750 // Overload resolution is always an unevaluated context.
6751 EnterExpressionEvaluationContext
Unevaluated(
6752 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
6754 // C++ [over.match.oper]p3:
6755 // if no operand has a class type, only those non-member functions in the
6756 // lookup set that have a first parameter of type T1 or "reference to
6757 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6758 // is a right operand) a second parameter of type T2 or "reference to
6759 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6760 // candidate functions.
6761 if (CandidateSet
.getKind() == OverloadCandidateSet::CSK_Operator
&&
6762 !IsAcceptableNonMemberOperatorCandidate(Context
, Function
, Args
))
6765 // Add this candidate
6766 OverloadCandidate
&Candidate
=
6767 CandidateSet
.addCandidate(Args
.size(), EarlyConversions
);
6768 Candidate
.FoundDecl
= FoundDecl
;
6769 Candidate
.Function
= Function
;
6770 Candidate
.Viable
= true;
6771 Candidate
.RewriteKind
=
6772 CandidateSet
.getRewriteInfo().getRewriteKind(Function
, PO
);
6773 Candidate
.IsSurrogate
= false;
6774 Candidate
.IsADLCandidate
= IsADLCandidate
;
6775 Candidate
.IgnoreObjectArgument
= false;
6776 Candidate
.ExplicitCallArguments
= Args
.size();
6778 // Explicit functions are not actually candidates at all if we're not
6779 // allowing them in this context, but keep them around so we can point
6780 // to them in diagnostics.
6781 if (!AllowExplicit
&& ExplicitSpecifier::getFromDecl(Function
).isExplicit()) {
6782 Candidate
.Viable
= false;
6783 Candidate
.FailureKind
= ovl_fail_explicit
;
6787 // Functions with internal linkage are only viable in the same module unit.
6788 if (getLangOpts().CPlusPlusModules
&& Function
->isInAnotherModuleUnit()) {
6789 /// FIXME: Currently, the semantics of linkage in clang is slightly
6790 /// different from the semantics in C++ spec. In C++ spec, only names
6791 /// have linkage. So that all entities of the same should share one
6792 /// linkage. But in clang, different entities of the same could have
6793 /// different linkage.
6794 NamedDecl
*ND
= Function
;
6795 if (auto *SpecInfo
= Function
->getTemplateSpecializationInfo())
6796 ND
= SpecInfo
->getTemplate();
6798 if (ND
->getFormalLinkage() == Linkage::Internal
) {
6799 Candidate
.Viable
= false;
6800 Candidate
.FailureKind
= ovl_fail_module_mismatched
;
6805 if (Function
->isMultiVersion() &&
6806 ((Function
->hasAttr
<TargetAttr
>() &&
6807 !Function
->getAttr
<TargetAttr
>()->isDefaultVersion()) ||
6808 (Function
->hasAttr
<TargetVersionAttr
>() &&
6809 !Function
->getAttr
<TargetVersionAttr
>()->isDefaultVersion()))) {
6810 Candidate
.Viable
= false;
6811 Candidate
.FailureKind
= ovl_non_default_multiversion_function
;
6816 // C++ [class.copy]p3:
6817 // A member function template is never instantiated to perform the copy
6818 // of a class object to an object of its class type.
6819 QualType ClassType
= Context
.getTypeDeclType(Constructor
->getParent());
6820 if (Args
.size() == 1 && Constructor
->isSpecializationCopyingObject() &&
6821 (Context
.hasSameUnqualifiedType(ClassType
, Args
[0]->getType()) ||
6822 IsDerivedFrom(Args
[0]->getBeginLoc(), Args
[0]->getType(),
6824 Candidate
.Viable
= false;
6825 Candidate
.FailureKind
= ovl_fail_illegal_constructor
;
6829 // C++ [over.match.funcs]p8: (proposed DR resolution)
6830 // A constructor inherited from class type C that has a first parameter
6831 // of type "reference to P" (including such a constructor instantiated
6832 // from a template) is excluded from the set of candidate functions when
6833 // constructing an object of type cv D if the argument list has exactly
6834 // one argument and D is reference-related to P and P is reference-related
6836 auto *Shadow
= dyn_cast
<ConstructorUsingShadowDecl
>(FoundDecl
.getDecl());
6837 if (Shadow
&& Args
.size() == 1 && Constructor
->getNumParams() >= 1 &&
6838 Constructor
->getParamDecl(0)->getType()->isReferenceType()) {
6839 QualType P
= Constructor
->getParamDecl(0)->getType()->getPointeeType();
6840 QualType C
= Context
.getRecordType(Constructor
->getParent());
6841 QualType D
= Context
.getRecordType(Shadow
->getParent());
6842 SourceLocation Loc
= Args
.front()->getExprLoc();
6843 if ((Context
.hasSameUnqualifiedType(P
, C
) || IsDerivedFrom(Loc
, P
, C
)) &&
6844 (Context
.hasSameUnqualifiedType(D
, P
) || IsDerivedFrom(Loc
, D
, P
))) {
6845 Candidate
.Viable
= false;
6846 Candidate
.FailureKind
= ovl_fail_inhctor_slice
;
6851 // Check that the constructor is capable of constructing an object in the
6852 // destination address space.
6853 if (!Qualifiers::isAddressSpaceSupersetOf(
6854 Constructor
->getMethodQualifiers().getAddressSpace(),
6855 CandidateSet
.getDestAS())) {
6856 Candidate
.Viable
= false;
6857 Candidate
.FailureKind
= ovl_fail_object_addrspace_mismatch
;
6861 unsigned NumParams
= Proto
->getNumParams();
6863 // (C++ 13.3.2p2): A candidate function having fewer than m
6864 // parameters is viable only if it has an ellipsis in its parameter
6866 if (TooManyArguments(NumParams
, Args
.size(), PartialOverloading
) &&
6867 !Proto
->isVariadic() &&
6868 shouldEnforceArgLimit(PartialOverloading
, Function
)) {
6869 Candidate
.Viable
= false;
6870 Candidate
.FailureKind
= ovl_fail_too_many_arguments
;
6874 // (C++ 13.3.2p2): A candidate function having more than m parameters
6875 // is viable only if the (m+1)st parameter has a default argument
6876 // (8.3.6). For the purposes of overload resolution, the
6877 // parameter list is truncated on the right, so that there are
6878 // exactly m parameters.
6879 unsigned MinRequiredArgs
= Function
->getMinRequiredArguments();
6880 if (!AggregateCandidateDeduction
&& Args
.size() < MinRequiredArgs
&&
6881 !PartialOverloading
) {
6882 // Not enough arguments.
6883 Candidate
.Viable
= false;
6884 Candidate
.FailureKind
= ovl_fail_too_few_arguments
;
6888 // (CUDA B.1): Check for invalid calls between targets.
6889 if (getLangOpts().CUDA
) {
6890 const FunctionDecl
*Caller
= getCurFunctionDecl(/*AllowLambda=*/true);
6891 // Skip the check for callers that are implicit members, because in this
6892 // case we may not yet know what the member's target is; the target is
6893 // inferred for the member automatically, based on the bases and fields of
6895 if (!(Caller
&& Caller
->isImplicit()) &&
6896 !IsAllowedCUDACall(Caller
, Function
)) {
6897 Candidate
.Viable
= false;
6898 Candidate
.FailureKind
= ovl_fail_bad_target
;
6903 if (Function
->getTrailingRequiresClause()) {
6904 ConstraintSatisfaction Satisfaction
;
6905 if (CheckFunctionConstraints(Function
, Satisfaction
, /*Loc*/ {},
6906 /*ForOverloadResolution*/ true) ||
6907 !Satisfaction
.IsSatisfied
) {
6908 Candidate
.Viable
= false;
6909 Candidate
.FailureKind
= ovl_fail_constraints_not_satisfied
;
6914 // Determine the implicit conversion sequences for each of the
6916 for (unsigned ArgIdx
= 0; ArgIdx
< Args
.size(); ++ArgIdx
) {
6918 PO
== OverloadCandidateParamOrder::Reversed
? 1 - ArgIdx
: ArgIdx
;
6919 if (Candidate
.Conversions
[ConvIdx
].isInitialized()) {
6920 // We already formed a conversion sequence for this parameter during
6921 // template argument deduction.
6922 } else if (ArgIdx
< NumParams
) {
6923 // (C++ 13.3.2p3): for F to be a viable function, there shall
6924 // exist for each argument an implicit conversion sequence
6925 // (13.3.3.1) that converts that argument to the corresponding
6927 QualType ParamType
= Proto
->getParamType(ArgIdx
);
6928 Candidate
.Conversions
[ConvIdx
] = TryCopyInitialization(
6929 *this, Args
[ArgIdx
], ParamType
, SuppressUserConversions
,
6930 /*InOverloadResolution=*/true,
6931 /*AllowObjCWritebackConversion=*/
6932 getLangOpts().ObjCAutoRefCount
, AllowExplicitConversions
);
6933 if (Candidate
.Conversions
[ConvIdx
].isBad()) {
6934 Candidate
.Viable
= false;
6935 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
6939 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6940 // argument for which there is no corresponding parameter is
6941 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6942 Candidate
.Conversions
[ConvIdx
].setEllipsis();
6946 if (EnableIfAttr
*FailedAttr
=
6947 CheckEnableIf(Function
, CandidateSet
.getLocation(), Args
)) {
6948 Candidate
.Viable
= false;
6949 Candidate
.FailureKind
= ovl_fail_enable_if
;
6950 Candidate
.DeductionFailure
.Data
= FailedAttr
;
6956 Sema::SelectBestMethod(Selector Sel
, MultiExprArg Args
, bool IsInstance
,
6957 SmallVectorImpl
<ObjCMethodDecl
*> &Methods
) {
6958 if (Methods
.size() <= 1)
6961 for (unsigned b
= 0, e
= Methods
.size(); b
< e
; b
++) {
6963 ObjCMethodDecl
*Method
= Methods
[b
];
6964 unsigned NumNamedArgs
= Sel
.getNumArgs();
6965 // Method might have more arguments than selector indicates. This is due
6966 // to addition of c-style arguments in method.
6967 if (Method
->param_size() > NumNamedArgs
)
6968 NumNamedArgs
= Method
->param_size();
6969 if (Args
.size() < NumNamedArgs
)
6972 for (unsigned i
= 0; i
< NumNamedArgs
; i
++) {
6973 // We can't do any type-checking on a type-dependent argument.
6974 if (Args
[i
]->isTypeDependent()) {
6979 ParmVarDecl
*param
= Method
->parameters()[i
];
6980 Expr
*argExpr
= Args
[i
];
6981 assert(argExpr
&& "SelectBestMethod(): missing expression");
6983 // Strip the unbridged-cast placeholder expression off unless it's
6984 // a consumed argument.
6985 if (argExpr
->hasPlaceholderType(BuiltinType::ARCUnbridgedCast
) &&
6986 !param
->hasAttr
<CFConsumedAttr
>())
6987 argExpr
= stripARCUnbridgedCast(argExpr
);
6989 // If the parameter is __unknown_anytype, move on to the next method.
6990 if (param
->getType() == Context
.UnknownAnyTy
) {
6995 ImplicitConversionSequence ConversionState
6996 = TryCopyInitialization(*this, argExpr
, param
->getType(),
6997 /*SuppressUserConversions*/false,
6998 /*InOverloadResolution=*/true,
6999 /*AllowObjCWritebackConversion=*/
7000 getLangOpts().ObjCAutoRefCount
,
7001 /*AllowExplicit*/false);
7002 // This function looks for a reasonably-exact match, so we consider
7003 // incompatible pointer conversions to be a failure here.
7004 if (ConversionState
.isBad() ||
7005 (ConversionState
.isStandard() &&
7006 ConversionState
.Standard
.Second
==
7007 ICK_Incompatible_Pointer_Conversion
)) {
7012 // Promote additional arguments to variadic methods.
7013 if (Match
&& Method
->isVariadic()) {
7014 for (unsigned i
= NumNamedArgs
, e
= Args
.size(); i
< e
; ++i
) {
7015 if (Args
[i
]->isTypeDependent()) {
7019 ExprResult Arg
= DefaultVariadicArgumentPromotion(Args
[i
], VariadicMethod
,
7021 if (Arg
.isInvalid()) {
7027 // Check for extra arguments to non-variadic methods.
7028 if (Args
.size() != NumNamedArgs
)
7030 else if (Match
&& NumNamedArgs
== 0 && Methods
.size() > 1) {
7031 // Special case when selectors have no argument. In this case, select
7032 // one with the most general result type of 'id'.
7033 for (unsigned b
= 0, e
= Methods
.size(); b
< e
; b
++) {
7034 QualType ReturnT
= Methods
[b
]->getReturnType();
7035 if (ReturnT
->isObjCIdType())
7047 static bool convertArgsForAvailabilityChecks(
7048 Sema
&S
, FunctionDecl
*Function
, Expr
*ThisArg
, SourceLocation CallLoc
,
7049 ArrayRef
<Expr
*> Args
, Sema::SFINAETrap
&Trap
, bool MissingImplicitThis
,
7050 Expr
*&ConvertedThis
, SmallVectorImpl
<Expr
*> &ConvertedArgs
) {
7052 CXXMethodDecl
*Method
= cast
<CXXMethodDecl
>(Function
);
7053 assert(!isa
<CXXConstructorDecl
>(Method
) &&
7054 "Shouldn't have `this` for ctors!");
7055 assert(!Method
->isStatic() && "Shouldn't have `this` for static methods!");
7056 ExprResult R
= S
.PerformImplicitObjectArgumentInitialization(
7057 ThisArg
, /*Qualifier=*/nullptr, Method
, Method
);
7060 ConvertedThis
= R
.get();
7062 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(Function
)) {
7064 assert((MissingImplicitThis
|| MD
->isStatic() ||
7065 isa
<CXXConstructorDecl
>(MD
)) &&
7066 "Expected `this` for non-ctor instance methods");
7068 ConvertedThis
= nullptr;
7071 // Ignore any variadic arguments. Converting them is pointless, since the
7072 // user can't refer to them in the function condition.
7073 unsigned ArgSizeNoVarargs
= std::min(Function
->param_size(), Args
.size());
7075 // Convert the arguments.
7076 for (unsigned I
= 0; I
!= ArgSizeNoVarargs
; ++I
) {
7078 R
= S
.PerformCopyInitialization(InitializedEntity::InitializeParameter(
7079 S
.Context
, Function
->getParamDecl(I
)),
7080 SourceLocation(), Args
[I
]);
7085 ConvertedArgs
.push_back(R
.get());
7088 if (Trap
.hasErrorOccurred())
7091 // Push default arguments if needed.
7092 if (!Function
->isVariadic() && Args
.size() < Function
->getNumParams()) {
7093 for (unsigned i
= Args
.size(), e
= Function
->getNumParams(); i
!= e
; ++i
) {
7094 ParmVarDecl
*P
= Function
->getParamDecl(i
);
7095 if (!P
->hasDefaultArg())
7097 ExprResult R
= S
.BuildCXXDefaultArgExpr(CallLoc
, Function
, P
);
7100 ConvertedArgs
.push_back(R
.get());
7103 if (Trap
.hasErrorOccurred())
7109 EnableIfAttr
*Sema::CheckEnableIf(FunctionDecl
*Function
,
7110 SourceLocation CallLoc
,
7111 ArrayRef
<Expr
*> Args
,
7112 bool MissingImplicitThis
) {
7113 auto EnableIfAttrs
= Function
->specific_attrs
<EnableIfAttr
>();
7114 if (EnableIfAttrs
.begin() == EnableIfAttrs
.end())
7117 SFINAETrap
Trap(*this);
7118 SmallVector
<Expr
*, 16> ConvertedArgs
;
7119 // FIXME: We should look into making enable_if late-parsed.
7120 Expr
*DiscardedThis
;
7121 if (!convertArgsForAvailabilityChecks(
7122 *this, Function
, /*ThisArg=*/nullptr, CallLoc
, Args
, Trap
,
7123 /*MissingImplicitThis=*/true, DiscardedThis
, ConvertedArgs
))
7124 return *EnableIfAttrs
.begin();
7126 for (auto *EIA
: EnableIfAttrs
) {
7128 // FIXME: This doesn't consider value-dependent cases, because doing so is
7129 // very difficult. Ideally, we should handle them more gracefully.
7130 if (EIA
->getCond()->isValueDependent() ||
7131 !EIA
->getCond()->EvaluateWithSubstitution(
7132 Result
, Context
, Function
, llvm::ArrayRef(ConvertedArgs
)))
7135 if (!Result
.isInt() || !Result
.getInt().getBoolValue())
7141 template <typename CheckFn
>
7142 static bool diagnoseDiagnoseIfAttrsWith(Sema
&S
, const NamedDecl
*ND
,
7143 bool ArgDependent
, SourceLocation Loc
,
7144 CheckFn
&&IsSuccessful
) {
7145 SmallVector
<const DiagnoseIfAttr
*, 8> Attrs
;
7146 for (const auto *DIA
: ND
->specific_attrs
<DiagnoseIfAttr
>()) {
7147 if (ArgDependent
== DIA
->getArgDependent())
7148 Attrs
.push_back(DIA
);
7151 // Common case: No diagnose_if attributes, so we can quit early.
7155 auto WarningBegin
= std::stable_partition(
7156 Attrs
.begin(), Attrs
.end(),
7157 [](const DiagnoseIfAttr
*DIA
) { return DIA
->isError(); });
7159 // Note that diagnose_if attributes are late-parsed, so they appear in the
7160 // correct order (unlike enable_if attributes).
7161 auto ErrAttr
= llvm::find_if(llvm::make_range(Attrs
.begin(), WarningBegin
),
7163 if (ErrAttr
!= WarningBegin
) {
7164 const DiagnoseIfAttr
*DIA
= *ErrAttr
;
7165 S
.Diag(Loc
, diag::err_diagnose_if_succeeded
) << DIA
->getMessage();
7166 S
.Diag(DIA
->getLocation(), diag::note_from_diagnose_if
)
7167 << DIA
->getParent() << DIA
->getCond()->getSourceRange();
7171 for (const auto *DIA
: llvm::make_range(WarningBegin
, Attrs
.end()))
7172 if (IsSuccessful(DIA
)) {
7173 S
.Diag(Loc
, diag::warn_diagnose_if_succeeded
) << DIA
->getMessage();
7174 S
.Diag(DIA
->getLocation(), diag::note_from_diagnose_if
)
7175 << DIA
->getParent() << DIA
->getCond()->getSourceRange();
7181 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl
*Function
,
7182 const Expr
*ThisArg
,
7183 ArrayRef
<const Expr
*> Args
,
7184 SourceLocation Loc
) {
7185 return diagnoseDiagnoseIfAttrsWith(
7186 *this, Function
, /*ArgDependent=*/true, Loc
,
7187 [&](const DiagnoseIfAttr
*DIA
) {
7189 // It's sane to use the same Args for any redecl of this function, since
7190 // EvaluateWithSubstitution only cares about the position of each
7191 // argument in the arg list, not the ParmVarDecl* it maps to.
7192 if (!DIA
->getCond()->EvaluateWithSubstitution(
7193 Result
, Context
, cast
<FunctionDecl
>(DIA
->getParent()), Args
, ThisArg
))
7195 return Result
.isInt() && Result
.getInt().getBoolValue();
7199 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl
*ND
,
7200 SourceLocation Loc
) {
7201 return diagnoseDiagnoseIfAttrsWith(
7202 *this, ND
, /*ArgDependent=*/false, Loc
,
7203 [&](const DiagnoseIfAttr
*DIA
) {
7205 return DIA
->getCond()->EvaluateAsBooleanCondition(Result
, Context
) &&
7210 /// Add all of the function declarations in the given function set to
7211 /// the overload candidate set.
7212 void Sema::AddFunctionCandidates(const UnresolvedSetImpl
&Fns
,
7213 ArrayRef
<Expr
*> Args
,
7214 OverloadCandidateSet
&CandidateSet
,
7215 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
7216 bool SuppressUserConversions
,
7217 bool PartialOverloading
,
7218 bool FirstArgumentIsBase
) {
7219 for (UnresolvedSetIterator F
= Fns
.begin(), E
= Fns
.end(); F
!= E
; ++F
) {
7220 NamedDecl
*D
= F
.getDecl()->getUnderlyingDecl();
7221 ArrayRef
<Expr
*> FunctionArgs
= Args
;
7223 FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
);
7225 FunTmpl
? FunTmpl
->getTemplatedDecl() : cast
<FunctionDecl
>(D
);
7227 if (isa
<CXXMethodDecl
>(FD
) && !cast
<CXXMethodDecl
>(FD
)->isStatic()) {
7228 QualType ObjectType
;
7229 Expr::Classification ObjectClassification
;
7230 if (Args
.size() > 0) {
7231 if (Expr
*E
= Args
[0]) {
7232 // Use the explicit base to restrict the lookup:
7233 ObjectType
= E
->getType();
7234 // Pointers in the object arguments are implicitly dereferenced, so we
7235 // always classify them as l-values.
7236 if (!ObjectType
.isNull() && ObjectType
->isPointerType())
7237 ObjectClassification
= Expr::Classification::makeSimpleLValue();
7239 ObjectClassification
= E
->Classify(Context
);
7240 } // .. else there is an implicit base.
7241 FunctionArgs
= Args
.slice(1);
7244 AddMethodTemplateCandidate(
7245 FunTmpl
, F
.getPair(),
7246 cast
<CXXRecordDecl
>(FunTmpl
->getDeclContext()),
7247 ExplicitTemplateArgs
, ObjectType
, ObjectClassification
,
7248 FunctionArgs
, CandidateSet
, SuppressUserConversions
,
7249 PartialOverloading
);
7251 AddMethodCandidate(cast
<CXXMethodDecl
>(FD
), F
.getPair(),
7252 cast
<CXXMethodDecl
>(FD
)->getParent(), ObjectType
,
7253 ObjectClassification
, FunctionArgs
, CandidateSet
,
7254 SuppressUserConversions
, PartialOverloading
);
7257 // This branch handles both standalone functions and static methods.
7259 // Slice the first argument (which is the base) when we access
7260 // static method as non-static.
7261 if (Args
.size() > 0 &&
7262 (!Args
[0] || (FirstArgumentIsBase
&& isa
<CXXMethodDecl
>(FD
) &&
7263 !isa
<CXXConstructorDecl
>(FD
)))) {
7264 assert(cast
<CXXMethodDecl
>(FD
)->isStatic());
7265 FunctionArgs
= Args
.slice(1);
7268 AddTemplateOverloadCandidate(FunTmpl
, F
.getPair(),
7269 ExplicitTemplateArgs
, FunctionArgs
,
7270 CandidateSet
, SuppressUserConversions
,
7271 PartialOverloading
);
7273 AddOverloadCandidate(FD
, F
.getPair(), FunctionArgs
, CandidateSet
,
7274 SuppressUserConversions
, PartialOverloading
);
7280 /// AddMethodCandidate - Adds a named decl (which is some kind of
7281 /// method) as a method candidate to the given overload set.
7282 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl
, QualType ObjectType
,
7283 Expr::Classification ObjectClassification
,
7284 ArrayRef
<Expr
*> Args
,
7285 OverloadCandidateSet
&CandidateSet
,
7286 bool SuppressUserConversions
,
7287 OverloadCandidateParamOrder PO
) {
7288 NamedDecl
*Decl
= FoundDecl
.getDecl();
7289 CXXRecordDecl
*ActingContext
= cast
<CXXRecordDecl
>(Decl
->getDeclContext());
7291 if (isa
<UsingShadowDecl
>(Decl
))
7292 Decl
= cast
<UsingShadowDecl
>(Decl
)->getTargetDecl();
7294 if (FunctionTemplateDecl
*TD
= dyn_cast
<FunctionTemplateDecl
>(Decl
)) {
7295 assert(isa
<CXXMethodDecl
>(TD
->getTemplatedDecl()) &&
7296 "Expected a member function template");
7297 AddMethodTemplateCandidate(TD
, FoundDecl
, ActingContext
,
7298 /*ExplicitArgs*/ nullptr, ObjectType
,
7299 ObjectClassification
, Args
, CandidateSet
,
7300 SuppressUserConversions
, false, PO
);
7302 AddMethodCandidate(cast
<CXXMethodDecl
>(Decl
), FoundDecl
, ActingContext
,
7303 ObjectType
, ObjectClassification
, Args
, CandidateSet
,
7304 SuppressUserConversions
, false, std::nullopt
, PO
);
7308 /// AddMethodCandidate - Adds the given C++ member function to the set
7309 /// of candidate functions, using the given function call arguments
7310 /// and the object argument (@c Object). For example, in a call
7311 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7312 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7313 /// allow user-defined conversions via constructors or conversion
7316 Sema::AddMethodCandidate(CXXMethodDecl
*Method
, DeclAccessPair FoundDecl
,
7317 CXXRecordDecl
*ActingContext
, QualType ObjectType
,
7318 Expr::Classification ObjectClassification
,
7319 ArrayRef
<Expr
*> Args
,
7320 OverloadCandidateSet
&CandidateSet
,
7321 bool SuppressUserConversions
,
7322 bool PartialOverloading
,
7323 ConversionSequenceList EarlyConversions
,
7324 OverloadCandidateParamOrder PO
) {
7325 const FunctionProtoType
*Proto
7326 = dyn_cast
<FunctionProtoType
>(Method
->getType()->getAs
<FunctionType
>());
7327 assert(Proto
&& "Methods without a prototype cannot be overloaded");
7328 assert(!isa
<CXXConstructorDecl
>(Method
) &&
7329 "Use AddOverloadCandidate for constructors");
7331 if (!CandidateSet
.isNewCandidate(Method
, PO
))
7334 // C++11 [class.copy]p23: [DR1402]
7335 // A defaulted move assignment operator that is defined as deleted is
7336 // ignored by overload resolution.
7337 if (Method
->isDefaulted() && Method
->isDeleted() &&
7338 Method
->isMoveAssignmentOperator())
7341 // Overload resolution is always an unevaluated context.
7342 EnterExpressionEvaluationContext
Unevaluated(
7343 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
7345 // Add this candidate
7346 OverloadCandidate
&Candidate
=
7347 CandidateSet
.addCandidate(Args
.size() + 1, EarlyConversions
);
7348 Candidate
.FoundDecl
= FoundDecl
;
7349 Candidate
.Function
= Method
;
7350 Candidate
.RewriteKind
=
7351 CandidateSet
.getRewriteInfo().getRewriteKind(Method
, PO
);
7352 Candidate
.IsSurrogate
= false;
7353 Candidate
.IgnoreObjectArgument
= false;
7354 Candidate
.ExplicitCallArguments
= Args
.size();
7356 unsigned NumParams
= Method
->getNumExplicitParams();
7357 unsigned ExplicitOffset
= Method
->isExplicitObjectMemberFunction() ? 1 : 0;
7359 // (C++ 13.3.2p2): A candidate function having fewer than m
7360 // parameters is viable only if it has an ellipsis in its parameter
7362 if (TooManyArguments(NumParams
, Args
.size(), PartialOverloading
) &&
7363 !Proto
->isVariadic() &&
7364 shouldEnforceArgLimit(PartialOverloading
, Method
)) {
7365 Candidate
.Viable
= false;
7366 Candidate
.FailureKind
= ovl_fail_too_many_arguments
;
7370 // (C++ 13.3.2p2): A candidate function having more than m parameters
7371 // is viable only if the (m+1)st parameter has a default argument
7372 // (8.3.6). For the purposes of overload resolution, the
7373 // parameter list is truncated on the right, so that there are
7374 // exactly m parameters.
7375 unsigned MinRequiredArgs
= Method
->getMinRequiredExplicitArguments();
7376 if (Args
.size() < MinRequiredArgs
&& !PartialOverloading
) {
7377 // Not enough arguments.
7378 Candidate
.Viable
= false;
7379 Candidate
.FailureKind
= ovl_fail_too_few_arguments
;
7383 Candidate
.Viable
= true;
7385 unsigned FirstConvIdx
= PO
== OverloadCandidateParamOrder::Reversed
? 1 : 0;
7386 if (ObjectType
.isNull())
7387 Candidate
.IgnoreObjectArgument
= true;
7388 else if (Method
->isStatic()) {
7389 // [over.best.ics.general]p8
7390 // When the parameter is the implicit object parameter of a static member
7391 // function, the implicit conversion sequence is a standard conversion
7392 // sequence that is neither better nor worse than any other standard
7393 // conversion sequence.
7395 // This is a rule that was introduced in C++23 to support static lambdas. We
7396 // apply it retroactively because we want to support static lambdas as an
7397 // extension and it doesn't hurt previous code.
7398 Candidate
.Conversions
[FirstConvIdx
].setStaticObjectArgument();
7400 // Determine the implicit conversion sequence for the object
7402 Candidate
.Conversions
[FirstConvIdx
] = TryObjectArgumentInitialization(
7403 *this, CandidateSet
.getLocation(), ObjectType
, ObjectClassification
,
7404 Method
, ActingContext
, /*InOverloadResolution=*/true);
7405 if (Candidate
.Conversions
[FirstConvIdx
].isBad()) {
7406 Candidate
.Viable
= false;
7407 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7412 // (CUDA B.1): Check for invalid calls between targets.
7413 if (getLangOpts().CUDA
)
7414 if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method
)) {
7415 Candidate
.Viable
= false;
7416 Candidate
.FailureKind
= ovl_fail_bad_target
;
7420 if (Method
->getTrailingRequiresClause()) {
7421 ConstraintSatisfaction Satisfaction
;
7422 if (CheckFunctionConstraints(Method
, Satisfaction
, /*Loc*/ {},
7423 /*ForOverloadResolution*/ true) ||
7424 !Satisfaction
.IsSatisfied
) {
7425 Candidate
.Viable
= false;
7426 Candidate
.FailureKind
= ovl_fail_constraints_not_satisfied
;
7431 // Determine the implicit conversion sequences for each of the
7433 for (unsigned ArgIdx
= 0; ArgIdx
< Args
.size(); ++ArgIdx
) {
7435 PO
== OverloadCandidateParamOrder::Reversed
? 0 : (ArgIdx
+ 1);
7436 if (Candidate
.Conversions
[ConvIdx
].isInitialized()) {
7437 // We already formed a conversion sequence for this parameter during
7438 // template argument deduction.
7439 } else if (ArgIdx
< NumParams
) {
7440 // (C++ 13.3.2p3): for F to be a viable function, there shall
7441 // exist for each argument an implicit conversion sequence
7442 // (13.3.3.1) that converts that argument to the corresponding
7444 QualType ParamType
= Proto
->getParamType(ArgIdx
+ ExplicitOffset
);
7445 Candidate
.Conversions
[ConvIdx
]
7446 = TryCopyInitialization(*this, Args
[ArgIdx
], ParamType
,
7447 SuppressUserConversions
,
7448 /*InOverloadResolution=*/true,
7449 /*AllowObjCWritebackConversion=*/
7450 getLangOpts().ObjCAutoRefCount
);
7451 if (Candidate
.Conversions
[ConvIdx
].isBad()) {
7452 Candidate
.Viable
= false;
7453 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7457 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7458 // argument for which there is no corresponding parameter is
7459 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7460 Candidate
.Conversions
[ConvIdx
].setEllipsis();
7464 if (EnableIfAttr
*FailedAttr
=
7465 CheckEnableIf(Method
, CandidateSet
.getLocation(), Args
, true)) {
7466 Candidate
.Viable
= false;
7467 Candidate
.FailureKind
= ovl_fail_enable_if
;
7468 Candidate
.DeductionFailure
.Data
= FailedAttr
;
7472 if (Method
->isMultiVersion() &&
7473 ((Method
->hasAttr
<TargetAttr
>() &&
7474 !Method
->getAttr
<TargetAttr
>()->isDefaultVersion()) ||
7475 (Method
->hasAttr
<TargetVersionAttr
>() &&
7476 !Method
->getAttr
<TargetVersionAttr
>()->isDefaultVersion()))) {
7477 Candidate
.Viable
= false;
7478 Candidate
.FailureKind
= ovl_non_default_multiversion_function
;
7482 /// Add a C++ member function template as a candidate to the candidate
7483 /// set, using template argument deduction to produce an appropriate member
7484 /// function template specialization.
7485 void Sema::AddMethodTemplateCandidate(
7486 FunctionTemplateDecl
*MethodTmpl
, DeclAccessPair FoundDecl
,
7487 CXXRecordDecl
*ActingContext
,
7488 TemplateArgumentListInfo
*ExplicitTemplateArgs
, QualType ObjectType
,
7489 Expr::Classification ObjectClassification
, ArrayRef
<Expr
*> Args
,
7490 OverloadCandidateSet
&CandidateSet
, bool SuppressUserConversions
,
7491 bool PartialOverloading
, OverloadCandidateParamOrder PO
) {
7492 if (!CandidateSet
.isNewCandidate(MethodTmpl
, PO
))
7495 // C++ [over.match.funcs]p7:
7496 // In each case where a candidate is a function template, candidate
7497 // function template specializations are generated using template argument
7498 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7499 // candidate functions in the usual way.113) A given name can refer to one
7500 // or more function templates and also to a set of overloaded non-template
7501 // functions. In such a case, the candidate functions generated from each
7502 // function template are combined with the set of non-template candidate
7504 TemplateDeductionInfo
Info(CandidateSet
.getLocation());
7505 FunctionDecl
*Specialization
= nullptr;
7506 ConversionSequenceList Conversions
;
7507 if (TemplateDeductionResult Result
= DeduceTemplateArguments(
7508 MethodTmpl
, ExplicitTemplateArgs
, Args
, Specialization
, Info
,
7509 PartialOverloading
, /*AggregateDeductionCandidate=*/false, ObjectType
,
7510 ObjectClassification
, [&](ArrayRef
<QualType
> ParamTypes
) {
7511 return CheckNonDependentConversions(
7512 MethodTmpl
, ParamTypes
, Args
, CandidateSet
, Conversions
,
7513 SuppressUserConversions
, ActingContext
, ObjectType
,
7514 ObjectClassification
, PO
);
7516 OverloadCandidate
&Candidate
=
7517 CandidateSet
.addCandidate(Conversions
.size(), Conversions
);
7518 Candidate
.FoundDecl
= FoundDecl
;
7519 Candidate
.Function
= MethodTmpl
->getTemplatedDecl();
7520 Candidate
.Viable
= false;
7521 Candidate
.RewriteKind
=
7522 CandidateSet
.getRewriteInfo().getRewriteKind(Candidate
.Function
, PO
);
7523 Candidate
.IsSurrogate
= false;
7524 Candidate
.IgnoreObjectArgument
=
7525 cast
<CXXMethodDecl
>(Candidate
.Function
)->isStatic() ||
7526 ObjectType
.isNull();
7527 Candidate
.ExplicitCallArguments
= Args
.size();
7528 if (Result
== TDK_NonDependentConversionFailure
)
7529 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7531 Candidate
.FailureKind
= ovl_fail_bad_deduction
;
7532 Candidate
.DeductionFailure
= MakeDeductionFailureInfo(Context
, Result
,
7538 // Add the function template specialization produced by template argument
7539 // deduction as a candidate.
7540 assert(Specialization
&& "Missing member function template specialization?");
7541 assert(isa
<CXXMethodDecl
>(Specialization
) &&
7542 "Specialization is not a member function?");
7543 AddMethodCandidate(cast
<CXXMethodDecl
>(Specialization
), FoundDecl
,
7544 ActingContext
, ObjectType
, ObjectClassification
, Args
,
7545 CandidateSet
, SuppressUserConversions
, PartialOverloading
,
7549 /// Determine whether a given function template has a simple explicit specifier
7550 /// or a non-value-dependent explicit-specification that evaluates to true.
7551 static bool isNonDependentlyExplicit(FunctionTemplateDecl
*FTD
) {
7552 return ExplicitSpecifier::getFromDecl(FTD
->getTemplatedDecl()).isExplicit();
7555 /// Add a C++ function template specialization as a candidate
7556 /// in the candidate set, using template argument deduction to produce
7557 /// an appropriate function template specialization.
7558 void Sema::AddTemplateOverloadCandidate(
7559 FunctionTemplateDecl
*FunctionTemplate
, DeclAccessPair FoundDecl
,
7560 TemplateArgumentListInfo
*ExplicitTemplateArgs
, ArrayRef
<Expr
*> Args
,
7561 OverloadCandidateSet
&CandidateSet
, bool SuppressUserConversions
,
7562 bool PartialOverloading
, bool AllowExplicit
, ADLCallKind IsADLCandidate
,
7563 OverloadCandidateParamOrder PO
, bool AggregateCandidateDeduction
) {
7564 if (!CandidateSet
.isNewCandidate(FunctionTemplate
, PO
))
7567 // If the function template has a non-dependent explicit specification,
7568 // exclude it now if appropriate; we are not permitted to perform deduction
7569 // and substitution in this case.
7570 if (!AllowExplicit
&& isNonDependentlyExplicit(FunctionTemplate
)) {
7571 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate();
7572 Candidate
.FoundDecl
= FoundDecl
;
7573 Candidate
.Function
= FunctionTemplate
->getTemplatedDecl();
7574 Candidate
.Viable
= false;
7575 Candidate
.FailureKind
= ovl_fail_explicit
;
7579 // C++ [over.match.funcs]p7:
7580 // In each case where a candidate is a function template, candidate
7581 // function template specializations are generated using template argument
7582 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7583 // candidate functions in the usual way.113) A given name can refer to one
7584 // or more function templates and also to a set of overloaded non-template
7585 // functions. In such a case, the candidate functions generated from each
7586 // function template are combined with the set of non-template candidate
7588 TemplateDeductionInfo
Info(CandidateSet
.getLocation());
7589 FunctionDecl
*Specialization
= nullptr;
7590 ConversionSequenceList Conversions
;
7591 if (TemplateDeductionResult Result
= DeduceTemplateArguments(
7592 FunctionTemplate
, ExplicitTemplateArgs
, Args
, Specialization
, Info
,
7593 PartialOverloading
, AggregateCandidateDeduction
,
7594 /*ObjectType=*/QualType(),
7595 /*ObjectClassification=*/Expr::Classification(),
7596 [&](ArrayRef
<QualType
> ParamTypes
) {
7597 return CheckNonDependentConversions(
7598 FunctionTemplate
, ParamTypes
, Args
, CandidateSet
, Conversions
,
7599 SuppressUserConversions
, nullptr, QualType(), {}, PO
);
7601 OverloadCandidate
&Candidate
=
7602 CandidateSet
.addCandidate(Conversions
.size(), Conversions
);
7603 Candidate
.FoundDecl
= FoundDecl
;
7604 Candidate
.Function
= FunctionTemplate
->getTemplatedDecl();
7605 Candidate
.Viable
= false;
7606 Candidate
.RewriteKind
=
7607 CandidateSet
.getRewriteInfo().getRewriteKind(Candidate
.Function
, PO
);
7608 Candidate
.IsSurrogate
= false;
7609 Candidate
.IsADLCandidate
= IsADLCandidate
;
7610 // Ignore the object argument if there is one, since we don't have an object
7612 Candidate
.IgnoreObjectArgument
=
7613 isa
<CXXMethodDecl
>(Candidate
.Function
) &&
7614 !isa
<CXXConstructorDecl
>(Candidate
.Function
);
7615 Candidate
.ExplicitCallArguments
= Args
.size();
7616 if (Result
== TDK_NonDependentConversionFailure
)
7617 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7619 Candidate
.FailureKind
= ovl_fail_bad_deduction
;
7620 Candidate
.DeductionFailure
= MakeDeductionFailureInfo(Context
, Result
,
7626 // Add the function template specialization produced by template argument
7627 // deduction as a candidate.
7628 assert(Specialization
&& "Missing function template specialization?");
7629 AddOverloadCandidate(
7630 Specialization
, FoundDecl
, Args
, CandidateSet
, SuppressUserConversions
,
7631 PartialOverloading
, AllowExplicit
,
7632 /*AllowExplicitConversions=*/false, IsADLCandidate
, Conversions
, PO
,
7633 Info
.AggregateDeductionCandidateHasMismatchedArity
);
7636 /// Check that implicit conversion sequences can be formed for each argument
7637 /// whose corresponding parameter has a non-dependent type, per DR1391's
7638 /// [temp.deduct.call]p10.
7639 bool Sema::CheckNonDependentConversions(
7640 FunctionTemplateDecl
*FunctionTemplate
, ArrayRef
<QualType
> ParamTypes
,
7641 ArrayRef
<Expr
*> Args
, OverloadCandidateSet
&CandidateSet
,
7642 ConversionSequenceList
&Conversions
, bool SuppressUserConversions
,
7643 CXXRecordDecl
*ActingContext
, QualType ObjectType
,
7644 Expr::Classification ObjectClassification
, OverloadCandidateParamOrder PO
) {
7645 // FIXME: The cases in which we allow explicit conversions for constructor
7646 // arguments never consider calling a constructor template. It's not clear
7648 const bool AllowExplicit
= false;
7650 auto *FD
= FunctionTemplate
->getTemplatedDecl();
7651 auto *Method
= dyn_cast
<CXXMethodDecl
>(FD
);
7652 bool HasThisConversion
= Method
&& !isa
<CXXConstructorDecl
>(Method
);
7653 unsigned ThisConversions
= HasThisConversion
? 1 : 0;
7656 CandidateSet
.allocateConversionSequences(ThisConversions
+ Args
.size());
7658 // Overload resolution is always an unevaluated context.
7659 EnterExpressionEvaluationContext
Unevaluated(
7660 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
7662 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7663 // require that, but this check should never result in a hard error, and
7664 // overload resolution is permitted to sidestep instantiations.
7665 if (HasThisConversion
&& !cast
<CXXMethodDecl
>(FD
)->isStatic() &&
7666 !ObjectType
.isNull()) {
7667 unsigned ConvIdx
= PO
== OverloadCandidateParamOrder::Reversed
? 1 : 0;
7668 if (!FD
->hasCXXExplicitFunctionObjectParameter() ||
7669 !ParamTypes
[0]->isDependentType()) {
7670 Conversions
[ConvIdx
] = TryObjectArgumentInitialization(
7671 *this, CandidateSet
.getLocation(), ObjectType
, ObjectClassification
,
7672 Method
, ActingContext
, /*InOverloadResolution=*/true,
7673 FD
->hasCXXExplicitFunctionObjectParameter() ? ParamTypes
[0]
7675 if (Conversions
[ConvIdx
].isBad())
7681 Method
&& Method
->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7683 for (unsigned I
= 0, N
= std::min(ParamTypes
.size(), Args
.size()); I
!= N
;
7685 QualType ParamType
= ParamTypes
[I
+ Offset
];
7686 if (!ParamType
->isDependentType()) {
7687 unsigned ConvIdx
= PO
== OverloadCandidateParamOrder::Reversed
7689 : (ThisConversions
+ I
);
7690 Conversions
[ConvIdx
]
7691 = TryCopyInitialization(*this, Args
[I
], ParamType
,
7692 SuppressUserConversions
,
7693 /*InOverloadResolution=*/true,
7694 /*AllowObjCWritebackConversion=*/
7695 getLangOpts().ObjCAutoRefCount
,
7697 if (Conversions
[ConvIdx
].isBad())
7705 /// Determine whether this is an allowable conversion from the result
7706 /// of an explicit conversion operator to the expected type, per C++
7707 /// [over.match.conv]p1 and [over.match.ref]p1.
7709 /// \param ConvType The return type of the conversion function.
7711 /// \param ToType The type we are converting to.
7713 /// \param AllowObjCPointerConversion Allow a conversion from one
7714 /// Objective-C pointer to another.
7716 /// \returns true if the conversion is allowable, false otherwise.
7717 static bool isAllowableExplicitConversion(Sema
&S
,
7718 QualType ConvType
, QualType ToType
,
7719 bool AllowObjCPointerConversion
) {
7720 QualType ToNonRefType
= ToType
.getNonReferenceType();
7722 // Easy case: the types are the same.
7723 if (S
.Context
.hasSameUnqualifiedType(ConvType
, ToNonRefType
))
7726 // Allow qualification conversions.
7727 bool ObjCLifetimeConversion
;
7728 if (S
.IsQualificationConversion(ConvType
, ToNonRefType
, /*CStyle*/false,
7729 ObjCLifetimeConversion
))
7732 // If we're not allowed to consider Objective-C pointer conversions,
7734 if (!AllowObjCPointerConversion
)
7737 // Is this an Objective-C pointer conversion?
7738 bool IncompatibleObjC
= false;
7739 QualType ConvertedType
;
7740 return S
.isObjCPointerConversion(ConvType
, ToNonRefType
, ConvertedType
,
7744 /// AddConversionCandidate - Add a C++ conversion function as a
7745 /// candidate in the candidate set (C++ [over.match.conv],
7746 /// C++ [over.match.copy]). From is the expression we're converting from,
7747 /// and ToType is the type that we're eventually trying to convert to
7748 /// (which may or may not be the same type as the type that the
7749 /// conversion function produces).
7750 void Sema::AddConversionCandidate(
7751 CXXConversionDecl
*Conversion
, DeclAccessPair FoundDecl
,
7752 CXXRecordDecl
*ActingContext
, Expr
*From
, QualType ToType
,
7753 OverloadCandidateSet
&CandidateSet
, bool AllowObjCConversionOnExplicit
,
7754 bool AllowExplicit
, bool AllowResultConversion
) {
7755 assert(!Conversion
->getDescribedFunctionTemplate() &&
7756 "Conversion function templates use AddTemplateConversionCandidate");
7757 QualType ConvType
= Conversion
->getConversionType().getNonReferenceType();
7758 if (!CandidateSet
.isNewCandidate(Conversion
))
7761 // If the conversion function has an undeduced return type, trigger its
7763 if (getLangOpts().CPlusPlus14
&& ConvType
->isUndeducedType()) {
7764 if (DeduceReturnType(Conversion
, From
->getExprLoc()))
7766 ConvType
= Conversion
->getConversionType().getNonReferenceType();
7769 // If we don't allow any conversion of the result type, ignore conversion
7770 // functions that don't convert to exactly (possibly cv-qualified) T.
7771 if (!AllowResultConversion
&&
7772 !Context
.hasSameUnqualifiedType(Conversion
->getConversionType(), ToType
))
7775 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7776 // operator is only a candidate if its return type is the target type or
7777 // can be converted to the target type with a qualification conversion.
7779 // FIXME: Include such functions in the candidate list and explain why we
7780 // can't select them.
7781 if (Conversion
->isExplicit() &&
7782 !isAllowableExplicitConversion(*this, ConvType
, ToType
,
7783 AllowObjCConversionOnExplicit
))
7786 // Overload resolution is always an unevaluated context.
7787 EnterExpressionEvaluationContext
Unevaluated(
7788 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
7790 // Add this candidate
7791 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate(1);
7792 Candidate
.FoundDecl
= FoundDecl
;
7793 Candidate
.Function
= Conversion
;
7794 Candidate
.IsSurrogate
= false;
7795 Candidate
.IgnoreObjectArgument
= false;
7796 Candidate
.FinalConversion
.setAsIdentityConversion();
7797 Candidate
.FinalConversion
.setFromType(ConvType
);
7798 Candidate
.FinalConversion
.setAllToTypes(ToType
);
7799 Candidate
.Viable
= true;
7800 Candidate
.ExplicitCallArguments
= 1;
7802 // Explicit functions are not actually candidates at all if we're not
7803 // allowing them in this context, but keep them around so we can point
7804 // to them in diagnostics.
7805 if (!AllowExplicit
&& Conversion
->isExplicit()) {
7806 Candidate
.Viable
= false;
7807 Candidate
.FailureKind
= ovl_fail_explicit
;
7811 // C++ [over.match.funcs]p4:
7812 // For conversion functions, the function is considered to be a member of
7813 // the class of the implicit implied object argument for the purpose of
7814 // defining the type of the implicit object parameter.
7816 // Determine the implicit conversion sequence for the implicit
7817 // object parameter.
7818 QualType ObjectType
= From
->getType();
7819 if (const auto *FromPtrType
= ObjectType
->getAs
<PointerType
>())
7820 ObjectType
= FromPtrType
->getPointeeType();
7821 const auto *ConversionContext
=
7822 cast
<CXXRecordDecl
>(ObjectType
->castAs
<RecordType
>()->getDecl());
7824 // C++23 [over.best.ics.general]
7825 // However, if the target is [...]
7826 // - the object parameter of a user-defined conversion function
7827 // [...] user-defined conversion sequences are not considered.
7828 Candidate
.Conversions
[0] = TryObjectArgumentInitialization(
7829 *this, CandidateSet
.getLocation(), From
->getType(),
7830 From
->Classify(Context
), Conversion
, ConversionContext
,
7831 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
7832 /*SuppressUserConversion*/ true);
7834 if (Candidate
.Conversions
[0].isBad()) {
7835 Candidate
.Viable
= false;
7836 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7840 if (Conversion
->getTrailingRequiresClause()) {
7841 ConstraintSatisfaction Satisfaction
;
7842 if (CheckFunctionConstraints(Conversion
, Satisfaction
) ||
7843 !Satisfaction
.IsSatisfied
) {
7844 Candidate
.Viable
= false;
7845 Candidate
.FailureKind
= ovl_fail_constraints_not_satisfied
;
7850 // We won't go through a user-defined type conversion function to convert a
7851 // derived to base as such conversions are given Conversion Rank. They only
7852 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7854 = Context
.getCanonicalType(From
->getType().getUnqualifiedType());
7855 QualType ToCanon
= Context
.getCanonicalType(ToType
).getUnqualifiedType();
7856 if (FromCanon
== ToCanon
||
7857 IsDerivedFrom(CandidateSet
.getLocation(), FromCanon
, ToCanon
)) {
7858 Candidate
.Viable
= false;
7859 Candidate
.FailureKind
= ovl_fail_trivial_conversion
;
7863 // To determine what the conversion from the result of calling the
7864 // conversion function to the type we're eventually trying to
7865 // convert to (ToType), we need to synthesize a call to the
7866 // conversion function and attempt copy initialization from it. This
7867 // makes sure that we get the right semantics with respect to
7868 // lvalues/rvalues and the type. Fortunately, we can allocate this
7869 // call on the stack and we don't need its arguments to be
7871 DeclRefExpr
ConversionRef(Context
, Conversion
, false, Conversion
->getType(),
7872 VK_LValue
, From
->getBeginLoc());
7873 ImplicitCastExpr
ConversionFn(ImplicitCastExpr::OnStack
,
7874 Context
.getPointerType(Conversion
->getType()),
7875 CK_FunctionToPointerDecay
, &ConversionRef
,
7876 VK_PRValue
, FPOptionsOverride());
7878 QualType ConversionType
= Conversion
->getConversionType();
7879 if (!isCompleteType(From
->getBeginLoc(), ConversionType
)) {
7880 Candidate
.Viable
= false;
7881 Candidate
.FailureKind
= ovl_fail_bad_final_conversion
;
7885 ExprValueKind VK
= Expr::getValueKindForType(ConversionType
);
7887 // Note that it is safe to allocate CallExpr on the stack here because
7888 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7890 QualType CallResultType
= ConversionType
.getNonLValueExprType(Context
);
7892 alignas(CallExpr
) char Buffer
[sizeof(CallExpr
) + sizeof(Stmt
*)];
7893 CallExpr
*TheTemporaryCall
= CallExpr::CreateTemporary(
7894 Buffer
, &ConversionFn
, CallResultType
, VK
, From
->getBeginLoc());
7896 ImplicitConversionSequence ICS
=
7897 TryCopyInitialization(*this, TheTemporaryCall
, ToType
,
7898 /*SuppressUserConversions=*/true,
7899 /*InOverloadResolution=*/false,
7900 /*AllowObjCWritebackConversion=*/false);
7902 switch (ICS
.getKind()) {
7903 case ImplicitConversionSequence::StandardConversion
:
7904 Candidate
.FinalConversion
= ICS
.Standard
;
7906 // C++ [over.ics.user]p3:
7907 // If the user-defined conversion is specified by a specialization of a
7908 // conversion function template, the second standard conversion sequence
7909 // shall have exact match rank.
7910 if (Conversion
->getPrimaryTemplate() &&
7911 GetConversionRank(ICS
.Standard
.Second
) != ICR_Exact_Match
) {
7912 Candidate
.Viable
= false;
7913 Candidate
.FailureKind
= ovl_fail_final_conversion_not_exact
;
7917 // C++0x [dcl.init.ref]p5:
7918 // In the second case, if the reference is an rvalue reference and
7919 // the second standard conversion sequence of the user-defined
7920 // conversion sequence includes an lvalue-to-rvalue conversion, the
7921 // program is ill-formed.
7922 if (ToType
->isRValueReferenceType() &&
7923 ICS
.Standard
.First
== ICK_Lvalue_To_Rvalue
) {
7924 Candidate
.Viable
= false;
7925 Candidate
.FailureKind
= ovl_fail_bad_final_conversion
;
7930 case ImplicitConversionSequence::BadConversion
:
7931 Candidate
.Viable
= false;
7932 Candidate
.FailureKind
= ovl_fail_bad_final_conversion
;
7937 "Can only end up with a standard conversion sequence or failure");
7940 if (EnableIfAttr
*FailedAttr
=
7941 CheckEnableIf(Conversion
, CandidateSet
.getLocation(), std::nullopt
)) {
7942 Candidate
.Viable
= false;
7943 Candidate
.FailureKind
= ovl_fail_enable_if
;
7944 Candidate
.DeductionFailure
.Data
= FailedAttr
;
7948 if (Conversion
->isMultiVersion() &&
7949 ((Conversion
->hasAttr
<TargetAttr
>() &&
7950 !Conversion
->getAttr
<TargetAttr
>()->isDefaultVersion()) ||
7951 (Conversion
->hasAttr
<TargetVersionAttr
>() &&
7952 !Conversion
->getAttr
<TargetVersionAttr
>()->isDefaultVersion()))) {
7953 Candidate
.Viable
= false;
7954 Candidate
.FailureKind
= ovl_non_default_multiversion_function
;
7958 /// Adds a conversion function template specialization
7959 /// candidate to the overload set, using template argument deduction
7960 /// to deduce the template arguments of the conversion function
7961 /// template from the type that we are converting to (C++
7962 /// [temp.deduct.conv]).
7963 void Sema::AddTemplateConversionCandidate(
7964 FunctionTemplateDecl
*FunctionTemplate
, DeclAccessPair FoundDecl
,
7965 CXXRecordDecl
*ActingDC
, Expr
*From
, QualType ToType
,
7966 OverloadCandidateSet
&CandidateSet
, bool AllowObjCConversionOnExplicit
,
7967 bool AllowExplicit
, bool AllowResultConversion
) {
7968 assert(isa
<CXXConversionDecl
>(FunctionTemplate
->getTemplatedDecl()) &&
7969 "Only conversion function templates permitted here");
7971 if (!CandidateSet
.isNewCandidate(FunctionTemplate
))
7974 // If the function template has a non-dependent explicit specification,
7975 // exclude it now if appropriate; we are not permitted to perform deduction
7976 // and substitution in this case.
7977 if (!AllowExplicit
&& isNonDependentlyExplicit(FunctionTemplate
)) {
7978 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate();
7979 Candidate
.FoundDecl
= FoundDecl
;
7980 Candidate
.Function
= FunctionTemplate
->getTemplatedDecl();
7981 Candidate
.Viable
= false;
7982 Candidate
.FailureKind
= ovl_fail_explicit
;
7986 QualType ObjectType
= From
->getType();
7987 Expr::Classification ObjectClassification
= From
->Classify(getASTContext());
7989 TemplateDeductionInfo
Info(CandidateSet
.getLocation());
7990 CXXConversionDecl
*Specialization
= nullptr;
7991 if (TemplateDeductionResult Result
= DeduceTemplateArguments(
7992 FunctionTemplate
, ObjectType
, ObjectClassification
, ToType
,
7993 Specialization
, Info
)) {
7994 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate();
7995 Candidate
.FoundDecl
= FoundDecl
;
7996 Candidate
.Function
= FunctionTemplate
->getTemplatedDecl();
7997 Candidate
.Viable
= false;
7998 Candidate
.FailureKind
= ovl_fail_bad_deduction
;
7999 Candidate
.IsSurrogate
= false;
8000 Candidate
.IgnoreObjectArgument
= false;
8001 Candidate
.ExplicitCallArguments
= 1;
8002 Candidate
.DeductionFailure
= MakeDeductionFailureInfo(Context
, Result
,
8007 // Add the conversion function template specialization produced by
8008 // template argument deduction as a candidate.
8009 assert(Specialization
&& "Missing function template specialization?");
8010 AddConversionCandidate(Specialization
, FoundDecl
, ActingDC
, From
, ToType
,
8011 CandidateSet
, AllowObjCConversionOnExplicit
,
8012 AllowExplicit
, AllowResultConversion
);
8015 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8016 /// converts the given @c Object to a function pointer via the
8017 /// conversion function @c Conversion, and then attempts to call it
8018 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
8019 /// the type of function that we'll eventually be calling.
8020 void Sema::AddSurrogateCandidate(CXXConversionDecl
*Conversion
,
8021 DeclAccessPair FoundDecl
,
8022 CXXRecordDecl
*ActingContext
,
8023 const FunctionProtoType
*Proto
,
8025 ArrayRef
<Expr
*> Args
,
8026 OverloadCandidateSet
& CandidateSet
) {
8027 if (!CandidateSet
.isNewCandidate(Conversion
))
8030 // Overload resolution is always an unevaluated context.
8031 EnterExpressionEvaluationContext
Unevaluated(
8032 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
8034 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate(Args
.size() + 1);
8035 Candidate
.FoundDecl
= FoundDecl
;
8036 Candidate
.Function
= nullptr;
8037 Candidate
.Surrogate
= Conversion
;
8038 Candidate
.Viable
= true;
8039 Candidate
.IsSurrogate
= true;
8040 Candidate
.IgnoreObjectArgument
= false;
8041 Candidate
.ExplicitCallArguments
= Args
.size();
8043 // Determine the implicit conversion sequence for the implicit
8044 // object parameter.
8045 ImplicitConversionSequence ObjectInit
;
8046 if (Conversion
->hasCXXExplicitFunctionObjectParameter()) {
8047 ObjectInit
= TryCopyInitialization(*this, Object
,
8048 Conversion
->getParamDecl(0)->getType(),
8049 /*SuppressUserConversions=*/false,
8050 /*InOverloadResolution=*/true, false);
8052 ObjectInit
= TryObjectArgumentInitialization(
8053 *this, CandidateSet
.getLocation(), Object
->getType(),
8054 Object
->Classify(Context
), Conversion
, ActingContext
);
8057 if (ObjectInit
.isBad()) {
8058 Candidate
.Viable
= false;
8059 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
8060 Candidate
.Conversions
[0] = ObjectInit
;
8064 // The first conversion is actually a user-defined conversion whose
8065 // first conversion is ObjectInit's standard conversion (which is
8066 // effectively a reference binding). Record it as such.
8067 Candidate
.Conversions
[0].setUserDefined();
8068 Candidate
.Conversions
[0].UserDefined
.Before
= ObjectInit
.Standard
;
8069 Candidate
.Conversions
[0].UserDefined
.EllipsisConversion
= false;
8070 Candidate
.Conversions
[0].UserDefined
.HadMultipleCandidates
= false;
8071 Candidate
.Conversions
[0].UserDefined
.ConversionFunction
= Conversion
;
8072 Candidate
.Conversions
[0].UserDefined
.FoundConversionFunction
= FoundDecl
;
8073 Candidate
.Conversions
[0].UserDefined
.After
8074 = Candidate
.Conversions
[0].UserDefined
.Before
;
8075 Candidate
.Conversions
[0].UserDefined
.After
.setAsIdentityConversion();
8078 unsigned NumParams
= Proto
->getNumParams();
8080 // (C++ 13.3.2p2): A candidate function having fewer than m
8081 // parameters is viable only if it has an ellipsis in its parameter
8083 if (Args
.size() > NumParams
&& !Proto
->isVariadic()) {
8084 Candidate
.Viable
= false;
8085 Candidate
.FailureKind
= ovl_fail_too_many_arguments
;
8089 // Function types don't have any default arguments, so just check if
8090 // we have enough arguments.
8091 if (Args
.size() < NumParams
) {
8092 // Not enough arguments.
8093 Candidate
.Viable
= false;
8094 Candidate
.FailureKind
= ovl_fail_too_few_arguments
;
8098 // Determine the implicit conversion sequences for each of the
8100 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
8101 if (ArgIdx
< NumParams
) {
8102 // (C++ 13.3.2p3): for F to be a viable function, there shall
8103 // exist for each argument an implicit conversion sequence
8104 // (13.3.3.1) that converts that argument to the corresponding
8106 QualType ParamType
= Proto
->getParamType(ArgIdx
);
8107 Candidate
.Conversions
[ArgIdx
+ 1]
8108 = TryCopyInitialization(*this, Args
[ArgIdx
], ParamType
,
8109 /*SuppressUserConversions=*/false,
8110 /*InOverloadResolution=*/false,
8111 /*AllowObjCWritebackConversion=*/
8112 getLangOpts().ObjCAutoRefCount
);
8113 if (Candidate
.Conversions
[ArgIdx
+ 1].isBad()) {
8114 Candidate
.Viable
= false;
8115 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
8119 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8120 // argument for which there is no corresponding parameter is
8121 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8122 Candidate
.Conversions
[ArgIdx
+ 1].setEllipsis();
8126 if (Conversion
->getTrailingRequiresClause()) {
8127 ConstraintSatisfaction Satisfaction
;
8128 if (CheckFunctionConstraints(Conversion
, Satisfaction
, /*Loc*/ {},
8129 /*ForOverloadResolution*/ true) ||
8130 !Satisfaction
.IsSatisfied
) {
8131 Candidate
.Viable
= false;
8132 Candidate
.FailureKind
= ovl_fail_constraints_not_satisfied
;
8137 if (EnableIfAttr
*FailedAttr
=
8138 CheckEnableIf(Conversion
, CandidateSet
.getLocation(), std::nullopt
)) {
8139 Candidate
.Viable
= false;
8140 Candidate
.FailureKind
= ovl_fail_enable_if
;
8141 Candidate
.DeductionFailure
.Data
= FailedAttr
;
8146 /// Add all of the non-member operator function declarations in the given
8147 /// function set to the overload candidate set.
8148 void Sema::AddNonMemberOperatorCandidates(
8149 const UnresolvedSetImpl
&Fns
, ArrayRef
<Expr
*> Args
,
8150 OverloadCandidateSet
&CandidateSet
,
8151 TemplateArgumentListInfo
*ExplicitTemplateArgs
) {
8152 for (UnresolvedSetIterator F
= Fns
.begin(), E
= Fns
.end(); F
!= E
; ++F
) {
8153 NamedDecl
*D
= F
.getDecl()->getUnderlyingDecl();
8154 ArrayRef
<Expr
*> FunctionArgs
= Args
;
8156 FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
);
8158 FunTmpl
? FunTmpl
->getTemplatedDecl() : cast
<FunctionDecl
>(D
);
8160 // Don't consider rewritten functions if we're not rewriting.
8161 if (!CandidateSet
.getRewriteInfo().isAcceptableCandidate(FD
))
8164 assert(!isa
<CXXMethodDecl
>(FD
) &&
8165 "unqualified operator lookup found a member function");
8168 AddTemplateOverloadCandidate(FunTmpl
, F
.getPair(), ExplicitTemplateArgs
,
8169 FunctionArgs
, CandidateSet
);
8170 if (CandidateSet
.getRewriteInfo().shouldAddReversed(*this, Args
, FD
))
8171 AddTemplateOverloadCandidate(
8172 FunTmpl
, F
.getPair(), ExplicitTemplateArgs
,
8173 {FunctionArgs
[1], FunctionArgs
[0]}, CandidateSet
, false, false,
8174 true, ADLCallKind::NotADL
, OverloadCandidateParamOrder::Reversed
);
8176 if (ExplicitTemplateArgs
)
8178 AddOverloadCandidate(FD
, F
.getPair(), FunctionArgs
, CandidateSet
);
8179 if (CandidateSet
.getRewriteInfo().shouldAddReversed(*this, Args
, FD
))
8180 AddOverloadCandidate(
8181 FD
, F
.getPair(), {FunctionArgs
[1], FunctionArgs
[0]}, CandidateSet
,
8182 false, false, true, false, ADLCallKind::NotADL
, std::nullopt
,
8183 OverloadCandidateParamOrder::Reversed
);
8188 /// Add overload candidates for overloaded operators that are
8189 /// member functions.
8191 /// Add the overloaded operator candidates that are member functions
8192 /// for the operator Op that was used in an operator expression such
8193 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
8194 /// CandidateSet will store the added overload candidates. (C++
8195 /// [over.match.oper]).
8196 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op
,
8197 SourceLocation OpLoc
,
8198 ArrayRef
<Expr
*> Args
,
8199 OverloadCandidateSet
&CandidateSet
,
8200 OverloadCandidateParamOrder PO
) {
8201 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
8203 // C++ [over.match.oper]p3:
8204 // For a unary operator @ with an operand of a type whose
8205 // cv-unqualified version is T1, and for a binary operator @ with
8206 // a left operand of a type whose cv-unqualified version is T1 and
8207 // a right operand of a type whose cv-unqualified version is T2,
8208 // three sets of candidate functions, designated member
8209 // candidates, non-member candidates and built-in candidates, are
8210 // constructed as follows:
8211 QualType T1
= Args
[0]->getType();
8213 // -- If T1 is a complete class type or a class currently being
8214 // defined, the set of member candidates is the result of the
8215 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8216 // the set of member candidates is empty.
8217 if (const RecordType
*T1Rec
= T1
->getAs
<RecordType
>()) {
8218 // Complete the type if it can be completed.
8219 if (!isCompleteType(OpLoc
, T1
) && !T1Rec
->isBeingDefined())
8221 // If the type is neither complete nor being defined, bail out now.
8222 if (!T1Rec
->getDecl()->getDefinition())
8225 LookupResult
Operators(*this, OpName
, OpLoc
, LookupOrdinaryName
);
8226 LookupQualifiedName(Operators
, T1Rec
->getDecl());
8227 Operators
.suppressAccessDiagnostics();
8229 for (LookupResult::iterator Oper
= Operators
.begin(),
8230 OperEnd
= Operators
.end();
8231 Oper
!= OperEnd
; ++Oper
) {
8232 if (Oper
->getAsFunction() &&
8233 PO
== OverloadCandidateParamOrder::Reversed
&&
8234 !CandidateSet
.getRewriteInfo().shouldAddReversed(
8235 *this, {Args
[1], Args
[0]}, Oper
->getAsFunction()))
8237 AddMethodCandidate(Oper
.getPair(), Args
[0]->getType(),
8238 Args
[0]->Classify(Context
), Args
.slice(1),
8239 CandidateSet
, /*SuppressUserConversion=*/false, PO
);
8244 /// AddBuiltinCandidate - Add a candidate for a built-in
8245 /// operator. ResultTy and ParamTys are the result and parameter types
8246 /// of the built-in candidate, respectively. Args and NumArgs are the
8247 /// arguments being passed to the candidate. IsAssignmentOperator
8248 /// should be true when this built-in candidate is an assignment
8249 /// operator. NumContextualBoolArguments is the number of arguments
8250 /// (at the beginning of the argument list) that will be contextually
8251 /// converted to bool.
8252 void Sema::AddBuiltinCandidate(QualType
*ParamTys
, ArrayRef
<Expr
*> Args
,
8253 OverloadCandidateSet
& CandidateSet
,
8254 bool IsAssignmentOperator
,
8255 unsigned NumContextualBoolArguments
) {
8256 // Overload resolution is always an unevaluated context.
8257 EnterExpressionEvaluationContext
Unevaluated(
8258 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
8260 // Add this candidate
8261 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate(Args
.size());
8262 Candidate
.FoundDecl
= DeclAccessPair::make(nullptr, AS_none
);
8263 Candidate
.Function
= nullptr;
8264 Candidate
.IsSurrogate
= false;
8265 Candidate
.IgnoreObjectArgument
= false;
8266 std::copy(ParamTys
, ParamTys
+ Args
.size(), Candidate
.BuiltinParamTypes
);
8268 // Determine the implicit conversion sequences for each of the
8270 Candidate
.Viable
= true;
8271 Candidate
.ExplicitCallArguments
= Args
.size();
8272 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
8273 // C++ [over.match.oper]p4:
8274 // For the built-in assignment operators, conversions of the
8275 // left operand are restricted as follows:
8276 // -- no temporaries are introduced to hold the left operand, and
8277 // -- no user-defined conversions are applied to the left
8278 // operand to achieve a type match with the left-most
8279 // parameter of a built-in candidate.
8281 // We block these conversions by turning off user-defined
8282 // conversions, since that is the only way that initialization of
8283 // a reference to a non-class type can occur from something that
8284 // is not of the same type.
8285 if (ArgIdx
< NumContextualBoolArguments
) {
8286 assert(ParamTys
[ArgIdx
] == Context
.BoolTy
&&
8287 "Contextual conversion to bool requires bool type");
8288 Candidate
.Conversions
[ArgIdx
]
8289 = TryContextuallyConvertToBool(*this, Args
[ArgIdx
]);
8291 Candidate
.Conversions
[ArgIdx
]
8292 = TryCopyInitialization(*this, Args
[ArgIdx
], ParamTys
[ArgIdx
],
8293 ArgIdx
== 0 && IsAssignmentOperator
,
8294 /*InOverloadResolution=*/false,
8295 /*AllowObjCWritebackConversion=*/
8296 getLangOpts().ObjCAutoRefCount
);
8298 if (Candidate
.Conversions
[ArgIdx
].isBad()) {
8299 Candidate
.Viable
= false;
8300 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
8308 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8309 /// candidate operator functions for built-in operators (C++
8310 /// [over.built]). The types are separated into pointer types and
8311 /// enumeration types.
8312 class BuiltinCandidateTypeSet
{
8313 /// TypeSet - A set of types.
8314 typedef llvm::SmallSetVector
<QualType
, 8> TypeSet
;
8316 /// PointerTypes - The set of pointer types that will be used in the
8317 /// built-in candidates.
8318 TypeSet PointerTypes
;
8320 /// MemberPointerTypes - The set of member pointer types that will be
8321 /// used in the built-in candidates.
8322 TypeSet MemberPointerTypes
;
8324 /// EnumerationTypes - The set of enumeration types that will be
8325 /// used in the built-in candidates.
8326 TypeSet EnumerationTypes
;
8328 /// The set of vector types that will be used in the built-in
8330 TypeSet VectorTypes
;
8332 /// The set of matrix types that will be used in the built-in
8334 TypeSet MatrixTypes
;
8336 /// A flag indicating non-record types are viable candidates
8337 bool HasNonRecordTypes
;
8339 /// A flag indicating whether either arithmetic or enumeration types
8340 /// were present in the candidate set.
8341 bool HasArithmeticOrEnumeralTypes
;
8343 /// A flag indicating whether the nullptr type was present in the
8345 bool HasNullPtrType
;
8347 /// Sema - The semantic analysis instance where we are building the
8348 /// candidate type set.
8351 /// Context - The AST context in which we will build the type sets.
8352 ASTContext
&Context
;
8354 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty
,
8355 const Qualifiers
&VisibleQuals
);
8356 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty
);
8359 /// iterator - Iterates through the types that are part of the set.
8360 typedef TypeSet::iterator iterator
;
8362 BuiltinCandidateTypeSet(Sema
&SemaRef
)
8363 : HasNonRecordTypes(false),
8364 HasArithmeticOrEnumeralTypes(false),
8365 HasNullPtrType(false),
8367 Context(SemaRef
.Context
) { }
8369 void AddTypesConvertedFrom(QualType Ty
,
8371 bool AllowUserConversions
,
8372 bool AllowExplicitConversions
,
8373 const Qualifiers
&VisibleTypeConversionsQuals
);
8375 llvm::iterator_range
<iterator
> pointer_types() { return PointerTypes
; }
8376 llvm::iterator_range
<iterator
> member_pointer_types() {
8377 return MemberPointerTypes
;
8379 llvm::iterator_range
<iterator
> enumeration_types() {
8380 return EnumerationTypes
;
8382 llvm::iterator_range
<iterator
> vector_types() { return VectorTypes
; }
8383 llvm::iterator_range
<iterator
> matrix_types() { return MatrixTypes
; }
8385 bool containsMatrixType(QualType Ty
) const { return MatrixTypes
.count(Ty
); }
8386 bool hasNonRecordTypes() { return HasNonRecordTypes
; }
8387 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes
; }
8388 bool hasNullPtrType() const { return HasNullPtrType
; }
8391 } // end anonymous namespace
8393 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8394 /// the set of pointer types along with any more-qualified variants of
8395 /// that type. For example, if @p Ty is "int const *", this routine
8396 /// will add "int const *", "int const volatile *", "int const
8397 /// restrict *", and "int const volatile restrict *" to the set of
8398 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8399 /// false otherwise.
8401 /// FIXME: what to do about extended qualifiers?
8403 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty
,
8404 const Qualifiers
&VisibleQuals
) {
8406 // Insert this type.
8407 if (!PointerTypes
.insert(Ty
))
8411 const PointerType
*PointerTy
= Ty
->getAs
<PointerType
>();
8412 bool buildObjCPtr
= false;
8414 const ObjCObjectPointerType
*PTy
= Ty
->castAs
<ObjCObjectPointerType
>();
8415 PointeeTy
= PTy
->getPointeeType();
8416 buildObjCPtr
= true;
8418 PointeeTy
= PointerTy
->getPointeeType();
8421 // Don't add qualified variants of arrays. For one, they're not allowed
8422 // (the qualifier would sink to the element type), and for another, the
8423 // only overload situation where it matters is subscript or pointer +- int,
8424 // and those shouldn't have qualifier variants anyway.
8425 if (PointeeTy
->isArrayType())
8428 unsigned BaseCVR
= PointeeTy
.getCVRQualifiers();
8429 bool hasVolatile
= VisibleQuals
.hasVolatile();
8430 bool hasRestrict
= VisibleQuals
.hasRestrict();
8432 // Iterate through all strict supersets of BaseCVR.
8433 for (unsigned CVR
= BaseCVR
+1; CVR
<= Qualifiers::CVRMask
; ++CVR
) {
8434 if ((CVR
| BaseCVR
) != CVR
) continue;
8435 // Skip over volatile if no volatile found anywhere in the types.
8436 if ((CVR
& Qualifiers::Volatile
) && !hasVolatile
) continue;
8438 // Skip over restrict if no restrict found anywhere in the types, or if
8439 // the type cannot be restrict-qualified.
8440 if ((CVR
& Qualifiers::Restrict
) &&
8442 (!(PointeeTy
->isAnyPointerType() || PointeeTy
->isReferenceType()))))
8445 // Build qualified pointee type.
8446 QualType QPointeeTy
= Context
.getCVRQualifiedType(PointeeTy
, CVR
);
8448 // Build qualified pointer type.
8449 QualType QPointerTy
;
8451 QPointerTy
= Context
.getPointerType(QPointeeTy
);
8453 QPointerTy
= Context
.getObjCObjectPointerType(QPointeeTy
);
8455 // Insert qualified pointer type.
8456 PointerTypes
.insert(QPointerTy
);
8462 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8463 /// to the set of pointer types along with any more-qualified variants of
8464 /// that type. For example, if @p Ty is "int const *", this routine
8465 /// will add "int const *", "int const volatile *", "int const
8466 /// restrict *", and "int const volatile restrict *" to the set of
8467 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8468 /// false otherwise.
8470 /// FIXME: what to do about extended qualifiers?
8472 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8474 // Insert this type.
8475 if (!MemberPointerTypes
.insert(Ty
))
8478 const MemberPointerType
*PointerTy
= Ty
->getAs
<MemberPointerType
>();
8479 assert(PointerTy
&& "type was not a member pointer type!");
8481 QualType PointeeTy
= PointerTy
->getPointeeType();
8482 // Don't add qualified variants of arrays. For one, they're not allowed
8483 // (the qualifier would sink to the element type), and for another, the
8484 // only overload situation where it matters is subscript or pointer +- int,
8485 // and those shouldn't have qualifier variants anyway.
8486 if (PointeeTy
->isArrayType())
8488 const Type
*ClassTy
= PointerTy
->getClass();
8490 // Iterate through all strict supersets of the pointee type's CVR
8492 unsigned BaseCVR
= PointeeTy
.getCVRQualifiers();
8493 for (unsigned CVR
= BaseCVR
+1; CVR
<= Qualifiers::CVRMask
; ++CVR
) {
8494 if ((CVR
| BaseCVR
) != CVR
) continue;
8496 QualType QPointeeTy
= Context
.getCVRQualifiedType(PointeeTy
, CVR
);
8497 MemberPointerTypes
.insert(
8498 Context
.getMemberPointerType(QPointeeTy
, ClassTy
));
8504 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8505 /// Ty can be implicit converted to the given set of @p Types. We're
8506 /// primarily interested in pointer types and enumeration types. We also
8507 /// take member pointer types, for the conditional operator.
8508 /// AllowUserConversions is true if we should look at the conversion
8509 /// functions of a class type, and AllowExplicitConversions if we
8510 /// should also include the explicit conversion functions of a class
8513 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty
,
8515 bool AllowUserConversions
,
8516 bool AllowExplicitConversions
,
8517 const Qualifiers
&VisibleQuals
) {
8518 // Only deal with canonical types.
8519 Ty
= Context
.getCanonicalType(Ty
);
8521 // Look through reference types; they aren't part of the type of an
8522 // expression for the purposes of conversions.
8523 if (const ReferenceType
*RefTy
= Ty
->getAs
<ReferenceType
>())
8524 Ty
= RefTy
->getPointeeType();
8526 // If we're dealing with an array type, decay to the pointer.
8527 if (Ty
->isArrayType())
8528 Ty
= SemaRef
.Context
.getArrayDecayedType(Ty
);
8530 // Otherwise, we don't care about qualifiers on the type.
8531 Ty
= Ty
.getLocalUnqualifiedType();
8533 // Flag if we ever add a non-record type.
8534 const RecordType
*TyRec
= Ty
->getAs
<RecordType
>();
8535 HasNonRecordTypes
= HasNonRecordTypes
|| !TyRec
;
8537 // Flag if we encounter an arithmetic type.
8538 HasArithmeticOrEnumeralTypes
=
8539 HasArithmeticOrEnumeralTypes
|| Ty
->isArithmeticType();
8541 if (Ty
->isObjCIdType() || Ty
->isObjCClassType())
8542 PointerTypes
.insert(Ty
);
8543 else if (Ty
->getAs
<PointerType
>() || Ty
->getAs
<ObjCObjectPointerType
>()) {
8544 // Insert our type, and its more-qualified variants, into the set
8546 if (!AddPointerWithMoreQualifiedTypeVariants(Ty
, VisibleQuals
))
8548 } else if (Ty
->isMemberPointerType()) {
8549 // Member pointers are far easier, since the pointee can't be converted.
8550 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty
))
8552 } else if (Ty
->isEnumeralType()) {
8553 HasArithmeticOrEnumeralTypes
= true;
8554 EnumerationTypes
.insert(Ty
);
8555 } else if (Ty
->isVectorType()) {
8556 // We treat vector types as arithmetic types in many contexts as an
8558 HasArithmeticOrEnumeralTypes
= true;
8559 VectorTypes
.insert(Ty
);
8560 } else if (Ty
->isMatrixType()) {
8561 // Similar to vector types, we treat vector types as arithmetic types in
8562 // many contexts as an extension.
8563 HasArithmeticOrEnumeralTypes
= true;
8564 MatrixTypes
.insert(Ty
);
8565 } else if (Ty
->isNullPtrType()) {
8566 HasNullPtrType
= true;
8567 } else if (AllowUserConversions
&& TyRec
) {
8568 // No conversion functions in incomplete types.
8569 if (!SemaRef
.isCompleteType(Loc
, Ty
))
8572 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(TyRec
->getDecl());
8573 for (NamedDecl
*D
: ClassDecl
->getVisibleConversionFunctions()) {
8574 if (isa
<UsingShadowDecl
>(D
))
8575 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
8577 // Skip conversion function templates; they don't tell us anything
8578 // about which builtin types we can convert to.
8579 if (isa
<FunctionTemplateDecl
>(D
))
8582 CXXConversionDecl
*Conv
= cast
<CXXConversionDecl
>(D
);
8583 if (AllowExplicitConversions
|| !Conv
->isExplicit()) {
8584 AddTypesConvertedFrom(Conv
->getConversionType(), Loc
, false, false,
8590 /// Helper function for adjusting address spaces for the pointer or reference
8591 /// operands of builtin operators depending on the argument.
8592 static QualType
AdjustAddressSpaceForBuiltinOperandType(Sema
&S
, QualType T
,
8594 return S
.Context
.getAddrSpaceQualType(T
, Arg
->getType().getAddressSpace());
8597 /// Helper function for AddBuiltinOperatorCandidates() that adds
8598 /// the volatile- and non-volatile-qualified assignment operators for the
8599 /// given type to the candidate set.
8600 static void AddBuiltinAssignmentOperatorCandidates(Sema
&S
,
8602 ArrayRef
<Expr
*> Args
,
8603 OverloadCandidateSet
&CandidateSet
) {
8604 QualType ParamTypes
[2];
8606 // T& operator=(T&, T)
8607 ParamTypes
[0] = S
.Context
.getLValueReferenceType(
8608 AdjustAddressSpaceForBuiltinOperandType(S
, T
, Args
[0]));
8610 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
8611 /*IsAssignmentOperator=*/true);
8613 if (!S
.Context
.getCanonicalType(T
).isVolatileQualified()) {
8614 // volatile T& operator=(volatile T&, T)
8615 ParamTypes
[0] = S
.Context
.getLValueReferenceType(
8616 AdjustAddressSpaceForBuiltinOperandType(S
, S
.Context
.getVolatileType(T
),
8619 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
8620 /*IsAssignmentOperator=*/true);
8624 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8625 /// if any, found in visible type conversion functions found in ArgExpr's type.
8626 static Qualifiers
CollectVRQualifiers(ASTContext
&Context
, Expr
* ArgExpr
) {
8628 const RecordType
*TyRec
;
8629 if (const MemberPointerType
*RHSMPType
=
8630 ArgExpr
->getType()->getAs
<MemberPointerType
>())
8631 TyRec
= RHSMPType
->getClass()->getAs
<RecordType
>();
8633 TyRec
= ArgExpr
->getType()->getAs
<RecordType
>();
8635 // Just to be safe, assume the worst case.
8636 VRQuals
.addVolatile();
8637 VRQuals
.addRestrict();
8641 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(TyRec
->getDecl());
8642 if (!ClassDecl
->hasDefinition())
8645 for (NamedDecl
*D
: ClassDecl
->getVisibleConversionFunctions()) {
8646 if (isa
<UsingShadowDecl
>(D
))
8647 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
8648 if (CXXConversionDecl
*Conv
= dyn_cast
<CXXConversionDecl
>(D
)) {
8649 QualType CanTy
= Context
.getCanonicalType(Conv
->getConversionType());
8650 if (const ReferenceType
*ResTypeRef
= CanTy
->getAs
<ReferenceType
>())
8651 CanTy
= ResTypeRef
->getPointeeType();
8652 // Need to go down the pointer/mempointer chain and add qualifiers
8656 if (CanTy
.isRestrictQualified())
8657 VRQuals
.addRestrict();
8658 if (const PointerType
*ResTypePtr
= CanTy
->getAs
<PointerType
>())
8659 CanTy
= ResTypePtr
->getPointeeType();
8660 else if (const MemberPointerType
*ResTypeMPtr
=
8661 CanTy
->getAs
<MemberPointerType
>())
8662 CanTy
= ResTypeMPtr
->getPointeeType();
8665 if (CanTy
.isVolatileQualified())
8666 VRQuals
.addVolatile();
8667 if (VRQuals
.hasRestrict() && VRQuals
.hasVolatile())
8675 // Note: We're currently only handling qualifiers that are meaningful for the
8676 // LHS of compound assignment overloading.
8677 static void forAllQualifierCombinationsImpl(
8678 QualifiersAndAtomic Available
, QualifiersAndAtomic Applied
,
8679 llvm::function_ref
<void(QualifiersAndAtomic
)> Callback
) {
8681 if (Available
.hasAtomic()) {
8682 Available
.removeAtomic();
8683 forAllQualifierCombinationsImpl(Available
, Applied
.withAtomic(), Callback
);
8684 forAllQualifierCombinationsImpl(Available
, Applied
, Callback
);
8689 if (Available
.hasVolatile()) {
8690 Available
.removeVolatile();
8691 assert(!Applied
.hasVolatile());
8692 forAllQualifierCombinationsImpl(Available
, Applied
.withVolatile(),
8694 forAllQualifierCombinationsImpl(Available
, Applied
, Callback
);
8701 static void forAllQualifierCombinations(
8702 QualifiersAndAtomic Quals
,
8703 llvm::function_ref
<void(QualifiersAndAtomic
)> Callback
) {
8704 return forAllQualifierCombinationsImpl(Quals
, QualifiersAndAtomic(),
8708 static QualType
makeQualifiedLValueReferenceType(QualType Base
,
8709 QualifiersAndAtomic Quals
,
8711 if (Quals
.hasAtomic())
8712 Base
= S
.Context
.getAtomicType(Base
);
8713 if (Quals
.hasVolatile())
8714 Base
= S
.Context
.getVolatileType(Base
);
8715 return S
.Context
.getLValueReferenceType(Base
);
8720 /// Helper class to manage the addition of builtin operator overload
8721 /// candidates. It provides shared state and utility methods used throughout
8722 /// the process, as well as a helper method to add each group of builtin
8723 /// operator overloads from the standard to a candidate set.
8724 class BuiltinOperatorOverloadBuilder
{
8725 // Common instance state available to all overload candidate addition methods.
8727 ArrayRef
<Expr
*> Args
;
8728 QualifiersAndAtomic VisibleTypeConversionsQuals
;
8729 bool HasArithmeticOrEnumeralCandidateType
;
8730 SmallVectorImpl
<BuiltinCandidateTypeSet
> &CandidateTypes
;
8731 OverloadCandidateSet
&CandidateSet
;
8733 static constexpr int ArithmeticTypesCap
= 24;
8734 SmallVector
<CanQualType
, ArithmeticTypesCap
> ArithmeticTypes
;
8736 // Define some indices used to iterate over the arithmetic types in
8737 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8738 // types are that preserved by promotion (C++ [over.built]p2).
8739 unsigned FirstIntegralType
,
8741 unsigned FirstPromotedIntegralType
,
8742 LastPromotedIntegralType
;
8743 unsigned FirstPromotedArithmeticType
,
8744 LastPromotedArithmeticType
;
8745 unsigned NumArithmeticTypes
;
8747 void InitArithmeticTypes() {
8748 // Start of promoted types.
8749 FirstPromotedArithmeticType
= 0;
8750 ArithmeticTypes
.push_back(S
.Context
.FloatTy
);
8751 ArithmeticTypes
.push_back(S
.Context
.DoubleTy
);
8752 ArithmeticTypes
.push_back(S
.Context
.LongDoubleTy
);
8753 if (S
.Context
.getTargetInfo().hasFloat128Type())
8754 ArithmeticTypes
.push_back(S
.Context
.Float128Ty
);
8755 if (S
.Context
.getTargetInfo().hasIbm128Type())
8756 ArithmeticTypes
.push_back(S
.Context
.Ibm128Ty
);
8758 // Start of integral types.
8759 FirstIntegralType
= ArithmeticTypes
.size();
8760 FirstPromotedIntegralType
= ArithmeticTypes
.size();
8761 ArithmeticTypes
.push_back(S
.Context
.IntTy
);
8762 ArithmeticTypes
.push_back(S
.Context
.LongTy
);
8763 ArithmeticTypes
.push_back(S
.Context
.LongLongTy
);
8764 if (S
.Context
.getTargetInfo().hasInt128Type() ||
8765 (S
.Context
.getAuxTargetInfo() &&
8766 S
.Context
.getAuxTargetInfo()->hasInt128Type()))
8767 ArithmeticTypes
.push_back(S
.Context
.Int128Ty
);
8768 ArithmeticTypes
.push_back(S
.Context
.UnsignedIntTy
);
8769 ArithmeticTypes
.push_back(S
.Context
.UnsignedLongTy
);
8770 ArithmeticTypes
.push_back(S
.Context
.UnsignedLongLongTy
);
8771 if (S
.Context
.getTargetInfo().hasInt128Type() ||
8772 (S
.Context
.getAuxTargetInfo() &&
8773 S
.Context
.getAuxTargetInfo()->hasInt128Type()))
8774 ArithmeticTypes
.push_back(S
.Context
.UnsignedInt128Ty
);
8775 LastPromotedIntegralType
= ArithmeticTypes
.size();
8776 LastPromotedArithmeticType
= ArithmeticTypes
.size();
8777 // End of promoted types.
8779 ArithmeticTypes
.push_back(S
.Context
.BoolTy
);
8780 ArithmeticTypes
.push_back(S
.Context
.CharTy
);
8781 ArithmeticTypes
.push_back(S
.Context
.WCharTy
);
8782 if (S
.Context
.getLangOpts().Char8
)
8783 ArithmeticTypes
.push_back(S
.Context
.Char8Ty
);
8784 ArithmeticTypes
.push_back(S
.Context
.Char16Ty
);
8785 ArithmeticTypes
.push_back(S
.Context
.Char32Ty
);
8786 ArithmeticTypes
.push_back(S
.Context
.SignedCharTy
);
8787 ArithmeticTypes
.push_back(S
.Context
.ShortTy
);
8788 ArithmeticTypes
.push_back(S
.Context
.UnsignedCharTy
);
8789 ArithmeticTypes
.push_back(S
.Context
.UnsignedShortTy
);
8790 LastIntegralType
= ArithmeticTypes
.size();
8791 NumArithmeticTypes
= ArithmeticTypes
.size();
8792 // End of integral types.
8793 // FIXME: What about complex? What about half?
8795 assert(ArithmeticTypes
.size() <= ArithmeticTypesCap
&&
8796 "Enough inline storage for all arithmetic types.");
8799 /// Helper method to factor out the common pattern of adding overloads
8800 /// for '++' and '--' builtin operators.
8801 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy
,
8804 QualType ParamTypes
[2] = {
8805 S
.Context
.getLValueReferenceType(CandidateTy
),
8809 // Non-volatile version.
8810 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
8812 // Use a heuristic to reduce number of builtin candidates in the set:
8813 // add volatile version only if there are conversions to a volatile type.
8816 S
.Context
.getLValueReferenceType(
8817 S
.Context
.getVolatileType(CandidateTy
));
8818 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
8821 // Add restrict version only if there are conversions to a restrict type
8822 // and our candidate type is a non-restrict-qualified pointer.
8823 if (HasRestrict
&& CandidateTy
->isAnyPointerType() &&
8824 !CandidateTy
.isRestrictQualified()) {
8826 = S
.Context
.getLValueReferenceType(
8827 S
.Context
.getCVRQualifiedType(CandidateTy
, Qualifiers::Restrict
));
8828 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
8832 = S
.Context
.getLValueReferenceType(
8833 S
.Context
.getCVRQualifiedType(CandidateTy
,
8834 (Qualifiers::Volatile
|
8835 Qualifiers::Restrict
)));
8836 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
8842 /// Helper to add an overload candidate for a binary builtin with types \p L
8844 void AddCandidate(QualType L
, QualType R
) {
8845 QualType LandR
[2] = {L
, R
};
8846 S
.AddBuiltinCandidate(LandR
, Args
, CandidateSet
);
8850 BuiltinOperatorOverloadBuilder(
8851 Sema
&S
, ArrayRef
<Expr
*> Args
,
8852 QualifiersAndAtomic VisibleTypeConversionsQuals
,
8853 bool HasArithmeticOrEnumeralCandidateType
,
8854 SmallVectorImpl
<BuiltinCandidateTypeSet
> &CandidateTypes
,
8855 OverloadCandidateSet
&CandidateSet
)
8857 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals
),
8858 HasArithmeticOrEnumeralCandidateType(
8859 HasArithmeticOrEnumeralCandidateType
),
8860 CandidateTypes(CandidateTypes
),
8861 CandidateSet(CandidateSet
) {
8863 InitArithmeticTypes();
8866 // Increment is deprecated for bool since C++17.
8868 // C++ [over.built]p3:
8870 // For every pair (T, VQ), where T is an arithmetic type other
8871 // than bool, and VQ is either volatile or empty, there exist
8872 // candidate operator functions of the form
8874 // VQ T& operator++(VQ T&);
8875 // T operator++(VQ T&, int);
8877 // C++ [over.built]p4:
8879 // For every pair (T, VQ), where T is an arithmetic type other
8880 // than bool, and VQ is either volatile or empty, there exist
8881 // candidate operator functions of the form
8883 // VQ T& operator--(VQ T&);
8884 // T operator--(VQ T&, int);
8885 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op
) {
8886 if (!HasArithmeticOrEnumeralCandidateType
)
8889 for (unsigned Arith
= 0; Arith
< NumArithmeticTypes
; ++Arith
) {
8890 const auto TypeOfT
= ArithmeticTypes
[Arith
];
8891 if (TypeOfT
== S
.Context
.BoolTy
) {
8892 if (Op
== OO_MinusMinus
)
8894 if (Op
== OO_PlusPlus
&& S
.getLangOpts().CPlusPlus17
)
8897 addPlusPlusMinusMinusStyleOverloads(
8899 VisibleTypeConversionsQuals
.hasVolatile(),
8900 VisibleTypeConversionsQuals
.hasRestrict());
8904 // C++ [over.built]p5:
8906 // For every pair (T, VQ), where T is a cv-qualified or
8907 // cv-unqualified object type, and VQ is either volatile or
8908 // empty, there exist candidate operator functions of the form
8910 // T*VQ& operator++(T*VQ&);
8911 // T*VQ& operator--(T*VQ&);
8912 // T* operator++(T*VQ&, int);
8913 // T* operator--(T*VQ&, int);
8914 void addPlusPlusMinusMinusPointerOverloads() {
8915 for (QualType PtrTy
: CandidateTypes
[0].pointer_types()) {
8916 // Skip pointer types that aren't pointers to object types.
8917 if (!PtrTy
->getPointeeType()->isObjectType())
8920 addPlusPlusMinusMinusStyleOverloads(
8922 (!PtrTy
.isVolatileQualified() &&
8923 VisibleTypeConversionsQuals
.hasVolatile()),
8924 (!PtrTy
.isRestrictQualified() &&
8925 VisibleTypeConversionsQuals
.hasRestrict()));
8929 // C++ [over.built]p6:
8930 // For every cv-qualified or cv-unqualified object type T, there
8931 // exist candidate operator functions of the form
8933 // T& operator*(T*);
8935 // C++ [over.built]p7:
8936 // For every function type T that does not have cv-qualifiers or a
8937 // ref-qualifier, there exist candidate operator functions of the form
8938 // T& operator*(T*);
8939 void addUnaryStarPointerOverloads() {
8940 for (QualType ParamTy
: CandidateTypes
[0].pointer_types()) {
8941 QualType PointeeTy
= ParamTy
->getPointeeType();
8942 if (!PointeeTy
->isObjectType() && !PointeeTy
->isFunctionType())
8945 if (const FunctionProtoType
*Proto
=PointeeTy
->getAs
<FunctionProtoType
>())
8946 if (Proto
->getMethodQuals() || Proto
->getRefQualifier())
8949 S
.AddBuiltinCandidate(&ParamTy
, Args
, CandidateSet
);
8953 // C++ [over.built]p9:
8954 // For every promoted arithmetic type T, there exist candidate
8955 // operator functions of the form
8959 void addUnaryPlusOrMinusArithmeticOverloads() {
8960 if (!HasArithmeticOrEnumeralCandidateType
)
8963 for (unsigned Arith
= FirstPromotedArithmeticType
;
8964 Arith
< LastPromotedArithmeticType
; ++Arith
) {
8965 QualType ArithTy
= ArithmeticTypes
[Arith
];
8966 S
.AddBuiltinCandidate(&ArithTy
, Args
, CandidateSet
);
8969 // Extension: We also add these operators for vector types.
8970 for (QualType VecTy
: CandidateTypes
[0].vector_types())
8971 S
.AddBuiltinCandidate(&VecTy
, Args
, CandidateSet
);
8974 // C++ [over.built]p8:
8975 // For every type T, there exist candidate operator functions of
8978 // T* operator+(T*);
8979 void addUnaryPlusPointerOverloads() {
8980 for (QualType ParamTy
: CandidateTypes
[0].pointer_types())
8981 S
.AddBuiltinCandidate(&ParamTy
, Args
, CandidateSet
);
8984 // C++ [over.built]p10:
8985 // For every promoted integral type T, there exist candidate
8986 // operator functions of the form
8989 void addUnaryTildePromotedIntegralOverloads() {
8990 if (!HasArithmeticOrEnumeralCandidateType
)
8993 for (unsigned Int
= FirstPromotedIntegralType
;
8994 Int
< LastPromotedIntegralType
; ++Int
) {
8995 QualType IntTy
= ArithmeticTypes
[Int
];
8996 S
.AddBuiltinCandidate(&IntTy
, Args
, CandidateSet
);
8999 // Extension: We also add this operator for vector types.
9000 for (QualType VecTy
: CandidateTypes
[0].vector_types())
9001 S
.AddBuiltinCandidate(&VecTy
, Args
, CandidateSet
);
9004 // C++ [over.match.oper]p16:
9005 // For every pointer to member type T or type std::nullptr_t, there
9006 // exist candidate operator functions of the form
9008 // bool operator==(T,T);
9009 // bool operator!=(T,T);
9010 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9011 /// Set of (canonical) types that we've already handled.
9012 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9014 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9015 for (QualType MemPtrTy
: CandidateTypes
[ArgIdx
].member_pointer_types()) {
9016 // Don't add the same builtin candidate twice.
9017 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(MemPtrTy
)).second
)
9020 QualType ParamTypes
[2] = {MemPtrTy
, MemPtrTy
};
9021 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9024 if (CandidateTypes
[ArgIdx
].hasNullPtrType()) {
9025 CanQualType NullPtrTy
= S
.Context
.getCanonicalType(S
.Context
.NullPtrTy
);
9026 if (AddedTypes
.insert(NullPtrTy
).second
) {
9027 QualType ParamTypes
[2] = { NullPtrTy
, NullPtrTy
};
9028 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9034 // C++ [over.built]p15:
9036 // For every T, where T is an enumeration type or a pointer type,
9037 // there exist candidate operator functions of the form
9039 // bool operator<(T, T);
9040 // bool operator>(T, T);
9041 // bool operator<=(T, T);
9042 // bool operator>=(T, T);
9043 // bool operator==(T, T);
9044 // bool operator!=(T, T);
9045 // R operator<=>(T, T)
9046 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship
) {
9047 // C++ [over.match.oper]p3:
9048 // [...]the built-in candidates include all of the candidate operator
9049 // functions defined in 13.6 that, compared to the given operator, [...]
9050 // do not have the same parameter-type-list as any non-template non-member
9053 // Note that in practice, this only affects enumeration types because there
9054 // aren't any built-in candidates of record type, and a user-defined operator
9055 // must have an operand of record or enumeration type. Also, the only other
9056 // overloaded operator with enumeration arguments, operator=,
9057 // cannot be overloaded for enumeration types, so this is the only place
9058 // where we must suppress candidates like this.
9059 llvm::DenseSet
<std::pair
<CanQualType
, CanQualType
> >
9060 UserDefinedBinaryOperators
;
9062 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9063 if (!CandidateTypes
[ArgIdx
].enumeration_types().empty()) {
9064 for (OverloadCandidateSet::iterator C
= CandidateSet
.begin(),
9065 CEnd
= CandidateSet
.end();
9067 if (!C
->Viable
|| !C
->Function
|| C
->Function
->getNumParams() != 2)
9070 if (C
->Function
->isFunctionTemplateSpecialization())
9073 // We interpret "same parameter-type-list" as applying to the
9074 // "synthesized candidate, with the order of the two parameters
9075 // reversed", not to the original function.
9076 bool Reversed
= C
->isReversed();
9077 QualType FirstParamType
= C
->Function
->getParamDecl(Reversed
? 1 : 0)
9079 .getUnqualifiedType();
9080 QualType SecondParamType
= C
->Function
->getParamDecl(Reversed
? 0 : 1)
9082 .getUnqualifiedType();
9084 // Skip if either parameter isn't of enumeral type.
9085 if (!FirstParamType
->isEnumeralType() ||
9086 !SecondParamType
->isEnumeralType())
9089 // Add this operator to the set of known user-defined operators.
9090 UserDefinedBinaryOperators
.insert(
9091 std::make_pair(S
.Context
.getCanonicalType(FirstParamType
),
9092 S
.Context
.getCanonicalType(SecondParamType
)));
9097 /// Set of (canonical) types that we've already handled.
9098 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9100 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9101 for (QualType PtrTy
: CandidateTypes
[ArgIdx
].pointer_types()) {
9102 // Don't add the same builtin candidate twice.
9103 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
)).second
)
9105 if (IsSpaceship
&& PtrTy
->isFunctionPointerType())
9108 QualType ParamTypes
[2] = {PtrTy
, PtrTy
};
9109 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9111 for (QualType EnumTy
: CandidateTypes
[ArgIdx
].enumeration_types()) {
9112 CanQualType CanonType
= S
.Context
.getCanonicalType(EnumTy
);
9114 // Don't add the same builtin candidate twice, or if a user defined
9115 // candidate exists.
9116 if (!AddedTypes
.insert(CanonType
).second
||
9117 UserDefinedBinaryOperators
.count(std::make_pair(CanonType
,
9120 QualType ParamTypes
[2] = {EnumTy
, EnumTy
};
9121 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9126 // C++ [over.built]p13:
9128 // For every cv-qualified or cv-unqualified object type T
9129 // there exist candidate operator functions of the form
9131 // T* operator+(T*, ptrdiff_t);
9132 // T& operator[](T*, ptrdiff_t); [BELOW]
9133 // T* operator-(T*, ptrdiff_t);
9134 // T* operator+(ptrdiff_t, T*);
9135 // T& operator[](ptrdiff_t, T*); [BELOW]
9137 // C++ [over.built]p14:
9139 // For every T, where T is a pointer to object type, there
9140 // exist candidate operator functions of the form
9142 // ptrdiff_t operator-(T, T);
9143 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op
) {
9144 /// Set of (canonical) types that we've already handled.
9145 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9147 for (int Arg
= 0; Arg
< 2; ++Arg
) {
9148 QualType AsymmetricParamTypes
[2] = {
9149 S
.Context
.getPointerDiffType(),
9150 S
.Context
.getPointerDiffType(),
9152 for (QualType PtrTy
: CandidateTypes
[Arg
].pointer_types()) {
9153 QualType PointeeTy
= PtrTy
->getPointeeType();
9154 if (!PointeeTy
->isObjectType())
9157 AsymmetricParamTypes
[Arg
] = PtrTy
;
9158 if (Arg
== 0 || Op
== OO_Plus
) {
9159 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9160 // T* operator+(ptrdiff_t, T*);
9161 S
.AddBuiltinCandidate(AsymmetricParamTypes
, Args
, CandidateSet
);
9163 if (Op
== OO_Minus
) {
9164 // ptrdiff_t operator-(T, T);
9165 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
)).second
)
9168 QualType ParamTypes
[2] = {PtrTy
, PtrTy
};
9169 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9175 // C++ [over.built]p12:
9177 // For every pair of promoted arithmetic types L and R, there
9178 // exist candidate operator functions of the form
9180 // LR operator*(L, R);
9181 // LR operator/(L, R);
9182 // LR operator+(L, R);
9183 // LR operator-(L, R);
9184 // bool operator<(L, R);
9185 // bool operator>(L, R);
9186 // bool operator<=(L, R);
9187 // bool operator>=(L, R);
9188 // bool operator==(L, R);
9189 // bool operator!=(L, R);
9191 // where LR is the result of the usual arithmetic conversions
9192 // between types L and R.
9194 // C++ [over.built]p24:
9196 // For every pair of promoted arithmetic types L and R, there exist
9197 // candidate operator functions of the form
9199 // LR operator?(bool, L, R);
9201 // where LR is the result of the usual arithmetic conversions
9202 // between types L and R.
9203 // Our candidates ignore the first parameter.
9204 void addGenericBinaryArithmeticOverloads() {
9205 if (!HasArithmeticOrEnumeralCandidateType
)
9208 for (unsigned Left
= FirstPromotedArithmeticType
;
9209 Left
< LastPromotedArithmeticType
; ++Left
) {
9210 for (unsigned Right
= FirstPromotedArithmeticType
;
9211 Right
< LastPromotedArithmeticType
; ++Right
) {
9212 QualType LandR
[2] = { ArithmeticTypes
[Left
],
9213 ArithmeticTypes
[Right
] };
9214 S
.AddBuiltinCandidate(LandR
, Args
, CandidateSet
);
9218 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9219 // conditional operator for vector types.
9220 for (QualType Vec1Ty
: CandidateTypes
[0].vector_types())
9221 for (QualType Vec2Ty
: CandidateTypes
[1].vector_types()) {
9222 QualType LandR
[2] = {Vec1Ty
, Vec2Ty
};
9223 S
.AddBuiltinCandidate(LandR
, Args
, CandidateSet
);
9227 /// Add binary operator overloads for each candidate matrix type M1, M2:
9228 /// * (M1, M1) -> M1
9229 /// * (M1, M1.getElementType()) -> M1
9230 /// * (M2.getElementType(), M2) -> M2
9231 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9232 void addMatrixBinaryArithmeticOverloads() {
9233 if (!HasArithmeticOrEnumeralCandidateType
)
9236 for (QualType M1
: CandidateTypes
[0].matrix_types()) {
9237 AddCandidate(M1
, cast
<MatrixType
>(M1
)->getElementType());
9238 AddCandidate(M1
, M1
);
9241 for (QualType M2
: CandidateTypes
[1].matrix_types()) {
9242 AddCandidate(cast
<MatrixType
>(M2
)->getElementType(), M2
);
9243 if (!CandidateTypes
[0].containsMatrixType(M2
))
9244 AddCandidate(M2
, M2
);
9248 // C++2a [over.built]p14:
9250 // For every integral type T there exists a candidate operator function
9253 // std::strong_ordering operator<=>(T, T)
9255 // C++2a [over.built]p15:
9257 // For every pair of floating-point types L and R, there exists a candidate
9258 // operator function of the form
9260 // std::partial_ordering operator<=>(L, R);
9262 // FIXME: The current specification for integral types doesn't play nice with
9263 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9264 // comparisons. Under the current spec this can lead to ambiguity during
9265 // overload resolution. For example:
9267 // enum A : int {a};
9268 // auto x = (a <=> (long)42);
9270 // error: call is ambiguous for arguments 'A' and 'long'.
9271 // note: candidate operator<=>(int, int)
9272 // note: candidate operator<=>(long, long)
9274 // To avoid this error, this function deviates from the specification and adds
9275 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9276 // arithmetic types (the same as the generic relational overloads).
9278 // For now this function acts as a placeholder.
9279 void addThreeWayArithmeticOverloads() {
9280 addGenericBinaryArithmeticOverloads();
9283 // C++ [over.built]p17:
9285 // For every pair of promoted integral types L and R, there
9286 // exist candidate operator functions of the form
9288 // LR operator%(L, R);
9289 // LR operator&(L, R);
9290 // LR operator^(L, R);
9291 // LR operator|(L, R);
9292 // L operator<<(L, R);
9293 // L operator>>(L, R);
9295 // where LR is the result of the usual arithmetic conversions
9296 // between types L and R.
9297 void addBinaryBitwiseArithmeticOverloads() {
9298 if (!HasArithmeticOrEnumeralCandidateType
)
9301 for (unsigned Left
= FirstPromotedIntegralType
;
9302 Left
< LastPromotedIntegralType
; ++Left
) {
9303 for (unsigned Right
= FirstPromotedIntegralType
;
9304 Right
< LastPromotedIntegralType
; ++Right
) {
9305 QualType LandR
[2] = { ArithmeticTypes
[Left
],
9306 ArithmeticTypes
[Right
] };
9307 S
.AddBuiltinCandidate(LandR
, Args
, CandidateSet
);
9312 // C++ [over.built]p20:
9314 // For every pair (T, VQ), where T is an enumeration or
9315 // pointer to member type and VQ is either volatile or
9316 // empty, there exist candidate operator functions of the form
9318 // VQ T& operator=(VQ T&, T);
9319 void addAssignmentMemberPointerOrEnumeralOverloads() {
9320 /// Set of (canonical) types that we've already handled.
9321 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9323 for (unsigned ArgIdx
= 0; ArgIdx
< 2; ++ArgIdx
) {
9324 for (QualType EnumTy
: CandidateTypes
[ArgIdx
].enumeration_types()) {
9325 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(EnumTy
)).second
)
9328 AddBuiltinAssignmentOperatorCandidates(S
, EnumTy
, Args
, CandidateSet
);
9331 for (QualType MemPtrTy
: CandidateTypes
[ArgIdx
].member_pointer_types()) {
9332 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(MemPtrTy
)).second
)
9335 AddBuiltinAssignmentOperatorCandidates(S
, MemPtrTy
, Args
, CandidateSet
);
9340 // C++ [over.built]p19:
9342 // For every pair (T, VQ), where T is any type and VQ is either
9343 // volatile or empty, there exist candidate operator functions
9346 // T*VQ& operator=(T*VQ&, T*);
9348 // C++ [over.built]p21:
9350 // For every pair (T, VQ), where T is a cv-qualified or
9351 // cv-unqualified object type and VQ is either volatile or
9352 // empty, there exist candidate operator functions of the form
9354 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9355 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9356 void addAssignmentPointerOverloads(bool isEqualOp
) {
9357 /// Set of (canonical) types that we've already handled.
9358 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9360 for (QualType PtrTy
: CandidateTypes
[0].pointer_types()) {
9361 // If this is operator=, keep track of the builtin candidates we added.
9363 AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
));
9364 else if (!PtrTy
->getPointeeType()->isObjectType())
9367 // non-volatile version
9368 QualType ParamTypes
[2] = {
9369 S
.Context
.getLValueReferenceType(PtrTy
),
9370 isEqualOp
? PtrTy
: S
.Context
.getPointerDiffType(),
9372 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9373 /*IsAssignmentOperator=*/ isEqualOp
);
9375 bool NeedVolatile
= !PtrTy
.isVolatileQualified() &&
9376 VisibleTypeConversionsQuals
.hasVolatile();
9380 S
.Context
.getLValueReferenceType(S
.Context
.getVolatileType(PtrTy
));
9381 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9382 /*IsAssignmentOperator=*/isEqualOp
);
9385 if (!PtrTy
.isRestrictQualified() &&
9386 VisibleTypeConversionsQuals
.hasRestrict()) {
9389 S
.Context
.getLValueReferenceType(S
.Context
.getRestrictType(PtrTy
));
9390 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9391 /*IsAssignmentOperator=*/isEqualOp
);
9394 // volatile restrict version
9396 S
.Context
.getLValueReferenceType(S
.Context
.getCVRQualifiedType(
9397 PtrTy
, (Qualifiers::Volatile
| Qualifiers::Restrict
)));
9398 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9399 /*IsAssignmentOperator=*/isEqualOp
);
9405 for (QualType PtrTy
: CandidateTypes
[1].pointer_types()) {
9406 // Make sure we don't add the same candidate twice.
9407 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
)).second
)
9410 QualType ParamTypes
[2] = {
9411 S
.Context
.getLValueReferenceType(PtrTy
),
9415 // non-volatile version
9416 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9417 /*IsAssignmentOperator=*/true);
9419 bool NeedVolatile
= !PtrTy
.isVolatileQualified() &&
9420 VisibleTypeConversionsQuals
.hasVolatile();
9423 ParamTypes
[0] = S
.Context
.getLValueReferenceType(
9424 S
.Context
.getVolatileType(PtrTy
));
9425 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9426 /*IsAssignmentOperator=*/true);
9429 if (!PtrTy
.isRestrictQualified() &&
9430 VisibleTypeConversionsQuals
.hasRestrict()) {
9432 ParamTypes
[0] = S
.Context
.getLValueReferenceType(
9433 S
.Context
.getRestrictType(PtrTy
));
9434 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9435 /*IsAssignmentOperator=*/true);
9438 // volatile restrict version
9440 S
.Context
.getLValueReferenceType(S
.Context
.getCVRQualifiedType(
9441 PtrTy
, (Qualifiers::Volatile
| Qualifiers::Restrict
)));
9442 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9443 /*IsAssignmentOperator=*/true);
9450 // C++ [over.built]p18:
9452 // For every triple (L, VQ, R), where L is an arithmetic type,
9453 // VQ is either volatile or empty, and R is a promoted
9454 // arithmetic type, there exist candidate operator functions of
9457 // VQ L& operator=(VQ L&, R);
9458 // VQ L& operator*=(VQ L&, R);
9459 // VQ L& operator/=(VQ L&, R);
9460 // VQ L& operator+=(VQ L&, R);
9461 // VQ L& operator-=(VQ L&, R);
9462 void addAssignmentArithmeticOverloads(bool isEqualOp
) {
9463 if (!HasArithmeticOrEnumeralCandidateType
)
9466 for (unsigned Left
= 0; Left
< NumArithmeticTypes
; ++Left
) {
9467 for (unsigned Right
= FirstPromotedArithmeticType
;
9468 Right
< LastPromotedArithmeticType
; ++Right
) {
9469 QualType ParamTypes
[2];
9470 ParamTypes
[1] = ArithmeticTypes
[Right
];
9471 auto LeftBaseTy
= AdjustAddressSpaceForBuiltinOperandType(
9472 S
, ArithmeticTypes
[Left
], Args
[0]);
9474 forAllQualifierCombinations(
9475 VisibleTypeConversionsQuals
, [&](QualifiersAndAtomic Quals
) {
9477 makeQualifiedLValueReferenceType(LeftBaseTy
, Quals
, S
);
9478 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9479 /*IsAssignmentOperator=*/isEqualOp
);
9484 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9485 for (QualType Vec1Ty
: CandidateTypes
[0].vector_types())
9486 for (QualType Vec2Ty
: CandidateTypes
[0].vector_types()) {
9487 QualType ParamTypes
[2];
9488 ParamTypes
[1] = Vec2Ty
;
9489 // Add this built-in operator as a candidate (VQ is empty).
9490 ParamTypes
[0] = S
.Context
.getLValueReferenceType(Vec1Ty
);
9491 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9492 /*IsAssignmentOperator=*/isEqualOp
);
9494 // Add this built-in operator as a candidate (VQ is 'volatile').
9495 if (VisibleTypeConversionsQuals
.hasVolatile()) {
9496 ParamTypes
[0] = S
.Context
.getVolatileType(Vec1Ty
);
9497 ParamTypes
[0] = S
.Context
.getLValueReferenceType(ParamTypes
[0]);
9498 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9499 /*IsAssignmentOperator=*/isEqualOp
);
9504 // C++ [over.built]p22:
9506 // For every triple (L, VQ, R), where L is an integral type, VQ
9507 // is either volatile or empty, and R is a promoted integral
9508 // type, there exist candidate operator functions of the form
9510 // VQ L& operator%=(VQ L&, R);
9511 // VQ L& operator<<=(VQ L&, R);
9512 // VQ L& operator>>=(VQ L&, R);
9513 // VQ L& operator&=(VQ L&, R);
9514 // VQ L& operator^=(VQ L&, R);
9515 // VQ L& operator|=(VQ L&, R);
9516 void addAssignmentIntegralOverloads() {
9517 if (!HasArithmeticOrEnumeralCandidateType
)
9520 for (unsigned Left
= FirstIntegralType
; Left
< LastIntegralType
; ++Left
) {
9521 for (unsigned Right
= FirstPromotedIntegralType
;
9522 Right
< LastPromotedIntegralType
; ++Right
) {
9523 QualType ParamTypes
[2];
9524 ParamTypes
[1] = ArithmeticTypes
[Right
];
9525 auto LeftBaseTy
= AdjustAddressSpaceForBuiltinOperandType(
9526 S
, ArithmeticTypes
[Left
], Args
[0]);
9528 forAllQualifierCombinations(
9529 VisibleTypeConversionsQuals
, [&](QualifiersAndAtomic Quals
) {
9531 makeQualifiedLValueReferenceType(LeftBaseTy
, Quals
, S
);
9532 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9538 // C++ [over.operator]p23:
9540 // There also exist candidate operator functions of the form
9542 // bool operator!(bool);
9543 // bool operator&&(bool, bool);
9544 // bool operator||(bool, bool);
9545 void addExclaimOverload() {
9546 QualType ParamTy
= S
.Context
.BoolTy
;
9547 S
.AddBuiltinCandidate(&ParamTy
, Args
, CandidateSet
,
9548 /*IsAssignmentOperator=*/false,
9549 /*NumContextualBoolArguments=*/1);
9551 void addAmpAmpOrPipePipeOverload() {
9552 QualType ParamTypes
[2] = { S
.Context
.BoolTy
, S
.Context
.BoolTy
};
9553 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9554 /*IsAssignmentOperator=*/false,
9555 /*NumContextualBoolArguments=*/2);
9558 // C++ [over.built]p13:
9560 // For every cv-qualified or cv-unqualified object type T there
9561 // exist candidate operator functions of the form
9563 // T* operator+(T*, ptrdiff_t); [ABOVE]
9564 // T& operator[](T*, ptrdiff_t);
9565 // T* operator-(T*, ptrdiff_t); [ABOVE]
9566 // T* operator+(ptrdiff_t, T*); [ABOVE]
9567 // T& operator[](ptrdiff_t, T*);
9568 void addSubscriptOverloads() {
9569 for (QualType PtrTy
: CandidateTypes
[0].pointer_types()) {
9570 QualType ParamTypes
[2] = {PtrTy
, S
.Context
.getPointerDiffType()};
9571 QualType PointeeType
= PtrTy
->getPointeeType();
9572 if (!PointeeType
->isObjectType())
9575 // T& operator[](T*, ptrdiff_t)
9576 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9579 for (QualType PtrTy
: CandidateTypes
[1].pointer_types()) {
9580 QualType ParamTypes
[2] = {S
.Context
.getPointerDiffType(), PtrTy
};
9581 QualType PointeeType
= PtrTy
->getPointeeType();
9582 if (!PointeeType
->isObjectType())
9585 // T& operator[](ptrdiff_t, T*)
9586 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9590 // C++ [over.built]p11:
9591 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9592 // C1 is the same type as C2 or is a derived class of C2, T is an object
9593 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9594 // there exist candidate operator functions of the form
9596 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9598 // where CV12 is the union of CV1 and CV2.
9599 void addArrowStarOverloads() {
9600 for (QualType PtrTy
: CandidateTypes
[0].pointer_types()) {
9601 QualType C1Ty
= PtrTy
;
9603 QualifierCollector Q1
;
9604 C1
= QualType(Q1
.strip(C1Ty
->getPointeeType()), 0);
9605 if (!isa
<RecordType
>(C1
))
9607 // heuristic to reduce number of builtin candidates in the set.
9608 // Add volatile/restrict version only if there are conversions to a
9609 // volatile/restrict type.
9610 if (!VisibleTypeConversionsQuals
.hasVolatile() && Q1
.hasVolatile())
9612 if (!VisibleTypeConversionsQuals
.hasRestrict() && Q1
.hasRestrict())
9614 for (QualType MemPtrTy
: CandidateTypes
[1].member_pointer_types()) {
9615 const MemberPointerType
*mptr
= cast
<MemberPointerType
>(MemPtrTy
);
9616 QualType C2
= QualType(mptr
->getClass(), 0);
9617 C2
= C2
.getUnqualifiedType();
9618 if (C1
!= C2
&& !S
.IsDerivedFrom(CandidateSet
.getLocation(), C1
, C2
))
9620 QualType ParamTypes
[2] = {PtrTy
, MemPtrTy
};
9622 QualType T
= mptr
->getPointeeType();
9623 if (!VisibleTypeConversionsQuals
.hasVolatile() &&
9624 T
.isVolatileQualified())
9626 if (!VisibleTypeConversionsQuals
.hasRestrict() &&
9627 T
.isRestrictQualified())
9629 T
= Q1
.apply(S
.Context
, T
);
9630 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9635 // Note that we don't consider the first argument, since it has been
9636 // contextually converted to bool long ago. The candidates below are
9637 // therefore added as binary.
9639 // C++ [over.built]p25:
9640 // For every type T, where T is a pointer, pointer-to-member, or scoped
9641 // enumeration type, there exist candidate operator functions of the form
9643 // T operator?(bool, T, T);
9645 void addConditionalOperatorOverloads() {
9646 /// Set of (canonical) types that we've already handled.
9647 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9649 for (unsigned ArgIdx
= 0; ArgIdx
< 2; ++ArgIdx
) {
9650 for (QualType PtrTy
: CandidateTypes
[ArgIdx
].pointer_types()) {
9651 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
)).second
)
9654 QualType ParamTypes
[2] = {PtrTy
, PtrTy
};
9655 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9658 for (QualType MemPtrTy
: CandidateTypes
[ArgIdx
].member_pointer_types()) {
9659 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(MemPtrTy
)).second
)
9662 QualType ParamTypes
[2] = {MemPtrTy
, MemPtrTy
};
9663 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9666 if (S
.getLangOpts().CPlusPlus11
) {
9667 for (QualType EnumTy
: CandidateTypes
[ArgIdx
].enumeration_types()) {
9668 if (!EnumTy
->castAs
<EnumType
>()->getDecl()->isScoped())
9671 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(EnumTy
)).second
)
9674 QualType ParamTypes
[2] = {EnumTy
, EnumTy
};
9675 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9682 } // end anonymous namespace
9684 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9685 /// operator overloads to the candidate set (C++ [over.built]), based
9686 /// on the operator @p Op and the arguments given. For example, if the
9687 /// operator is a binary '+', this routine might add "int
9688 /// operator+(int, int)" to cover integer addition.
9689 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op
,
9690 SourceLocation OpLoc
,
9691 ArrayRef
<Expr
*> Args
,
9692 OverloadCandidateSet
&CandidateSet
) {
9693 // Find all of the types that the arguments can convert to, but only
9694 // if the operator we're looking at has built-in operator candidates
9695 // that make use of these types. Also record whether we encounter non-record
9696 // candidate types or either arithmetic or enumeral candidate types.
9697 QualifiersAndAtomic VisibleTypeConversionsQuals
;
9698 VisibleTypeConversionsQuals
.addConst();
9699 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9700 VisibleTypeConversionsQuals
+= CollectVRQualifiers(Context
, Args
[ArgIdx
]);
9701 if (Args
[ArgIdx
]->getType()->isAtomicType())
9702 VisibleTypeConversionsQuals
.addAtomic();
9705 bool HasNonRecordCandidateType
= false;
9706 bool HasArithmeticOrEnumeralCandidateType
= false;
9707 SmallVector
<BuiltinCandidateTypeSet
, 2> CandidateTypes
;
9708 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9709 CandidateTypes
.emplace_back(*this);
9710 CandidateTypes
[ArgIdx
].AddTypesConvertedFrom(Args
[ArgIdx
]->getType(),
9713 (Op
== OO_Exclaim
||
9716 VisibleTypeConversionsQuals
);
9717 HasNonRecordCandidateType
= HasNonRecordCandidateType
||
9718 CandidateTypes
[ArgIdx
].hasNonRecordTypes();
9719 HasArithmeticOrEnumeralCandidateType
=
9720 HasArithmeticOrEnumeralCandidateType
||
9721 CandidateTypes
[ArgIdx
].hasArithmeticOrEnumeralTypes();
9724 // Exit early when no non-record types have been added to the candidate set
9725 // for any of the arguments to the operator.
9727 // We can't exit early for !, ||, or &&, since there we have always have
9728 // 'bool' overloads.
9729 if (!HasNonRecordCandidateType
&&
9730 !(Op
== OO_Exclaim
|| Op
== OO_AmpAmp
|| Op
== OO_PipePipe
))
9733 // Setup an object to manage the common state for building overloads.
9734 BuiltinOperatorOverloadBuilder
OpBuilder(*this, Args
,
9735 VisibleTypeConversionsQuals
,
9736 HasArithmeticOrEnumeralCandidateType
,
9737 CandidateTypes
, CandidateSet
);
9739 // Dispatch over the operation to add in only those overloads which apply.
9742 case NUM_OVERLOADED_OPERATORS
:
9743 llvm_unreachable("Expected an overloaded operator");
9748 case OO_Array_Delete
:
9751 "Special operators don't use AddBuiltinOperatorCandidates");
9756 // C++ [over.match.oper]p3:
9757 // -- For the operator ',', the unary operator '&', the
9758 // operator '->', or the operator 'co_await', the
9759 // built-in candidates set is empty.
9762 case OO_Plus
: // '+' is either unary or binary
9763 if (Args
.size() == 1)
9764 OpBuilder
.addUnaryPlusPointerOverloads();
9767 case OO_Minus
: // '-' is either unary or binary
9768 if (Args
.size() == 1) {
9769 OpBuilder
.addUnaryPlusOrMinusArithmeticOverloads();
9771 OpBuilder
.addBinaryPlusOrMinusPointerOverloads(Op
);
9772 OpBuilder
.addGenericBinaryArithmeticOverloads();
9773 OpBuilder
.addMatrixBinaryArithmeticOverloads();
9777 case OO_Star
: // '*' is either unary or binary
9778 if (Args
.size() == 1)
9779 OpBuilder
.addUnaryStarPointerOverloads();
9781 OpBuilder
.addGenericBinaryArithmeticOverloads();
9782 OpBuilder
.addMatrixBinaryArithmeticOverloads();
9787 OpBuilder
.addGenericBinaryArithmeticOverloads();
9792 OpBuilder
.addPlusPlusMinusMinusArithmeticOverloads(Op
);
9793 OpBuilder
.addPlusPlusMinusMinusPointerOverloads();
9797 case OO_ExclaimEqual
:
9798 OpBuilder
.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9799 OpBuilder
.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9800 OpBuilder
.addGenericBinaryArithmeticOverloads();
9806 case OO_GreaterEqual
:
9807 OpBuilder
.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9808 OpBuilder
.addGenericBinaryArithmeticOverloads();
9812 OpBuilder
.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9813 OpBuilder
.addThreeWayArithmeticOverloads();
9820 case OO_GreaterGreater
:
9821 OpBuilder
.addBinaryBitwiseArithmeticOverloads();
9824 case OO_Amp
: // '&' is either unary or binary
9825 if (Args
.size() == 1)
9826 // C++ [over.match.oper]p3:
9827 // -- For the operator ',', the unary operator '&', or the
9828 // operator '->', the built-in candidates set is empty.
9831 OpBuilder
.addBinaryBitwiseArithmeticOverloads();
9835 OpBuilder
.addUnaryTildePromotedIntegralOverloads();
9839 OpBuilder
.addAssignmentMemberPointerOrEnumeralOverloads();
9844 OpBuilder
.addAssignmentPointerOverloads(Op
== OO_Equal
);
9849 OpBuilder
.addAssignmentArithmeticOverloads(Op
== OO_Equal
);
9852 case OO_PercentEqual
:
9853 case OO_LessLessEqual
:
9854 case OO_GreaterGreaterEqual
:
9858 OpBuilder
.addAssignmentIntegralOverloads();
9862 OpBuilder
.addExclaimOverload();
9867 OpBuilder
.addAmpAmpOrPipePipeOverload();
9871 if (Args
.size() == 2)
9872 OpBuilder
.addSubscriptOverloads();
9876 OpBuilder
.addArrowStarOverloads();
9879 case OO_Conditional
:
9880 OpBuilder
.addConditionalOperatorOverloads();
9881 OpBuilder
.addGenericBinaryArithmeticOverloads();
9886 /// Add function candidates found via argument-dependent lookup
9887 /// to the set of overloading candidates.
9889 /// This routine performs argument-dependent name lookup based on the
9890 /// given function name (which may also be an operator name) and adds
9891 /// all of the overload candidates found by ADL to the overload
9892 /// candidate set (C++ [basic.lookup.argdep]).
9894 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name
,
9896 ArrayRef
<Expr
*> Args
,
9897 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
9898 OverloadCandidateSet
& CandidateSet
,
9899 bool PartialOverloading
) {
9902 // FIXME: This approach for uniquing ADL results (and removing
9903 // redundant candidates from the set) relies on pointer-equality,
9904 // which means we need to key off the canonical decl. However,
9905 // always going back to the canonical decl might not get us the
9906 // right set of default arguments. What default arguments are
9907 // we supposed to consider on ADL candidates, anyway?
9909 // FIXME: Pass in the explicit template arguments?
9910 ArgumentDependentLookup(Name
, Loc
, Args
, Fns
);
9912 // Erase all of the candidates we already knew about.
9913 for (OverloadCandidateSet::iterator Cand
= CandidateSet
.begin(),
9914 CandEnd
= CandidateSet
.end();
9915 Cand
!= CandEnd
; ++Cand
)
9916 if (Cand
->Function
) {
9917 Fns
.erase(Cand
->Function
);
9918 if (FunctionTemplateDecl
*FunTmpl
= Cand
->Function
->getPrimaryTemplate())
9922 // For each of the ADL candidates we found, add it to the overload
9924 for (ADLResult::iterator I
= Fns
.begin(), E
= Fns
.end(); I
!= E
; ++I
) {
9925 DeclAccessPair FoundDecl
= DeclAccessPair::make(*I
, AS_none
);
9927 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*I
)) {
9928 if (ExplicitTemplateArgs
)
9931 AddOverloadCandidate(
9932 FD
, FoundDecl
, Args
, CandidateSet
, /*SuppressUserConversions=*/false,
9933 PartialOverloading
, /*AllowExplicit=*/true,
9934 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL
);
9935 if (CandidateSet
.getRewriteInfo().shouldAddReversed(*this, Args
, FD
)) {
9936 AddOverloadCandidate(
9937 FD
, FoundDecl
, {Args
[1], Args
[0]}, CandidateSet
,
9938 /*SuppressUserConversions=*/false, PartialOverloading
,
9939 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9940 ADLCallKind::UsesADL
, std::nullopt
,
9941 OverloadCandidateParamOrder::Reversed
);
9944 auto *FTD
= cast
<FunctionTemplateDecl
>(*I
);
9945 AddTemplateOverloadCandidate(
9946 FTD
, FoundDecl
, ExplicitTemplateArgs
, Args
, CandidateSet
,
9947 /*SuppressUserConversions=*/false, PartialOverloading
,
9948 /*AllowExplicit=*/true, ADLCallKind::UsesADL
);
9949 if (CandidateSet
.getRewriteInfo().shouldAddReversed(
9950 *this, Args
, FTD
->getTemplatedDecl())) {
9951 AddTemplateOverloadCandidate(
9952 FTD
, FoundDecl
, ExplicitTemplateArgs
, {Args
[1], Args
[0]},
9953 CandidateSet
, /*SuppressUserConversions=*/false, PartialOverloading
,
9954 /*AllowExplicit=*/true, ADLCallKind::UsesADL
,
9955 OverloadCandidateParamOrder::Reversed
);
9962 enum class Comparison
{ Equal
, Better
, Worse
};
9965 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9966 /// overload resolution.
9968 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9969 /// Cand1's first N enable_if attributes have precisely the same conditions as
9970 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9971 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9973 /// Note that you can have a pair of candidates such that Cand1's enable_if
9974 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9975 /// worse than Cand1's.
9976 static Comparison
compareEnableIfAttrs(const Sema
&S
, const FunctionDecl
*Cand1
,
9977 const FunctionDecl
*Cand2
) {
9978 // Common case: One (or both) decls don't have enable_if attrs.
9979 bool Cand1Attr
= Cand1
->hasAttr
<EnableIfAttr
>();
9980 bool Cand2Attr
= Cand2
->hasAttr
<EnableIfAttr
>();
9981 if (!Cand1Attr
|| !Cand2Attr
) {
9982 if (Cand1Attr
== Cand2Attr
)
9983 return Comparison::Equal
;
9984 return Cand1Attr
? Comparison::Better
: Comparison::Worse
;
9987 auto Cand1Attrs
= Cand1
->specific_attrs
<EnableIfAttr
>();
9988 auto Cand2Attrs
= Cand2
->specific_attrs
<EnableIfAttr
>();
9990 llvm::FoldingSetNodeID Cand1ID
, Cand2ID
;
9991 for (auto Pair
: zip_longest(Cand1Attrs
, Cand2Attrs
)) {
9992 std::optional
<EnableIfAttr
*> Cand1A
= std::get
<0>(Pair
);
9993 std::optional
<EnableIfAttr
*> Cand2A
= std::get
<1>(Pair
);
9995 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9996 // has fewer enable_if attributes than Cand2, and vice versa.
9998 return Comparison::Worse
;
10000 return Comparison::Better
;
10005 (*Cand1A
)->getCond()->Profile(Cand1ID
, S
.getASTContext(), true);
10006 (*Cand2A
)->getCond()->Profile(Cand2ID
, S
.getASTContext(), true);
10007 if (Cand1ID
!= Cand2ID
)
10008 return Comparison::Worse
;
10011 return Comparison::Equal
;
10015 isBetterMultiversionCandidate(const OverloadCandidate
&Cand1
,
10016 const OverloadCandidate
&Cand2
) {
10017 if (!Cand1
.Function
|| !Cand1
.Function
->isMultiVersion() || !Cand2
.Function
||
10018 !Cand2
.Function
->isMultiVersion())
10019 return Comparison::Equal
;
10021 // If both are invalid, they are equal. If one of them is invalid, the other
10023 if (Cand1
.Function
->isInvalidDecl()) {
10024 if (Cand2
.Function
->isInvalidDecl())
10025 return Comparison::Equal
;
10026 return Comparison::Worse
;
10028 if (Cand2
.Function
->isInvalidDecl())
10029 return Comparison::Better
;
10031 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10032 // cpu_dispatch, else arbitrarily based on the identifiers.
10033 bool Cand1CPUDisp
= Cand1
.Function
->hasAttr
<CPUDispatchAttr
>();
10034 bool Cand2CPUDisp
= Cand2
.Function
->hasAttr
<CPUDispatchAttr
>();
10035 const auto *Cand1CPUSpec
= Cand1
.Function
->getAttr
<CPUSpecificAttr
>();
10036 const auto *Cand2CPUSpec
= Cand2
.Function
->getAttr
<CPUSpecificAttr
>();
10038 if (!Cand1CPUDisp
&& !Cand2CPUDisp
&& !Cand1CPUSpec
&& !Cand2CPUSpec
)
10039 return Comparison::Equal
;
10041 if (Cand1CPUDisp
&& !Cand2CPUDisp
)
10042 return Comparison::Better
;
10043 if (Cand2CPUDisp
&& !Cand1CPUDisp
)
10044 return Comparison::Worse
;
10046 if (Cand1CPUSpec
&& Cand2CPUSpec
) {
10047 if (Cand1CPUSpec
->cpus_size() != Cand2CPUSpec
->cpus_size())
10048 return Cand1CPUSpec
->cpus_size() < Cand2CPUSpec
->cpus_size()
10049 ? Comparison::Better
10050 : Comparison::Worse
;
10052 std::pair
<CPUSpecificAttr::cpus_iterator
, CPUSpecificAttr::cpus_iterator
>
10053 FirstDiff
= std::mismatch(
10054 Cand1CPUSpec
->cpus_begin(), Cand1CPUSpec
->cpus_end(),
10055 Cand2CPUSpec
->cpus_begin(),
10056 [](const IdentifierInfo
*LHS
, const IdentifierInfo
*RHS
) {
10057 return LHS
->getName() == RHS
->getName();
10060 assert(FirstDiff
.first
!= Cand1CPUSpec
->cpus_end() &&
10061 "Two different cpu-specific versions should not have the same "
10062 "identifier list, otherwise they'd be the same decl!");
10063 return (*FirstDiff
.first
)->getName() < (*FirstDiff
.second
)->getName()
10064 ? Comparison::Better
10065 : Comparison::Worse
;
10067 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10070 /// Compute the type of the implicit object parameter for the given function,
10071 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
10072 /// null QualType if there is a 'matches anything' implicit object parameter.
10073 static std::optional
<QualType
>
10074 getImplicitObjectParamType(ASTContext
&Context
, const FunctionDecl
*F
) {
10075 if (!isa
<CXXMethodDecl
>(F
) || isa
<CXXConstructorDecl
>(F
))
10076 return std::nullopt
;
10078 auto *M
= cast
<CXXMethodDecl
>(F
);
10079 // Static member functions' object parameters match all types.
10082 return M
->getFunctionObjectParameterReferenceType();
10085 static bool haveSameParameterTypes(ASTContext
&Context
, const FunctionDecl
*F1
,
10086 const FunctionDecl
*F2
) {
10087 if (declaresSameEntity(F1
, F2
))
10090 auto NextParam
= [&](const FunctionDecl
*F
, unsigned &I
, bool First
) {
10092 if (std::optional
<QualType
> T
= getImplicitObjectParamType(Context
, F
))
10095 assert(I
< F
->getNumParams());
10096 return F
->getParamDecl(I
++)->getType();
10099 unsigned F1NumParams
= F1
->getNumParams() + isa
<CXXMethodDecl
>(F1
);
10100 unsigned F2NumParams
= F2
->getNumParams() + isa
<CXXMethodDecl
>(F2
);
10102 if (F1NumParams
!= F2NumParams
)
10105 unsigned I1
= 0, I2
= 0;
10106 for (unsigned I
= 0; I
!= F1NumParams
; ++I
) {
10107 QualType T1
= NextParam(F1
, I1
, I
== 0);
10108 QualType T2
= NextParam(F2
, I2
, I
== 0);
10109 assert(!T1
.isNull() && !T2
.isNull() && "Unexpected null param types");
10110 if (!Context
.hasSameUnqualifiedType(T1
, T2
))
10116 /// We're allowed to use constraints partial ordering only if the candidates
10117 /// have the same parameter types:
10118 /// [over.match.best]p2.6
10119 /// F1 and F2 are non-template functions with the same parameter-type-lists,
10120 /// and F1 is more constrained than F2 [...]
10121 static bool sameFunctionParameterTypeLists(Sema
&S
,
10122 const OverloadCandidate
&Cand1
,
10123 const OverloadCandidate
&Cand2
) {
10124 if (Cand1
.Function
&& Cand2
.Function
) {
10125 auto *PT1
= cast
<FunctionProtoType
>(Cand1
.Function
->getFunctionType());
10126 auto *PT2
= cast
<FunctionProtoType
>(Cand2
.Function
->getFunctionType());
10127 if (PT1
->getNumParams() == PT2
->getNumParams() &&
10128 PT1
->isVariadic() == PT2
->isVariadic() &&
10129 S
.FunctionParamTypesAreEqual(PT1
, PT2
, nullptr,
10130 Cand1
.isReversed() ^ Cand2
.isReversed()))
10136 /// isBetterOverloadCandidate - Determines whether the first overload
10137 /// candidate is a better candidate than the second (C++ 13.3.3p1).
10138 bool clang::isBetterOverloadCandidate(
10139 Sema
&S
, const OverloadCandidate
&Cand1
, const OverloadCandidate
&Cand2
,
10140 SourceLocation Loc
, OverloadCandidateSet::CandidateSetKind Kind
) {
10141 // Define viable functions to be better candidates than non-viable
10144 return Cand1
.Viable
;
10145 else if (!Cand1
.Viable
)
10148 // [CUDA] A function with 'never' preference is marked not viable, therefore
10149 // is never shown up here. The worst preference shown up here is 'wrong side',
10150 // e.g. an H function called by a HD function in device compilation. This is
10151 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10152 // function which is called only by an H function. A deferred diagnostic will
10153 // be triggered if it is emitted. However a wrong-sided function is still
10154 // a viable candidate here.
10156 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10157 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10158 // can be emitted, Cand1 is not better than Cand2. This rule should have
10159 // precedence over other rules.
10161 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10162 // other rules should be used to determine which is better. This is because
10163 // host/device based overloading resolution is mostly for determining
10164 // viability of a function. If two functions are both viable, other factors
10165 // should take precedence in preference, e.g. the standard-defined preferences
10166 // like argument conversion ranks or enable_if partial-ordering. The
10167 // preference for pass-object-size parameters is probably most similar to a
10168 // type-based-overloading decision and so should take priority.
10170 // If other rules cannot determine which is better, CUDA preference will be
10171 // used again to determine which is better.
10173 // TODO: Currently IdentifyCUDAPreference does not return correct values
10174 // for functions called in global variable initializers due to missing
10175 // correct context about device/host. Therefore we can only enforce this
10176 // rule when there is a caller. We should enforce this rule for functions
10177 // in global variable initializers once proper context is added.
10179 // TODO: We can only enable the hostness based overloading resolution when
10180 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10181 // overloading resolution diagnostics.
10182 if (S
.getLangOpts().CUDA
&& Cand1
.Function
&& Cand2
.Function
&&
10183 S
.getLangOpts().GPUExcludeWrongSideOverloads
) {
10184 if (FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true)) {
10185 bool IsCallerImplicitHD
= Sema::isCUDAImplicitHostDeviceFunction(Caller
);
10186 bool IsCand1ImplicitHD
=
10187 Sema::isCUDAImplicitHostDeviceFunction(Cand1
.Function
);
10188 bool IsCand2ImplicitHD
=
10189 Sema::isCUDAImplicitHostDeviceFunction(Cand2
.Function
);
10190 auto P1
= S
.IdentifyCUDAPreference(Caller
, Cand1
.Function
);
10191 auto P2
= S
.IdentifyCUDAPreference(Caller
, Cand2
.Function
);
10192 assert(P1
!= Sema::CFP_Never
&& P2
!= Sema::CFP_Never
);
10193 // The implicit HD function may be a function in a system header which
10194 // is forced by pragma. In device compilation, if we prefer HD candidates
10195 // over wrong-sided candidates, overloading resolution may change, which
10196 // may result in non-deferrable diagnostics. As a workaround, we let
10197 // implicit HD candidates take equal preference as wrong-sided candidates.
10198 // This will preserve the overloading resolution.
10199 // TODO: We still need special handling of implicit HD functions since
10200 // they may incur other diagnostics to be deferred. We should make all
10201 // host/device related diagnostics deferrable and remove special handling
10202 // of implicit HD functions.
10203 auto EmitThreshold
=
10204 (S
.getLangOpts().CUDAIsDevice
&& IsCallerImplicitHD
&&
10205 (IsCand1ImplicitHD
|| IsCand2ImplicitHD
))
10207 : Sema::CFP_WrongSide
;
10208 auto Cand1Emittable
= P1
> EmitThreshold
;
10209 auto Cand2Emittable
= P2
> EmitThreshold
;
10210 if (Cand1Emittable
&& !Cand2Emittable
)
10212 if (!Cand1Emittable
&& Cand2Emittable
)
10217 // C++ [over.match.best]p1: (Changed in C++23)
10219 // -- if F is a static member function, ICS1(F) is defined such
10220 // that ICS1(F) is neither better nor worse than ICS1(G) for
10221 // any function G, and, symmetrically, ICS1(G) is neither
10222 // better nor worse than ICS1(F).
10223 unsigned StartArg
= 0;
10224 if (Cand1
.IgnoreObjectArgument
|| Cand2
.IgnoreObjectArgument
)
10227 auto IsIllFormedConversion
= [&](const ImplicitConversionSequence
&ICS
) {
10228 // We don't allow incompatible pointer conversions in C++.
10229 if (!S
.getLangOpts().CPlusPlus
)
10230 return ICS
.isStandard() &&
10231 ICS
.Standard
.Second
== ICK_Incompatible_Pointer_Conversion
;
10233 // The only ill-formed conversion we allow in C++ is the string literal to
10234 // char* conversion, which is only considered ill-formed after C++11.
10235 return S
.getLangOpts().CPlusPlus11
&& !S
.getLangOpts().WritableStrings
&&
10236 hasDeprecatedStringLiteralToCharPtrConversion(ICS
);
10239 // Define functions that don't require ill-formed conversions for a given
10240 // argument to be better candidates than functions that do.
10241 unsigned NumArgs
= Cand1
.Conversions
.size();
10242 assert(Cand2
.Conversions
.size() == NumArgs
&& "Overload candidate mismatch");
10243 bool HasBetterConversion
= false;
10244 for (unsigned ArgIdx
= StartArg
; ArgIdx
< NumArgs
; ++ArgIdx
) {
10245 bool Cand1Bad
= IsIllFormedConversion(Cand1
.Conversions
[ArgIdx
]);
10246 bool Cand2Bad
= IsIllFormedConversion(Cand2
.Conversions
[ArgIdx
]);
10247 if (Cand1Bad
!= Cand2Bad
) {
10250 HasBetterConversion
= true;
10254 if (HasBetterConversion
)
10257 // C++ [over.match.best]p1:
10258 // A viable function F1 is defined to be a better function than another
10259 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10260 // conversion sequence than ICSi(F2), and then...
10261 bool HasWorseConversion
= false;
10262 for (unsigned ArgIdx
= StartArg
; ArgIdx
< NumArgs
; ++ArgIdx
) {
10263 switch (CompareImplicitConversionSequences(S
, Loc
,
10264 Cand1
.Conversions
[ArgIdx
],
10265 Cand2
.Conversions
[ArgIdx
])) {
10266 case ImplicitConversionSequence::Better
:
10267 // Cand1 has a better conversion sequence.
10268 HasBetterConversion
= true;
10271 case ImplicitConversionSequence::Worse
:
10272 if (Cand1
.Function
&& Cand2
.Function
&&
10273 Cand1
.isReversed() != Cand2
.isReversed() &&
10274 haveSameParameterTypes(S
.Context
, Cand1
.Function
, Cand2
.Function
)) {
10275 // Work around large-scale breakage caused by considering reversed
10276 // forms of operator== in C++20:
10278 // When comparing a function against a reversed function with the same
10279 // parameter types, if we have a better conversion for one argument and
10280 // a worse conversion for the other, the implicit conversion sequences
10281 // are treated as being equally good.
10283 // This prevents a comparison function from being considered ambiguous
10284 // with a reversed form that is written in the same way.
10286 // We diagnose this as an extension from CreateOverloadedBinOp.
10287 HasWorseConversion
= true;
10291 // Cand1 can't be better than Cand2.
10294 case ImplicitConversionSequence::Indistinguishable
:
10300 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10301 // ICSj(F2), or, if not that,
10302 if (HasBetterConversion
&& !HasWorseConversion
)
10305 // -- the context is an initialization by user-defined conversion
10306 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10307 // from the return type of F1 to the destination type (i.e.,
10308 // the type of the entity being initialized) is a better
10309 // conversion sequence than the standard conversion sequence
10310 // from the return type of F2 to the destination type.
10311 if (Kind
== OverloadCandidateSet::CSK_InitByUserDefinedConversion
&&
10312 Cand1
.Function
&& Cand2
.Function
&&
10313 isa
<CXXConversionDecl
>(Cand1
.Function
) &&
10314 isa
<CXXConversionDecl
>(Cand2
.Function
)) {
10315 // First check whether we prefer one of the conversion functions over the
10316 // other. This only distinguishes the results in non-standard, extension
10317 // cases such as the conversion from a lambda closure type to a function
10318 // pointer or block.
10319 ImplicitConversionSequence::CompareKind Result
=
10320 compareConversionFunctions(S
, Cand1
.Function
, Cand2
.Function
);
10321 if (Result
== ImplicitConversionSequence::Indistinguishable
)
10322 Result
= CompareStandardConversionSequences(S
, Loc
,
10323 Cand1
.FinalConversion
,
10324 Cand2
.FinalConversion
);
10326 if (Result
!= ImplicitConversionSequence::Indistinguishable
)
10327 return Result
== ImplicitConversionSequence::Better
;
10329 // FIXME: Compare kind of reference binding if conversion functions
10330 // convert to a reference type used in direct reference binding, per
10331 // C++14 [over.match.best]p1 section 2 bullet 3.
10334 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10335 // as combined with the resolution to CWG issue 243.
10337 // When the context is initialization by constructor ([over.match.ctor] or
10338 // either phase of [over.match.list]), a constructor is preferred over
10339 // a conversion function.
10340 if (Kind
== OverloadCandidateSet::CSK_InitByConstructor
&& NumArgs
== 1 &&
10341 Cand1
.Function
&& Cand2
.Function
&&
10342 isa
<CXXConstructorDecl
>(Cand1
.Function
) !=
10343 isa
<CXXConstructorDecl
>(Cand2
.Function
))
10344 return isa
<CXXConstructorDecl
>(Cand1
.Function
);
10346 // -- F1 is a non-template function and F2 is a function template
10347 // specialization, or, if not that,
10348 bool Cand1IsSpecialization
= Cand1
.Function
&&
10349 Cand1
.Function
->getPrimaryTemplate();
10350 bool Cand2IsSpecialization
= Cand2
.Function
&&
10351 Cand2
.Function
->getPrimaryTemplate();
10352 if (Cand1IsSpecialization
!= Cand2IsSpecialization
)
10353 return Cand2IsSpecialization
;
10355 // -- F1 and F2 are function template specializations, and the function
10356 // template for F1 is more specialized than the template for F2
10357 // according to the partial ordering rules described in 14.5.5.2, or,
10359 if (Cand1IsSpecialization
&& Cand2IsSpecialization
) {
10360 if (FunctionTemplateDecl
*BetterTemplate
= S
.getMoreSpecializedTemplate(
10361 Cand1
.Function
->getPrimaryTemplate(),
10362 Cand2
.Function
->getPrimaryTemplate(), Loc
,
10363 isa
<CXXConversionDecl
>(Cand1
.Function
) ? TPOC_Conversion
10365 Cand1
.ExplicitCallArguments
, Cand2
.ExplicitCallArguments
,
10366 Cand1
.isReversed() ^ Cand2
.isReversed()))
10367 return BetterTemplate
== Cand1
.Function
->getPrimaryTemplate();
10370 // -— F1 and F2 are non-template functions with the same
10371 // parameter-type-lists, and F1 is more constrained than F2 [...],
10372 if (!Cand1IsSpecialization
&& !Cand2IsSpecialization
&&
10373 sameFunctionParameterTypeLists(S
, Cand1
, Cand2
)) {
10374 FunctionDecl
*Function1
= Cand1
.Function
;
10375 FunctionDecl
*Function2
= Cand2
.Function
;
10376 if (FunctionDecl
*MF
= Function1
->getInstantiatedFromMemberFunction())
10378 if (FunctionDecl
*MF
= Function2
->getInstantiatedFromMemberFunction())
10381 const Expr
*RC1
= Function1
->getTrailingRequiresClause();
10382 const Expr
*RC2
= Function2
->getTrailingRequiresClause();
10384 bool AtLeastAsConstrained1
, AtLeastAsConstrained2
;
10385 if (S
.IsAtLeastAsConstrained(Function1
, RC1
, Function2
, RC2
,
10386 AtLeastAsConstrained1
) ||
10387 S
.IsAtLeastAsConstrained(Function2
, RC2
, Function1
, RC1
,
10388 AtLeastAsConstrained2
))
10390 if (AtLeastAsConstrained1
!= AtLeastAsConstrained2
)
10391 return AtLeastAsConstrained1
;
10392 } else if (RC1
|| RC2
) {
10393 return RC1
!= nullptr;
10397 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10398 // class B of D, and for all arguments the corresponding parameters of
10399 // F1 and F2 have the same type.
10400 // FIXME: Implement the "all parameters have the same type" check.
10401 bool Cand1IsInherited
=
10402 isa_and_nonnull
<ConstructorUsingShadowDecl
>(Cand1
.FoundDecl
.getDecl());
10403 bool Cand2IsInherited
=
10404 isa_and_nonnull
<ConstructorUsingShadowDecl
>(Cand2
.FoundDecl
.getDecl());
10405 if (Cand1IsInherited
!= Cand2IsInherited
)
10406 return Cand2IsInherited
;
10407 else if (Cand1IsInherited
) {
10408 assert(Cand2IsInherited
);
10409 auto *Cand1Class
= cast
<CXXRecordDecl
>(Cand1
.Function
->getDeclContext());
10410 auto *Cand2Class
= cast
<CXXRecordDecl
>(Cand2
.Function
->getDeclContext());
10411 if (Cand1Class
->isDerivedFrom(Cand2Class
))
10413 if (Cand2Class
->isDerivedFrom(Cand1Class
))
10415 // Inherited from sibling base classes: still ambiguous.
10418 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10419 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10420 // with reversed order of parameters and F1 is not
10422 // We rank reversed + different operator as worse than just reversed, but
10423 // that comparison can never happen, because we only consider reversing for
10424 // the maximally-rewritten operator (== or <=>).
10425 if (Cand1
.RewriteKind
!= Cand2
.RewriteKind
)
10426 return Cand1
.RewriteKind
< Cand2
.RewriteKind
;
10428 // Check C++17 tie-breakers for deduction guides.
10430 auto *Guide1
= dyn_cast_or_null
<CXXDeductionGuideDecl
>(Cand1
.Function
);
10431 auto *Guide2
= dyn_cast_or_null
<CXXDeductionGuideDecl
>(Cand2
.Function
);
10432 if (Guide1
&& Guide2
) {
10433 // -- F1 is generated from a deduction-guide and F2 is not
10434 if (Guide1
->isImplicit() != Guide2
->isImplicit())
10435 return Guide2
->isImplicit();
10437 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10438 if (Guide1
->getDeductionCandidateKind() == DeductionCandidate::Copy
)
10440 if (Guide2
->getDeductionCandidateKind() == DeductionCandidate::Copy
)
10443 // --F1 is generated from a non-template constructor and F2 is generated
10444 // from a constructor template
10445 const auto *Constructor1
= Guide1
->getCorrespondingConstructor();
10446 const auto *Constructor2
= Guide2
->getCorrespondingConstructor();
10447 if (Constructor1
&& Constructor2
) {
10448 bool isC1Templated
= Constructor1
->getTemplatedKind() !=
10449 FunctionDecl::TemplatedKind::TK_NonTemplate
;
10450 bool isC2Templated
= Constructor2
->getTemplatedKind() !=
10451 FunctionDecl::TemplatedKind::TK_NonTemplate
;
10452 if (isC1Templated
!= isC2Templated
)
10453 return isC2Templated
;
10458 // Check for enable_if value-based overload resolution.
10459 if (Cand1
.Function
&& Cand2
.Function
) {
10460 Comparison Cmp
= compareEnableIfAttrs(S
, Cand1
.Function
, Cand2
.Function
);
10461 if (Cmp
!= Comparison::Equal
)
10462 return Cmp
== Comparison::Better
;
10465 bool HasPS1
= Cand1
.Function
!= nullptr &&
10466 functionHasPassObjectSizeParams(Cand1
.Function
);
10467 bool HasPS2
= Cand2
.Function
!= nullptr &&
10468 functionHasPassObjectSizeParams(Cand2
.Function
);
10469 if (HasPS1
!= HasPS2
&& HasPS1
)
10472 auto MV
= isBetterMultiversionCandidate(Cand1
, Cand2
);
10473 if (MV
== Comparison::Better
)
10475 if (MV
== Comparison::Worse
)
10478 // If other rules cannot determine which is better, CUDA preference is used
10479 // to determine which is better.
10480 if (S
.getLangOpts().CUDA
&& Cand1
.Function
&& Cand2
.Function
) {
10481 FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true);
10482 return S
.IdentifyCUDAPreference(Caller
, Cand1
.Function
) >
10483 S
.IdentifyCUDAPreference(Caller
, Cand2
.Function
);
10486 // General member function overloading is handled above, so this only handles
10487 // constructors with address spaces.
10488 // This only handles address spaces since C++ has no other
10489 // qualifier that can be used with constructors.
10490 const auto *CD1
= dyn_cast_or_null
<CXXConstructorDecl
>(Cand1
.Function
);
10491 const auto *CD2
= dyn_cast_or_null
<CXXConstructorDecl
>(Cand2
.Function
);
10493 LangAS AS1
= CD1
->getMethodQualifiers().getAddressSpace();
10494 LangAS AS2
= CD2
->getMethodQualifiers().getAddressSpace();
10496 if (Qualifiers::isAddressSpaceSupersetOf(AS2
, AS1
))
10498 if (Qualifiers::isAddressSpaceSupersetOf(AS1
, AS2
))
10506 /// Determine whether two declarations are "equivalent" for the purposes of
10507 /// name lookup and overload resolution. This applies when the same internal/no
10508 /// linkage entity is defined by two modules (probably by textually including
10509 /// the same header). In such a case, we don't consider the declarations to
10510 /// declare the same entity, but we also don't want lookups with both
10511 /// declarations visible to be ambiguous in some cases (this happens when using
10512 /// a modularized libstdc++).
10513 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl
*A
,
10514 const NamedDecl
*B
) {
10515 auto *VA
= dyn_cast_or_null
<ValueDecl
>(A
);
10516 auto *VB
= dyn_cast_or_null
<ValueDecl
>(B
);
10520 // The declarations must be declaring the same name as an internal linkage
10521 // entity in different modules.
10522 if (!VA
->getDeclContext()->getRedeclContext()->Equals(
10523 VB
->getDeclContext()->getRedeclContext()) ||
10524 getOwningModule(VA
) == getOwningModule(VB
) ||
10525 VA
->isExternallyVisible() || VB
->isExternallyVisible())
10528 // Check that the declarations appear to be equivalent.
10530 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10531 // For constants and functions, we should check the initializer or body is
10532 // the same. For non-constant variables, we shouldn't allow it at all.
10533 if (Context
.hasSameType(VA
->getType(), VB
->getType()))
10536 // Enum constants within unnamed enumerations will have different types, but
10537 // may still be similar enough to be interchangeable for our purposes.
10538 if (auto *EA
= dyn_cast
<EnumConstantDecl
>(VA
)) {
10539 if (auto *EB
= dyn_cast
<EnumConstantDecl
>(VB
)) {
10540 // Only handle anonymous enums. If the enumerations were named and
10541 // equivalent, they would have been merged to the same type.
10542 auto *EnumA
= cast
<EnumDecl
>(EA
->getDeclContext());
10543 auto *EnumB
= cast
<EnumDecl
>(EB
->getDeclContext());
10544 if (EnumA
->hasNameForLinkage() || EnumB
->hasNameForLinkage() ||
10545 !Context
.hasSameType(EnumA
->getIntegerType(),
10546 EnumB
->getIntegerType()))
10548 // Allow this only if the value is the same for both enumerators.
10549 return llvm::APSInt::isSameValue(EA
->getInitVal(), EB
->getInitVal());
10553 // Nothing else is sufficiently similar.
10557 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10558 SourceLocation Loc
, const NamedDecl
*D
, ArrayRef
<const NamedDecl
*> Equiv
) {
10559 assert(D
&& "Unknown declaration");
10560 Diag(Loc
, diag::ext_equivalent_internal_linkage_decl_in_modules
) << D
;
10562 Module
*M
= getOwningModule(D
);
10563 Diag(D
->getLocation(), diag::note_equivalent_internal_linkage_decl
)
10564 << !M
<< (M
? M
->getFullModuleName() : "");
10566 for (auto *E
: Equiv
) {
10567 Module
*M
= getOwningModule(E
);
10568 Diag(E
->getLocation(), diag::note_equivalent_internal_linkage_decl
)
10569 << !M
<< (M
? M
->getFullModuleName() : "");
10573 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10574 return FailureKind
== ovl_fail_bad_deduction
&&
10575 DeductionFailure
.Result
== Sema::TDK_ConstraintsNotSatisfied
&&
10576 static_cast<CNSInfo
*>(DeductionFailure
.Data
)
10577 ->Satisfaction
.ContainsErrors
;
10580 /// Computes the best viable function (C++ 13.3.3)
10581 /// within an overload candidate set.
10583 /// \param Loc The location of the function name (or operator symbol) for
10584 /// which overload resolution occurs.
10586 /// \param Best If overload resolution was successful or found a deleted
10587 /// function, \p Best points to the candidate function found.
10589 /// \returns The result of overload resolution.
10591 OverloadCandidateSet::BestViableFunction(Sema
&S
, SourceLocation Loc
,
10593 llvm::SmallVector
<OverloadCandidate
*, 16> Candidates
;
10594 std::transform(begin(), end(), std::back_inserter(Candidates
),
10595 [](OverloadCandidate
&Cand
) { return &Cand
; });
10597 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10598 // are accepted by both clang and NVCC. However, during a particular
10599 // compilation mode only one call variant is viable. We need to
10600 // exclude non-viable overload candidates from consideration based
10601 // only on their host/device attributes. Specifically, if one
10602 // candidate call is WrongSide and the other is SameSide, we ignore
10603 // the WrongSide candidate.
10604 // We only need to remove wrong-sided candidates here if
10605 // -fgpu-exclude-wrong-side-overloads is off. When
10606 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10607 // uniformly in isBetterOverloadCandidate.
10608 if (S
.getLangOpts().CUDA
&& !S
.getLangOpts().GPUExcludeWrongSideOverloads
) {
10609 const FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true);
10610 bool ContainsSameSideCandidate
=
10611 llvm::any_of(Candidates
, [&](OverloadCandidate
*Cand
) {
10612 // Check viable function only.
10613 return Cand
->Viable
&& Cand
->Function
&&
10614 S
.IdentifyCUDAPreference(Caller
, Cand
->Function
) ==
10615 Sema::CFP_SameSide
;
10617 if (ContainsSameSideCandidate
) {
10618 auto IsWrongSideCandidate
= [&](OverloadCandidate
*Cand
) {
10619 // Check viable function only to avoid unnecessary data copying/moving.
10620 return Cand
->Viable
&& Cand
->Function
&&
10621 S
.IdentifyCUDAPreference(Caller
, Cand
->Function
) ==
10622 Sema::CFP_WrongSide
;
10624 llvm::erase_if(Candidates
, IsWrongSideCandidate
);
10628 // Find the best viable function.
10630 for (auto *Cand
: Candidates
) {
10631 Cand
->Best
= false;
10632 if (Cand
->Viable
) {
10633 if (Best
== end() ||
10634 isBetterOverloadCandidate(S
, *Cand
, *Best
, Loc
, Kind
))
10636 } else if (Cand
->NotValidBecauseConstraintExprHasError()) {
10637 // This candidate has constraint that we were unable to evaluate because
10638 // it referenced an expression that contained an error. Rather than fall
10639 // back onto a potentially unintended candidate (made worse by
10640 // subsuming constraints), treat this as 'no viable candidate'.
10642 return OR_No_Viable_Function
;
10646 // If we didn't find any viable functions, abort.
10648 return OR_No_Viable_Function
;
10650 llvm::SmallVector
<const NamedDecl
*, 4> EquivalentCands
;
10652 llvm::SmallVector
<OverloadCandidate
*, 4> PendingBest
;
10653 PendingBest
.push_back(&*Best
);
10656 // Make sure that this function is better than every other viable
10657 // function. If not, we have an ambiguity.
10658 while (!PendingBest
.empty()) {
10659 auto *Curr
= PendingBest
.pop_back_val();
10660 for (auto *Cand
: Candidates
) {
10661 if (Cand
->Viable
&& !Cand
->Best
&&
10662 !isBetterOverloadCandidate(S
, *Curr
, *Cand
, Loc
, Kind
)) {
10663 PendingBest
.push_back(Cand
);
10666 if (S
.isEquivalentInternalLinkageDeclaration(Cand
->Function
,
10668 EquivalentCands
.push_back(Cand
->Function
);
10675 // If we found more than one best candidate, this is ambiguous.
10677 return OR_Ambiguous
;
10679 // Best is the best viable function.
10680 if (Best
->Function
&& Best
->Function
->isDeleted())
10683 if (!EquivalentCands
.empty())
10684 S
.diagnoseEquivalentInternalLinkageDeclarations(Loc
, Best
->Function
,
10692 enum OverloadCandidateKind
{
10695 oc_reversed_binary_operator
,
10697 oc_implicit_default_constructor
,
10698 oc_implicit_copy_constructor
,
10699 oc_implicit_move_constructor
,
10700 oc_implicit_copy_assignment
,
10701 oc_implicit_move_assignment
,
10702 oc_implicit_equality_comparison
,
10703 oc_inherited_constructor
10706 enum OverloadCandidateSelect
{
10709 ocs_described_template
,
10712 static std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
>
10713 ClassifyOverloadCandidate(Sema
&S
, const NamedDecl
*Found
,
10714 const FunctionDecl
*Fn
,
10715 OverloadCandidateRewriteKind CRK
,
10716 std::string
&Description
) {
10718 bool isTemplate
= Fn
->isTemplateDecl() || Found
->isTemplateDecl();
10719 if (FunctionTemplateDecl
*FunTmpl
= Fn
->getPrimaryTemplate()) {
10721 Description
= S
.getTemplateArgumentBindingsText(
10722 FunTmpl
->getTemplateParameters(), *Fn
->getTemplateSpecializationArgs());
10725 OverloadCandidateSelect Select
= [&]() {
10726 if (!Description
.empty())
10727 return ocs_described_template
;
10728 return isTemplate
? ocs_template
: ocs_non_template
;
10731 OverloadCandidateKind Kind
= [&]() {
10732 if (Fn
->isImplicit() && Fn
->getOverloadedOperator() == OO_EqualEqual
)
10733 return oc_implicit_equality_comparison
;
10735 if (CRK
& CRK_Reversed
)
10736 return oc_reversed_binary_operator
;
10738 if (const auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(Fn
)) {
10739 if (!Ctor
->isImplicit()) {
10740 if (isa
<ConstructorUsingShadowDecl
>(Found
))
10741 return oc_inherited_constructor
;
10743 return oc_constructor
;
10746 if (Ctor
->isDefaultConstructor())
10747 return oc_implicit_default_constructor
;
10749 if (Ctor
->isMoveConstructor())
10750 return oc_implicit_move_constructor
;
10752 assert(Ctor
->isCopyConstructor() &&
10753 "unexpected sort of implicit constructor");
10754 return oc_implicit_copy_constructor
;
10757 if (const auto *Meth
= dyn_cast
<CXXMethodDecl
>(Fn
)) {
10758 // This actually gets spelled 'candidate function' for now, but
10759 // it doesn't hurt to split it out.
10760 if (!Meth
->isImplicit())
10763 if (Meth
->isMoveAssignmentOperator())
10764 return oc_implicit_move_assignment
;
10766 if (Meth
->isCopyAssignmentOperator())
10767 return oc_implicit_copy_assignment
;
10769 assert(isa
<CXXConversionDecl
>(Meth
) && "expected conversion");
10773 return oc_function
;
10776 return std::make_pair(Kind
, Select
);
10779 void MaybeEmitInheritedConstructorNote(Sema
&S
, const Decl
*FoundDecl
) {
10780 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10782 if (const auto *Shadow
= dyn_cast
<ConstructorUsingShadowDecl
>(FoundDecl
))
10783 S
.Diag(FoundDecl
->getLocation(),
10784 diag::note_ovl_candidate_inherited_constructor
)
10785 << Shadow
->getNominatedBaseClass();
10788 } // end anonymous namespace
10790 static bool isFunctionAlwaysEnabled(const ASTContext
&Ctx
,
10791 const FunctionDecl
*FD
) {
10792 for (auto *EnableIf
: FD
->specific_attrs
<EnableIfAttr
>()) {
10794 if (EnableIf
->getCond()->isValueDependent() ||
10795 !EnableIf
->getCond()->EvaluateAsBooleanCondition(AlwaysTrue
, Ctx
))
10803 /// Returns true if we can take the address of the function.
10805 /// \param Complain - If true, we'll emit a diagnostic
10806 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10807 /// we in overload resolution?
10808 /// \param Loc - The location of the statement we're complaining about. Ignored
10809 /// if we're not complaining, or if we're in overload resolution.
10810 static bool checkAddressOfFunctionIsAvailable(Sema
&S
, const FunctionDecl
*FD
,
10812 bool InOverloadResolution
,
10813 SourceLocation Loc
) {
10814 if (!isFunctionAlwaysEnabled(S
.Context
, FD
)) {
10816 if (InOverloadResolution
)
10817 S
.Diag(FD
->getBeginLoc(),
10818 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr
);
10820 S
.Diag(Loc
, diag::err_addrof_function_disabled_by_enable_if_attr
) << FD
;
10825 if (FD
->getTrailingRequiresClause()) {
10826 ConstraintSatisfaction Satisfaction
;
10827 if (S
.CheckFunctionConstraints(FD
, Satisfaction
, Loc
))
10829 if (!Satisfaction
.IsSatisfied
) {
10831 if (InOverloadResolution
) {
10832 SmallString
<128> TemplateArgString
;
10833 if (FunctionTemplateDecl
*FunTmpl
= FD
->getPrimaryTemplate()) {
10834 TemplateArgString
+= " ";
10835 TemplateArgString
+= S
.getTemplateArgumentBindingsText(
10836 FunTmpl
->getTemplateParameters(),
10837 *FD
->getTemplateSpecializationArgs());
10840 S
.Diag(FD
->getBeginLoc(),
10841 diag::note_ovl_candidate_unsatisfied_constraints
)
10842 << TemplateArgString
;
10844 S
.Diag(Loc
, diag::err_addrof_function_constraints_not_satisfied
)
10846 S
.DiagnoseUnsatisfiedConstraint(Satisfaction
);
10852 auto I
= llvm::find_if(FD
->parameters(), [](const ParmVarDecl
*P
) {
10853 return P
->hasAttr
<PassObjectSizeAttr
>();
10855 if (I
== FD
->param_end())
10859 // Add one to ParamNo because it's user-facing
10860 unsigned ParamNo
= std::distance(FD
->param_begin(), I
) + 1;
10861 if (InOverloadResolution
)
10862 S
.Diag(FD
->getLocation(),
10863 diag::note_ovl_candidate_has_pass_object_size_params
)
10866 S
.Diag(Loc
, diag::err_address_of_function_with_pass_object_size_params
)
10872 static bool checkAddressOfCandidateIsAvailable(Sema
&S
,
10873 const FunctionDecl
*FD
) {
10874 return checkAddressOfFunctionIsAvailable(S
, FD
, /*Complain=*/true,
10875 /*InOverloadResolution=*/true,
10876 /*Loc=*/SourceLocation());
10879 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl
*Function
,
10881 SourceLocation Loc
) {
10882 return ::checkAddressOfFunctionIsAvailable(*this, Function
, Complain
,
10883 /*InOverloadResolution=*/false,
10887 // Don't print candidates other than the one that matches the calling
10888 // convention of the call operator, since that is guaranteed to exist.
10889 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl
*Fn
) {
10890 const auto *ConvD
= dyn_cast
<CXXConversionDecl
>(Fn
);
10894 const auto *RD
= cast
<CXXRecordDecl
>(Fn
->getParent());
10895 if (!RD
->isLambda())
10898 CXXMethodDecl
*CallOp
= RD
->getLambdaCallOperator();
10899 CallingConv CallOpCC
=
10900 CallOp
->getType()->castAs
<FunctionType
>()->getCallConv();
10901 QualType ConvRTy
= ConvD
->getType()->castAs
<FunctionType
>()->getReturnType();
10902 CallingConv ConvToCC
=
10903 ConvRTy
->getPointeeType()->castAs
<FunctionType
>()->getCallConv();
10905 return ConvToCC
!= CallOpCC
;
10908 // Notes the location of an overload candidate.
10909 void Sema::NoteOverloadCandidate(const NamedDecl
*Found
, const FunctionDecl
*Fn
,
10910 OverloadCandidateRewriteKind RewriteKind
,
10911 QualType DestType
, bool TakingAddress
) {
10912 if (TakingAddress
&& !checkAddressOfCandidateIsAvailable(*this, Fn
))
10914 if (Fn
->isMultiVersion() && Fn
->hasAttr
<TargetAttr
>() &&
10915 !Fn
->getAttr
<TargetAttr
>()->isDefaultVersion())
10917 if (Fn
->isMultiVersion() && Fn
->hasAttr
<TargetVersionAttr
>() &&
10918 !Fn
->getAttr
<TargetVersionAttr
>()->isDefaultVersion())
10920 if (shouldSkipNotingLambdaConversionDecl(Fn
))
10923 std::string FnDesc
;
10924 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> KSPair
=
10925 ClassifyOverloadCandidate(*this, Found
, Fn
, RewriteKind
, FnDesc
);
10926 PartialDiagnostic PD
= PDiag(diag::note_ovl_candidate
)
10927 << (unsigned)KSPair
.first
<< (unsigned)KSPair
.second
10930 HandleFunctionTypeMismatch(PD
, Fn
->getType(), DestType
);
10931 Diag(Fn
->getLocation(), PD
);
10932 MaybeEmitInheritedConstructorNote(*this, Found
);
10936 MaybeDiagnoseAmbiguousConstraints(Sema
&S
, ArrayRef
<OverloadCandidate
> Cands
) {
10937 // Perhaps the ambiguity was caused by two atomic constraints that are
10938 // 'identical' but not equivalent:
10940 // void foo() requires (sizeof(T) > 4) { } // #1
10941 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10943 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10944 // #2 to subsume #1, but these constraint are not considered equivalent
10945 // according to the subsumption rules because they are not the same
10946 // source-level construct. This behavior is quite confusing and we should try
10947 // to help the user figure out what happened.
10949 SmallVector
<const Expr
*, 3> FirstAC
, SecondAC
;
10950 FunctionDecl
*FirstCand
= nullptr, *SecondCand
= nullptr;
10951 for (auto I
= Cands
.begin(), E
= Cands
.end(); I
!= E
; ++I
) {
10954 SmallVector
<const Expr
*, 3> AC
;
10955 if (auto *Template
= I
->Function
->getPrimaryTemplate())
10956 Template
->getAssociatedConstraints(AC
);
10958 I
->Function
->getAssociatedConstraints(AC
);
10961 if (FirstCand
== nullptr) {
10962 FirstCand
= I
->Function
;
10964 } else if (SecondCand
== nullptr) {
10965 SecondCand
= I
->Function
;
10968 // We have more than one pair of constrained functions - this check is
10969 // expensive and we'd rather not try to diagnose it.
10975 // The diagnostic can only happen if there are associated constraints on
10976 // both sides (there needs to be some identical atomic constraint).
10977 if (S
.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand
, FirstAC
,
10978 SecondCand
, SecondAC
))
10979 // Just show the user one diagnostic, they'll probably figure it out
10984 // Notes the location of all overload candidates designated through
10986 void Sema::NoteAllOverloadCandidates(Expr
*OverloadedExpr
, QualType DestType
,
10987 bool TakingAddress
) {
10988 assert(OverloadedExpr
->getType() == Context
.OverloadTy
);
10990 OverloadExpr::FindResult Ovl
= OverloadExpr::find(OverloadedExpr
);
10991 OverloadExpr
*OvlExpr
= Ovl
.Expression
;
10993 for (UnresolvedSetIterator I
= OvlExpr
->decls_begin(),
10994 IEnd
= OvlExpr
->decls_end();
10996 if (FunctionTemplateDecl
*FunTmpl
=
10997 dyn_cast
<FunctionTemplateDecl
>((*I
)->getUnderlyingDecl()) ) {
10998 NoteOverloadCandidate(*I
, FunTmpl
->getTemplatedDecl(), CRK_None
, DestType
,
11000 } else if (FunctionDecl
*Fun
11001 = dyn_cast
<FunctionDecl
>((*I
)->getUnderlyingDecl()) ) {
11002 NoteOverloadCandidate(*I
, Fun
, CRK_None
, DestType
, TakingAddress
);
11007 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
11008 /// "lead" diagnostic; it will be given two arguments, the source and
11009 /// target types of the conversion.
11010 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11012 SourceLocation CaretLoc
,
11013 const PartialDiagnostic
&PDiag
) const {
11014 S
.Diag(CaretLoc
, PDiag
)
11015 << Ambiguous
.getFromType() << Ambiguous
.getToType();
11016 unsigned CandsShown
= 0;
11017 AmbiguousConversionSequence::const_iterator I
, E
;
11018 for (I
= Ambiguous
.begin(), E
= Ambiguous
.end(); I
!= E
; ++I
) {
11019 if (CandsShown
>= S
.Diags
.getNumOverloadCandidatesToShow())
11022 S
.NoteOverloadCandidate(I
->first
, I
->second
);
11024 S
.Diags
.overloadCandidatesShown(CandsShown
);
11026 S
.Diag(SourceLocation(), diag::note_ovl_too_many_candidates
) << int(E
- I
);
11029 static void DiagnoseBadConversion(Sema
&S
, OverloadCandidate
*Cand
,
11030 unsigned I
, bool TakingCandidateAddress
) {
11031 const ImplicitConversionSequence
&Conv
= Cand
->Conversions
[I
];
11032 assert(Conv
.isBad());
11033 assert(Cand
->Function
&& "for now, candidate must be a function");
11034 FunctionDecl
*Fn
= Cand
->Function
;
11036 // There's a conversion slot for the object argument if this is a
11037 // non-constructor method. Note that 'I' corresponds the
11038 // conversion-slot index.
11039 bool isObjectArgument
= false;
11040 if (isa
<CXXMethodDecl
>(Fn
) && !isa
<CXXConstructorDecl
>(Fn
)) {
11042 isObjectArgument
= true;
11047 std::string FnDesc
;
11048 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11049 ClassifyOverloadCandidate(S
, Cand
->FoundDecl
, Fn
, Cand
->getRewriteKind(),
11052 Expr
*FromExpr
= Conv
.Bad
.FromExpr
;
11053 QualType FromTy
= Conv
.Bad
.getFromType();
11054 QualType ToTy
= Conv
.Bad
.getToType();
11055 SourceRange ToParamRange
=
11056 !isObjectArgument
? Fn
->getParamDecl(I
)->getSourceRange() : SourceRange();
11058 if (FromTy
== S
.Context
.OverloadTy
) {
11059 assert(FromExpr
&& "overload set argument came from implicit argument?");
11060 Expr
*E
= FromExpr
->IgnoreParens();
11061 if (isa
<UnaryOperator
>(E
))
11062 E
= cast
<UnaryOperator
>(E
)->getSubExpr()->IgnoreParens();
11063 DeclarationName Name
= cast
<OverloadExpr
>(E
)->getName();
11065 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_overload
)
11066 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11067 << ToParamRange
<< ToTy
<< Name
<< I
+ 1;
11068 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11072 // Do some hand-waving analysis to see if the non-viability is due
11073 // to a qualifier mismatch.
11074 CanQualType CFromTy
= S
.Context
.getCanonicalType(FromTy
);
11075 CanQualType CToTy
= S
.Context
.getCanonicalType(ToTy
);
11076 if (CanQual
<ReferenceType
> RT
= CToTy
->getAs
<ReferenceType
>())
11077 CToTy
= RT
->getPointeeType();
11079 // TODO: detect and diagnose the full richness of const mismatches.
11080 if (CanQual
<PointerType
> FromPT
= CFromTy
->getAs
<PointerType
>())
11081 if (CanQual
<PointerType
> ToPT
= CToTy
->getAs
<PointerType
>()) {
11082 CFromTy
= FromPT
->getPointeeType();
11083 CToTy
= ToPT
->getPointeeType();
11087 if (CToTy
.getUnqualifiedType() == CFromTy
.getUnqualifiedType() &&
11088 !CToTy
.isAtLeastAsQualifiedAs(CFromTy
)) {
11089 Qualifiers FromQs
= CFromTy
.getQualifiers();
11090 Qualifiers ToQs
= CToTy
.getQualifiers();
11092 if (FromQs
.getAddressSpace() != ToQs
.getAddressSpace()) {
11093 if (isObjectArgument
)
11094 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_addrspace_this
)
11095 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
11096 << FnDesc
<< FromQs
.getAddressSpace() << ToQs
.getAddressSpace();
11098 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_addrspace
)
11099 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
11100 << FnDesc
<< ToParamRange
<< FromQs
.getAddressSpace()
11101 << ToQs
.getAddressSpace() << ToTy
->isReferenceType() << I
+ 1;
11102 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11106 if (FromQs
.getObjCLifetime() != ToQs
.getObjCLifetime()) {
11107 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_ownership
)
11108 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11109 << ToParamRange
<< FromTy
<< FromQs
.getObjCLifetime()
11110 << ToQs
.getObjCLifetime() << (unsigned)isObjectArgument
<< I
+ 1;
11111 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11115 if (FromQs
.getObjCGCAttr() != ToQs
.getObjCGCAttr()) {
11116 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_gc
)
11117 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11118 << ToParamRange
<< FromTy
<< FromQs
.getObjCGCAttr()
11119 << ToQs
.getObjCGCAttr() << (unsigned)isObjectArgument
<< I
+ 1;
11120 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11124 unsigned CVR
= FromQs
.getCVRQualifiers() & ~ToQs
.getCVRQualifiers();
11125 assert(CVR
&& "expected qualifiers mismatch");
11127 if (isObjectArgument
) {
11128 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_cvr_this
)
11129 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11130 << FromTy
<< (CVR
- 1);
11132 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_cvr
)
11133 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11134 << ToParamRange
<< FromTy
<< (CVR
- 1) << I
+ 1;
11136 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11140 if (Conv
.Bad
.Kind
== BadConversionSequence::lvalue_ref_to_rvalue
||
11141 Conv
.Bad
.Kind
== BadConversionSequence::rvalue_ref_to_lvalue
) {
11142 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_value_category
)
11143 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11144 << (unsigned)isObjectArgument
<< I
+ 1
11145 << (Conv
.Bad
.Kind
== BadConversionSequence::rvalue_ref_to_lvalue
)
11147 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11151 // Special diagnostic for failure to convert an initializer list, since
11152 // telling the user that it has type void is not useful.
11153 if (FromExpr
&& isa
<InitListExpr
>(FromExpr
)) {
11154 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_list_argument
)
11155 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11156 << ToParamRange
<< FromTy
<< ToTy
<< (unsigned)isObjectArgument
<< I
+ 1
11157 << (Conv
.Bad
.Kind
== BadConversionSequence::too_few_initializers
? 1
11158 : Conv
.Bad
.Kind
== BadConversionSequence::too_many_initializers
11161 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11165 // Diagnose references or pointers to incomplete types differently,
11166 // since it's far from impossible that the incompleteness triggered
11168 QualType TempFromTy
= FromTy
.getNonReferenceType();
11169 if (const PointerType
*PTy
= TempFromTy
->getAs
<PointerType
>())
11170 TempFromTy
= PTy
->getPointeeType();
11171 if (TempFromTy
->isIncompleteType()) {
11172 // Emit the generic diagnostic and, optionally, add the hints to it.
11173 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete
)
11174 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11175 << ToParamRange
<< FromTy
<< ToTy
<< (unsigned)isObjectArgument
<< I
+ 1
11176 << (unsigned)(Cand
->Fix
.Kind
);
11178 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11182 // Diagnose base -> derived pointer conversions.
11183 unsigned BaseToDerivedConversion
= 0;
11184 if (const PointerType
*FromPtrTy
= FromTy
->getAs
<PointerType
>()) {
11185 if (const PointerType
*ToPtrTy
= ToTy
->getAs
<PointerType
>()) {
11186 if (ToPtrTy
->getPointeeType().isAtLeastAsQualifiedAs(
11187 FromPtrTy
->getPointeeType()) &&
11188 !FromPtrTy
->getPointeeType()->isIncompleteType() &&
11189 !ToPtrTy
->getPointeeType()->isIncompleteType() &&
11190 S
.IsDerivedFrom(SourceLocation(), ToPtrTy
->getPointeeType(),
11191 FromPtrTy
->getPointeeType()))
11192 BaseToDerivedConversion
= 1;
11194 } else if (const ObjCObjectPointerType
*FromPtrTy
11195 = FromTy
->getAs
<ObjCObjectPointerType
>()) {
11196 if (const ObjCObjectPointerType
*ToPtrTy
11197 = ToTy
->getAs
<ObjCObjectPointerType
>())
11198 if (const ObjCInterfaceDecl
*FromIface
= FromPtrTy
->getInterfaceDecl())
11199 if (const ObjCInterfaceDecl
*ToIface
= ToPtrTy
->getInterfaceDecl())
11200 if (ToPtrTy
->getPointeeType().isAtLeastAsQualifiedAs(
11201 FromPtrTy
->getPointeeType()) &&
11202 FromIface
->isSuperClassOf(ToIface
))
11203 BaseToDerivedConversion
= 2;
11204 } else if (const ReferenceType
*ToRefTy
= ToTy
->getAs
<ReferenceType
>()) {
11205 if (ToRefTy
->getPointeeType().isAtLeastAsQualifiedAs(FromTy
) &&
11206 !FromTy
->isIncompleteType() &&
11207 !ToRefTy
->getPointeeType()->isIncompleteType() &&
11208 S
.IsDerivedFrom(SourceLocation(), ToRefTy
->getPointeeType(), FromTy
)) {
11209 BaseToDerivedConversion
= 3;
11213 if (BaseToDerivedConversion
) {
11214 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv
)
11215 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11216 << ToParamRange
<< (BaseToDerivedConversion
- 1) << FromTy
<< ToTy
11218 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11222 if (isa
<ObjCObjectPointerType
>(CFromTy
) &&
11223 isa
<PointerType
>(CToTy
)) {
11224 Qualifiers FromQs
= CFromTy
.getQualifiers();
11225 Qualifiers ToQs
= CToTy
.getQualifiers();
11226 if (FromQs
.getObjCLifetime() != ToQs
.getObjCLifetime()) {
11227 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_arc_conv
)
11228 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11229 << ToParamRange
<< FromTy
<< ToTy
<< (unsigned)isObjectArgument
11231 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11236 if (TakingCandidateAddress
&&
11237 !checkAddressOfCandidateIsAvailable(S
, Cand
->Function
))
11240 // Emit the generic diagnostic and, optionally, add the hints to it.
11241 PartialDiagnostic FDiag
= S
.PDiag(diag::note_ovl_candidate_bad_conv
);
11242 FDiag
<< (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11243 << ToParamRange
<< FromTy
<< ToTy
<< (unsigned)isObjectArgument
<< I
+ 1
11244 << (unsigned)(Cand
->Fix
.Kind
);
11246 // Check that location of Fn is not in system header.
11247 if (!S
.SourceMgr
.isInSystemHeader(Fn
->getLocation())) {
11248 // If we can fix the conversion, suggest the FixIts.
11249 for (const FixItHint
&HI
: Cand
->Fix
.Hints
)
11253 S
.Diag(Fn
->getLocation(), FDiag
);
11255 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11258 /// Additional arity mismatch diagnosis specific to a function overload
11259 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
11260 /// over a candidate in any candidate set.
11261 static bool CheckArityMismatch(Sema
&S
, OverloadCandidate
*Cand
,
11262 unsigned NumArgs
) {
11263 FunctionDecl
*Fn
= Cand
->Function
;
11264 unsigned MinParams
= Fn
->getMinRequiredArguments();
11266 // With invalid overloaded operators, it's possible that we think we
11267 // have an arity mismatch when in fact it looks like we have the
11268 // right number of arguments, because only overloaded operators have
11269 // the weird behavior of overloading member and non-member functions.
11270 // Just don't report anything.
11271 if (Fn
->isInvalidDecl() &&
11272 Fn
->getDeclName().getNameKind() == DeclarationName::CXXOperatorName
)
11275 if (NumArgs
< MinParams
) {
11276 assert((Cand
->FailureKind
== ovl_fail_too_few_arguments
) ||
11277 (Cand
->FailureKind
== ovl_fail_bad_deduction
&&
11278 Cand
->DeductionFailure
.Result
== Sema::TDK_TooFewArguments
));
11280 assert((Cand
->FailureKind
== ovl_fail_too_many_arguments
) ||
11281 (Cand
->FailureKind
== ovl_fail_bad_deduction
&&
11282 Cand
->DeductionFailure
.Result
== Sema::TDK_TooManyArguments
));
11288 /// General arity mismatch diagnosis over a candidate in a candidate set.
11289 static void DiagnoseArityMismatch(Sema
&S
, NamedDecl
*Found
, Decl
*D
,
11290 unsigned NumFormalArgs
) {
11291 assert(isa
<FunctionDecl
>(D
) &&
11292 "The templated declaration should at least be a function"
11293 " when diagnosing bad template argument deduction due to too many"
11294 " or too few arguments");
11296 FunctionDecl
*Fn
= cast
<FunctionDecl
>(D
);
11298 // TODO: treat calls to a missing default constructor as a special case
11299 const auto *FnTy
= Fn
->getType()->castAs
<FunctionProtoType
>();
11300 unsigned MinParams
= Fn
->getMinRequiredExplicitArguments();
11302 // at least / at most / exactly
11303 bool HasExplicitObjectParam
= Fn
->hasCXXExplicitFunctionObjectParameter();
11304 unsigned ParamCount
= FnTy
->getNumParams() - (HasExplicitObjectParam
? 1 : 0);
11305 unsigned mode
, modeCount
;
11306 if (NumFormalArgs
< MinParams
) {
11307 if (MinParams
!= ParamCount
|| FnTy
->isVariadic() ||
11308 FnTy
->isTemplateVariadic())
11309 mode
= 0; // "at least"
11311 mode
= 2; // "exactly"
11312 modeCount
= MinParams
;
11314 if (MinParams
!= ParamCount
)
11315 mode
= 1; // "at most"
11317 mode
= 2; // "exactly"
11318 modeCount
= ParamCount
;
11321 std::string Description
;
11322 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11323 ClassifyOverloadCandidate(S
, Found
, Fn
, CRK_None
, Description
);
11325 if (modeCount
== 1 &&
11326 Fn
->getParamDecl(HasExplicitObjectParam
? 1 : 0)->getDeclName())
11327 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_arity_one
)
11328 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
11329 << Description
<< mode
11330 << Fn
->getParamDecl(HasExplicitObjectParam
? 1 : 0) << NumFormalArgs
11331 << HasExplicitObjectParam
<< Fn
->getParametersSourceRange();
11333 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_arity
)
11334 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
11335 << Description
<< mode
<< modeCount
<< NumFormalArgs
11336 << HasExplicitObjectParam
<< Fn
->getParametersSourceRange();
11338 MaybeEmitInheritedConstructorNote(S
, Found
);
11341 /// Arity mismatch diagnosis specific to a function overload candidate.
11342 static void DiagnoseArityMismatch(Sema
&S
, OverloadCandidate
*Cand
,
11343 unsigned NumFormalArgs
) {
11344 if (!CheckArityMismatch(S
, Cand
, NumFormalArgs
))
11345 DiagnoseArityMismatch(S
, Cand
->FoundDecl
, Cand
->Function
, NumFormalArgs
);
11348 static TemplateDecl
*getDescribedTemplate(Decl
*Templated
) {
11349 if (TemplateDecl
*TD
= Templated
->getDescribedTemplate())
11351 llvm_unreachable("Unsupported: Getting the described template declaration"
11352 " for bad deduction diagnosis");
11355 /// Diagnose a failed template-argument deduction.
11356 static void DiagnoseBadDeduction(Sema
&S
, NamedDecl
*Found
, Decl
*Templated
,
11357 DeductionFailureInfo
&DeductionFailure
,
11359 bool TakingCandidateAddress
) {
11360 TemplateParameter Param
= DeductionFailure
.getTemplateParameter();
11362 (ParamD
= Param
.dyn_cast
<TemplateTypeParmDecl
*>()) ||
11363 (ParamD
= Param
.dyn_cast
<NonTypeTemplateParmDecl
*>()) ||
11364 (ParamD
= Param
.dyn_cast
<TemplateTemplateParmDecl
*>());
11365 switch (DeductionFailure
.Result
) {
11366 case Sema::TDK_Success
:
11367 llvm_unreachable("TDK_success while diagnosing bad deduction");
11369 case Sema::TDK_Incomplete
: {
11370 assert(ParamD
&& "no parameter found for incomplete deduction result");
11371 S
.Diag(Templated
->getLocation(),
11372 diag::note_ovl_candidate_incomplete_deduction
)
11373 << ParamD
->getDeclName();
11374 MaybeEmitInheritedConstructorNote(S
, Found
);
11378 case Sema::TDK_IncompletePack
: {
11379 assert(ParamD
&& "no parameter found for incomplete deduction result");
11380 S
.Diag(Templated
->getLocation(),
11381 diag::note_ovl_candidate_incomplete_deduction_pack
)
11382 << ParamD
->getDeclName()
11383 << (DeductionFailure
.getFirstArg()->pack_size() + 1)
11384 << *DeductionFailure
.getFirstArg();
11385 MaybeEmitInheritedConstructorNote(S
, Found
);
11389 case Sema::TDK_Underqualified
: {
11390 assert(ParamD
&& "no parameter found for bad qualifiers deduction result");
11391 TemplateTypeParmDecl
*TParam
= cast
<TemplateTypeParmDecl
>(ParamD
);
11393 QualType Param
= DeductionFailure
.getFirstArg()->getAsType();
11395 // Param will have been canonicalized, but it should just be a
11396 // qualified version of ParamD, so move the qualifiers to that.
11397 QualifierCollector Qs
;
11399 QualType NonCanonParam
= Qs
.apply(S
.Context
, TParam
->getTypeForDecl());
11400 assert(S
.Context
.hasSameType(Param
, NonCanonParam
));
11402 // Arg has also been canonicalized, but there's nothing we can do
11403 // about that. It also doesn't matter as much, because it won't
11404 // have any template parameters in it (because deduction isn't
11405 // done on dependent types).
11406 QualType Arg
= DeductionFailure
.getSecondArg()->getAsType();
11408 S
.Diag(Templated
->getLocation(), diag::note_ovl_candidate_underqualified
)
11409 << ParamD
->getDeclName() << Arg
<< NonCanonParam
;
11410 MaybeEmitInheritedConstructorNote(S
, Found
);
11414 case Sema::TDK_Inconsistent
: {
11415 assert(ParamD
&& "no parameter found for inconsistent deduction result");
11417 if (isa
<TemplateTypeParmDecl
>(ParamD
))
11419 else if (isa
<NonTypeTemplateParmDecl
>(ParamD
)) {
11420 // Deduction might have failed because we deduced arguments of two
11421 // different types for a non-type template parameter.
11422 // FIXME: Use a different TDK value for this.
11424 DeductionFailure
.getFirstArg()->getNonTypeTemplateArgumentType();
11426 DeductionFailure
.getSecondArg()->getNonTypeTemplateArgumentType();
11427 if (!T1
.isNull() && !T2
.isNull() && !S
.Context
.hasSameType(T1
, T2
)) {
11428 S
.Diag(Templated
->getLocation(),
11429 diag::note_ovl_candidate_inconsistent_deduction_types
)
11430 << ParamD
->getDeclName() << *DeductionFailure
.getFirstArg() << T1
11431 << *DeductionFailure
.getSecondArg() << T2
;
11432 MaybeEmitInheritedConstructorNote(S
, Found
);
11441 // Tweak the diagnostic if the problem is that we deduced packs of
11442 // different arities. We'll print the actual packs anyway in case that
11443 // includes additional useful information.
11444 if (DeductionFailure
.getFirstArg()->getKind() == TemplateArgument::Pack
&&
11445 DeductionFailure
.getSecondArg()->getKind() == TemplateArgument::Pack
&&
11446 DeductionFailure
.getFirstArg()->pack_size() !=
11447 DeductionFailure
.getSecondArg()->pack_size()) {
11451 S
.Diag(Templated
->getLocation(),
11452 diag::note_ovl_candidate_inconsistent_deduction
)
11453 << which
<< ParamD
->getDeclName() << *DeductionFailure
.getFirstArg()
11454 << *DeductionFailure
.getSecondArg();
11455 MaybeEmitInheritedConstructorNote(S
, Found
);
11459 case Sema::TDK_InvalidExplicitArguments
:
11460 assert(ParamD
&& "no parameter found for invalid explicit arguments");
11461 if (ParamD
->getDeclName())
11462 S
.Diag(Templated
->getLocation(),
11463 diag::note_ovl_candidate_explicit_arg_mismatch_named
)
11464 << ParamD
->getDeclName();
11467 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(ParamD
))
11468 index
= TTP
->getIndex();
11469 else if (NonTypeTemplateParmDecl
*NTTP
11470 = dyn_cast
<NonTypeTemplateParmDecl
>(ParamD
))
11471 index
= NTTP
->getIndex();
11473 index
= cast
<TemplateTemplateParmDecl
>(ParamD
)->getIndex();
11474 S
.Diag(Templated
->getLocation(),
11475 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed
)
11478 MaybeEmitInheritedConstructorNote(S
, Found
);
11481 case Sema::TDK_ConstraintsNotSatisfied
: {
11482 // Format the template argument list into the argument string.
11483 SmallString
<128> TemplateArgString
;
11484 TemplateArgumentList
*Args
= DeductionFailure
.getTemplateArgumentList();
11485 TemplateArgString
= " ";
11486 TemplateArgString
+= S
.getTemplateArgumentBindingsText(
11487 getDescribedTemplate(Templated
)->getTemplateParameters(), *Args
);
11488 if (TemplateArgString
.size() == 1)
11489 TemplateArgString
.clear();
11490 S
.Diag(Templated
->getLocation(),
11491 diag::note_ovl_candidate_unsatisfied_constraints
)
11492 << TemplateArgString
;
11494 S
.DiagnoseUnsatisfiedConstraint(
11495 static_cast<CNSInfo
*>(DeductionFailure
.Data
)->Satisfaction
);
11498 case Sema::TDK_TooManyArguments
:
11499 case Sema::TDK_TooFewArguments
:
11500 DiagnoseArityMismatch(S
, Found
, Templated
, NumArgs
);
11503 case Sema::TDK_InstantiationDepth
:
11504 S
.Diag(Templated
->getLocation(),
11505 diag::note_ovl_candidate_instantiation_depth
);
11506 MaybeEmitInheritedConstructorNote(S
, Found
);
11509 case Sema::TDK_SubstitutionFailure
: {
11510 // Format the template argument list into the argument string.
11511 SmallString
<128> TemplateArgString
;
11512 if (TemplateArgumentList
*Args
=
11513 DeductionFailure
.getTemplateArgumentList()) {
11514 TemplateArgString
= " ";
11515 TemplateArgString
+= S
.getTemplateArgumentBindingsText(
11516 getDescribedTemplate(Templated
)->getTemplateParameters(), *Args
);
11517 if (TemplateArgString
.size() == 1)
11518 TemplateArgString
.clear();
11521 // If this candidate was disabled by enable_if, say so.
11522 PartialDiagnosticAt
*PDiag
= DeductionFailure
.getSFINAEDiagnostic();
11523 if (PDiag
&& PDiag
->second
.getDiagID() ==
11524 diag::err_typename_nested_not_found_enable_if
) {
11525 // FIXME: Use the source range of the condition, and the fully-qualified
11526 // name of the enable_if template. These are both present in PDiag.
11527 S
.Diag(PDiag
->first
, diag::note_ovl_candidate_disabled_by_enable_if
)
11528 << "'enable_if'" << TemplateArgString
;
11532 // We found a specific requirement that disabled the enable_if.
11533 if (PDiag
&& PDiag
->second
.getDiagID() ==
11534 diag::err_typename_nested_not_found_requirement
) {
11535 S
.Diag(Templated
->getLocation(),
11536 diag::note_ovl_candidate_disabled_by_requirement
)
11537 << PDiag
->second
.getStringArg(0) << TemplateArgString
;
11541 // Format the SFINAE diagnostic into the argument string.
11542 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11543 // formatted message in another diagnostic.
11544 SmallString
<128> SFINAEArgString
;
11547 SFINAEArgString
= ": ";
11548 R
= SourceRange(PDiag
->first
, PDiag
->first
);
11549 PDiag
->second
.EmitToString(S
.getDiagnostics(), SFINAEArgString
);
11552 S
.Diag(Templated
->getLocation(),
11553 diag::note_ovl_candidate_substitution_failure
)
11554 << TemplateArgString
<< SFINAEArgString
<< R
;
11555 MaybeEmitInheritedConstructorNote(S
, Found
);
11559 case Sema::TDK_DeducedMismatch
:
11560 case Sema::TDK_DeducedMismatchNested
: {
11561 // Format the template argument list into the argument string.
11562 SmallString
<128> TemplateArgString
;
11563 if (TemplateArgumentList
*Args
=
11564 DeductionFailure
.getTemplateArgumentList()) {
11565 TemplateArgString
= " ";
11566 TemplateArgString
+= S
.getTemplateArgumentBindingsText(
11567 getDescribedTemplate(Templated
)->getTemplateParameters(), *Args
);
11568 if (TemplateArgString
.size() == 1)
11569 TemplateArgString
.clear();
11572 S
.Diag(Templated
->getLocation(), diag::note_ovl_candidate_deduced_mismatch
)
11573 << (*DeductionFailure
.getCallArgIndex() + 1)
11574 << *DeductionFailure
.getFirstArg() << *DeductionFailure
.getSecondArg()
11575 << TemplateArgString
11576 << (DeductionFailure
.Result
== Sema::TDK_DeducedMismatchNested
);
11580 case Sema::TDK_NonDeducedMismatch
: {
11581 // FIXME: Provide a source location to indicate what we couldn't match.
11582 TemplateArgument FirstTA
= *DeductionFailure
.getFirstArg();
11583 TemplateArgument SecondTA
= *DeductionFailure
.getSecondArg();
11584 if (FirstTA
.getKind() == TemplateArgument::Template
&&
11585 SecondTA
.getKind() == TemplateArgument::Template
) {
11586 TemplateName FirstTN
= FirstTA
.getAsTemplate();
11587 TemplateName SecondTN
= SecondTA
.getAsTemplate();
11588 if (FirstTN
.getKind() == TemplateName::Template
&&
11589 SecondTN
.getKind() == TemplateName::Template
) {
11590 if (FirstTN
.getAsTemplateDecl()->getName() ==
11591 SecondTN
.getAsTemplateDecl()->getName()) {
11592 // FIXME: This fixes a bad diagnostic where both templates are named
11593 // the same. This particular case is a bit difficult since:
11594 // 1) It is passed as a string to the diagnostic printer.
11595 // 2) The diagnostic printer only attempts to find a better
11596 // name for types, not decls.
11597 // Ideally, this should folded into the diagnostic printer.
11598 S
.Diag(Templated
->getLocation(),
11599 diag::note_ovl_candidate_non_deduced_mismatch_qualified
)
11600 << FirstTN
.getAsTemplateDecl() << SecondTN
.getAsTemplateDecl();
11606 if (TakingCandidateAddress
&& isa
<FunctionDecl
>(Templated
) &&
11607 !checkAddressOfCandidateIsAvailable(S
, cast
<FunctionDecl
>(Templated
)))
11610 // FIXME: For generic lambda parameters, check if the function is a lambda
11611 // call operator, and if so, emit a prettier and more informative
11612 // diagnostic that mentions 'auto' and lambda in addition to
11613 // (or instead of?) the canonical template type parameters.
11614 S
.Diag(Templated
->getLocation(),
11615 diag::note_ovl_candidate_non_deduced_mismatch
)
11616 << FirstTA
<< SecondTA
;
11619 // TODO: diagnose these individually, then kill off
11620 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11621 case Sema::TDK_MiscellaneousDeductionFailure
:
11622 S
.Diag(Templated
->getLocation(), diag::note_ovl_candidate_bad_deduction
);
11623 MaybeEmitInheritedConstructorNote(S
, Found
);
11625 case Sema::TDK_CUDATargetMismatch
:
11626 S
.Diag(Templated
->getLocation(),
11627 diag::note_cuda_ovl_candidate_target_mismatch
);
11632 /// Diagnose a failed template-argument deduction, for function calls.
11633 static void DiagnoseBadDeduction(Sema
&S
, OverloadCandidate
*Cand
,
11635 bool TakingCandidateAddress
) {
11636 unsigned TDK
= Cand
->DeductionFailure
.Result
;
11637 if (TDK
== Sema::TDK_TooFewArguments
|| TDK
== Sema::TDK_TooManyArguments
) {
11638 if (CheckArityMismatch(S
, Cand
, NumArgs
))
11641 DiagnoseBadDeduction(S
, Cand
->FoundDecl
, Cand
->Function
, // pattern
11642 Cand
->DeductionFailure
, NumArgs
, TakingCandidateAddress
);
11645 /// CUDA: diagnose an invalid call across targets.
11646 static void DiagnoseBadTarget(Sema
&S
, OverloadCandidate
*Cand
) {
11647 FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true);
11648 FunctionDecl
*Callee
= Cand
->Function
;
11650 Sema::CUDAFunctionTarget CallerTarget
= S
.IdentifyCUDATarget(Caller
),
11651 CalleeTarget
= S
.IdentifyCUDATarget(Callee
);
11653 std::string FnDesc
;
11654 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11655 ClassifyOverloadCandidate(S
, Cand
->FoundDecl
, Callee
,
11656 Cand
->getRewriteKind(), FnDesc
);
11658 S
.Diag(Callee
->getLocation(), diag::note_ovl_candidate_bad_target
)
11659 << (unsigned)FnKindPair
.first
<< (unsigned)ocs_non_template
11660 << FnDesc
/* Ignored */
11661 << CalleeTarget
<< CallerTarget
;
11663 // This could be an implicit constructor for which we could not infer the
11664 // target due to a collsion. Diagnose that case.
11665 CXXMethodDecl
*Meth
= dyn_cast
<CXXMethodDecl
>(Callee
);
11666 if (Meth
!= nullptr && Meth
->isImplicit()) {
11667 CXXRecordDecl
*ParentClass
= Meth
->getParent();
11668 Sema::CXXSpecialMember CSM
;
11670 switch (FnKindPair
.first
) {
11673 case oc_implicit_default_constructor
:
11674 CSM
= Sema::CXXDefaultConstructor
;
11676 case oc_implicit_copy_constructor
:
11677 CSM
= Sema::CXXCopyConstructor
;
11679 case oc_implicit_move_constructor
:
11680 CSM
= Sema::CXXMoveConstructor
;
11682 case oc_implicit_copy_assignment
:
11683 CSM
= Sema::CXXCopyAssignment
;
11685 case oc_implicit_move_assignment
:
11686 CSM
= Sema::CXXMoveAssignment
;
11690 bool ConstRHS
= false;
11691 if (Meth
->getNumParams()) {
11692 if (const ReferenceType
*RT
=
11693 Meth
->getParamDecl(0)->getType()->getAs
<ReferenceType
>()) {
11694 ConstRHS
= RT
->getPointeeType().isConstQualified();
11698 S
.inferCUDATargetForImplicitSpecialMember(ParentClass
, CSM
, Meth
,
11699 /* ConstRHS */ ConstRHS
,
11700 /* Diagnose */ true);
11704 static void DiagnoseFailedEnableIfAttr(Sema
&S
, OverloadCandidate
*Cand
) {
11705 FunctionDecl
*Callee
= Cand
->Function
;
11706 EnableIfAttr
*Attr
= static_cast<EnableIfAttr
*>(Cand
->DeductionFailure
.Data
);
11708 S
.Diag(Callee
->getLocation(),
11709 diag::note_ovl_candidate_disabled_by_function_cond_attr
)
11710 << Attr
->getCond()->getSourceRange() << Attr
->getMessage();
11713 static void DiagnoseFailedExplicitSpec(Sema
&S
, OverloadCandidate
*Cand
) {
11714 ExplicitSpecifier ES
= ExplicitSpecifier::getFromDecl(Cand
->Function
);
11715 assert(ES
.isExplicit() && "not an explicit candidate");
11718 switch (Cand
->Function
->getDeclKind()) {
11719 case Decl::Kind::CXXConstructor
:
11722 case Decl::Kind::CXXConversion
:
11725 case Decl::Kind::CXXDeductionGuide
:
11726 Kind
= Cand
->Function
->isImplicit() ? 0 : 2;
11729 llvm_unreachable("invalid Decl");
11732 // Note the location of the first (in-class) declaration; a redeclaration
11733 // (particularly an out-of-class definition) will typically lack the
11734 // 'explicit' specifier.
11735 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11736 FunctionDecl
*First
= Cand
->Function
->getFirstDecl();
11737 if (FunctionDecl
*Pattern
= First
->getTemplateInstantiationPattern())
11738 First
= Pattern
->getFirstDecl();
11740 S
.Diag(First
->getLocation(),
11741 diag::note_ovl_candidate_explicit
)
11742 << Kind
<< (ES
.getExpr() ? 1 : 0)
11743 << (ES
.getExpr() ? ES
.getExpr()->getSourceRange() : SourceRange());
11746 /// Generates a 'note' diagnostic for an overload candidate. We've
11747 /// already generated a primary error at the call site.
11749 /// It really does need to be a single diagnostic with its caret
11750 /// pointed at the candidate declaration. Yes, this creates some
11751 /// major challenges of technical writing. Yes, this makes pointing
11752 /// out problems with specific arguments quite awkward. It's still
11753 /// better than generating twenty screens of text for every failed
11756 /// It would be great to be able to express per-candidate problems
11757 /// more richly for those diagnostic clients that cared, but we'd
11758 /// still have to be just as careful with the default diagnostics.
11759 /// \param CtorDestAS Addr space of object being constructed (for ctor
11760 /// candidates only).
11761 static void NoteFunctionCandidate(Sema
&S
, OverloadCandidate
*Cand
,
11763 bool TakingCandidateAddress
,
11764 LangAS CtorDestAS
= LangAS::Default
) {
11765 FunctionDecl
*Fn
= Cand
->Function
;
11766 if (shouldSkipNotingLambdaConversionDecl(Fn
))
11769 // There is no physical candidate declaration to point to for OpenCL builtins.
11770 // Except for failed conversions, the notes are identical for each candidate,
11771 // so do not generate such notes.
11772 if (S
.getLangOpts().OpenCL
&& Fn
->isImplicit() &&
11773 Cand
->FailureKind
!= ovl_fail_bad_conversion
)
11776 // Note deleted candidates, but only if they're viable.
11777 if (Cand
->Viable
) {
11778 if (Fn
->isDeleted()) {
11779 std::string FnDesc
;
11780 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11781 ClassifyOverloadCandidate(S
, Cand
->FoundDecl
, Fn
,
11782 Cand
->getRewriteKind(), FnDesc
);
11784 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_deleted
)
11785 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11786 << (Fn
->isDeleted() ? (Fn
->isDeletedAsWritten() ? 1 : 2) : 0);
11787 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11791 // We don't really have anything else to say about viable candidates.
11792 S
.NoteOverloadCandidate(Cand
->FoundDecl
, Fn
, Cand
->getRewriteKind());
11796 switch (Cand
->FailureKind
) {
11797 case ovl_fail_too_many_arguments
:
11798 case ovl_fail_too_few_arguments
:
11799 return DiagnoseArityMismatch(S
, Cand
, NumArgs
);
11801 case ovl_fail_bad_deduction
:
11802 return DiagnoseBadDeduction(S
, Cand
, NumArgs
,
11803 TakingCandidateAddress
);
11805 case ovl_fail_illegal_constructor
: {
11806 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_illegal_constructor
)
11807 << (Fn
->getPrimaryTemplate() ? 1 : 0);
11808 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11812 case ovl_fail_object_addrspace_mismatch
: {
11813 Qualifiers QualsForPrinting
;
11814 QualsForPrinting
.setAddressSpace(CtorDestAS
);
11815 S
.Diag(Fn
->getLocation(),
11816 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch
)
11817 << QualsForPrinting
;
11818 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11822 case ovl_fail_trivial_conversion
:
11823 case ovl_fail_bad_final_conversion
:
11824 case ovl_fail_final_conversion_not_exact
:
11825 return S
.NoteOverloadCandidate(Cand
->FoundDecl
, Fn
, Cand
->getRewriteKind());
11827 case ovl_fail_bad_conversion
: {
11828 unsigned I
= (Cand
->IgnoreObjectArgument
? 1 : 0);
11829 for (unsigned N
= Cand
->Conversions
.size(); I
!= N
; ++I
)
11830 if (Cand
->Conversions
[I
].isBad())
11831 return DiagnoseBadConversion(S
, Cand
, I
, TakingCandidateAddress
);
11833 // FIXME: this currently happens when we're called from SemaInit
11834 // when user-conversion overload fails. Figure out how to handle
11835 // those conditions and diagnose them well.
11836 return S
.NoteOverloadCandidate(Cand
->FoundDecl
, Fn
, Cand
->getRewriteKind());
11839 case ovl_fail_bad_target
:
11840 return DiagnoseBadTarget(S
, Cand
);
11842 case ovl_fail_enable_if
:
11843 return DiagnoseFailedEnableIfAttr(S
, Cand
);
11845 case ovl_fail_explicit
:
11846 return DiagnoseFailedExplicitSpec(S
, Cand
);
11848 case ovl_fail_inhctor_slice
:
11849 // It's generally not interesting to note copy/move constructors here.
11850 if (cast
<CXXConstructorDecl
>(Fn
)->isCopyOrMoveConstructor())
11852 S
.Diag(Fn
->getLocation(),
11853 diag::note_ovl_candidate_inherited_constructor_slice
)
11854 << (Fn
->getPrimaryTemplate() ? 1 : 0)
11855 << Fn
->getParamDecl(0)->getType()->isRValueReferenceType();
11856 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11859 case ovl_fail_addr_not_available
: {
11860 bool Available
= checkAddressOfCandidateIsAvailable(S
, Cand
->Function
);
11862 assert(!Available
);
11865 case ovl_non_default_multiversion_function
:
11866 // Do nothing, these should simply be ignored.
11869 case ovl_fail_constraints_not_satisfied
: {
11870 std::string FnDesc
;
11871 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11872 ClassifyOverloadCandidate(S
, Cand
->FoundDecl
, Fn
,
11873 Cand
->getRewriteKind(), FnDesc
);
11875 S
.Diag(Fn
->getLocation(),
11876 diag::note_ovl_candidate_constraints_not_satisfied
)
11877 << (unsigned)FnKindPair
.first
<< (unsigned)ocs_non_template
11878 << FnDesc
/* Ignored */;
11879 ConstraintSatisfaction Satisfaction
;
11880 if (S
.CheckFunctionConstraints(Fn
, Satisfaction
))
11882 S
.DiagnoseUnsatisfiedConstraint(Satisfaction
);
11887 static void NoteSurrogateCandidate(Sema
&S
, OverloadCandidate
*Cand
) {
11888 if (shouldSkipNotingLambdaConversionDecl(Cand
->Surrogate
))
11891 // Desugar the type of the surrogate down to a function type,
11892 // retaining as many typedefs as possible while still showing
11893 // the function type (and, therefore, its parameter types).
11894 QualType FnType
= Cand
->Surrogate
->getConversionType();
11895 bool isLValueReference
= false;
11896 bool isRValueReference
= false;
11897 bool isPointer
= false;
11898 if (const LValueReferenceType
*FnTypeRef
=
11899 FnType
->getAs
<LValueReferenceType
>()) {
11900 FnType
= FnTypeRef
->getPointeeType();
11901 isLValueReference
= true;
11902 } else if (const RValueReferenceType
*FnTypeRef
=
11903 FnType
->getAs
<RValueReferenceType
>()) {
11904 FnType
= FnTypeRef
->getPointeeType();
11905 isRValueReference
= true;
11907 if (const PointerType
*FnTypePtr
= FnType
->getAs
<PointerType
>()) {
11908 FnType
= FnTypePtr
->getPointeeType();
11911 // Desugar down to a function type.
11912 FnType
= QualType(FnType
->getAs
<FunctionType
>(), 0);
11913 // Reconstruct the pointer/reference as appropriate.
11914 if (isPointer
) FnType
= S
.Context
.getPointerType(FnType
);
11915 if (isRValueReference
) FnType
= S
.Context
.getRValueReferenceType(FnType
);
11916 if (isLValueReference
) FnType
= S
.Context
.getLValueReferenceType(FnType
);
11918 if (!Cand
->Viable
&&
11919 Cand
->FailureKind
== ovl_fail_constraints_not_satisfied
) {
11920 S
.Diag(Cand
->Surrogate
->getLocation(),
11921 diag::note_ovl_surrogate_constraints_not_satisfied
)
11922 << Cand
->Surrogate
;
11923 ConstraintSatisfaction Satisfaction
;
11924 if (S
.CheckFunctionConstraints(Cand
->Surrogate
, Satisfaction
))
11925 S
.DiagnoseUnsatisfiedConstraint(Satisfaction
);
11927 S
.Diag(Cand
->Surrogate
->getLocation(), diag::note_ovl_surrogate_cand
)
11932 static void NoteBuiltinOperatorCandidate(Sema
&S
, StringRef Opc
,
11933 SourceLocation OpLoc
,
11934 OverloadCandidate
*Cand
) {
11935 assert(Cand
->Conversions
.size() <= 2 && "builtin operator is not binary");
11936 std::string
TypeStr("operator");
11939 TypeStr
+= Cand
->BuiltinParamTypes
[0].getAsString();
11940 if (Cand
->Conversions
.size() == 1) {
11942 S
.Diag(OpLoc
, diag::note_ovl_builtin_candidate
) << TypeStr
;
11945 TypeStr
+= Cand
->BuiltinParamTypes
[1].getAsString();
11947 S
.Diag(OpLoc
, diag::note_ovl_builtin_candidate
) << TypeStr
;
11951 static void NoteAmbiguousUserConversions(Sema
&S
, SourceLocation OpLoc
,
11952 OverloadCandidate
*Cand
) {
11953 for (const ImplicitConversionSequence
&ICS
: Cand
->Conversions
) {
11954 if (ICS
.isBad()) break; // all meaningless after first invalid
11955 if (!ICS
.isAmbiguous()) continue;
11957 ICS
.DiagnoseAmbiguousConversion(
11958 S
, OpLoc
, S
.PDiag(diag::note_ambiguous_type_conversion
));
11962 static SourceLocation
GetLocationForCandidate(const OverloadCandidate
*Cand
) {
11963 if (Cand
->Function
)
11964 return Cand
->Function
->getLocation();
11965 if (Cand
->IsSurrogate
)
11966 return Cand
->Surrogate
->getLocation();
11967 return SourceLocation();
11970 static unsigned RankDeductionFailure(const DeductionFailureInfo
&DFI
) {
11971 switch ((Sema::TemplateDeductionResult
)DFI
.Result
) {
11972 case Sema::TDK_Success
:
11973 case Sema::TDK_NonDependentConversionFailure
:
11974 case Sema::TDK_AlreadyDiagnosed
:
11975 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11977 case Sema::TDK_Invalid
:
11978 case Sema::TDK_Incomplete
:
11979 case Sema::TDK_IncompletePack
:
11982 case Sema::TDK_Underqualified
:
11983 case Sema::TDK_Inconsistent
:
11986 case Sema::TDK_SubstitutionFailure
:
11987 case Sema::TDK_DeducedMismatch
:
11988 case Sema::TDK_ConstraintsNotSatisfied
:
11989 case Sema::TDK_DeducedMismatchNested
:
11990 case Sema::TDK_NonDeducedMismatch
:
11991 case Sema::TDK_MiscellaneousDeductionFailure
:
11992 case Sema::TDK_CUDATargetMismatch
:
11995 case Sema::TDK_InstantiationDepth
:
11998 case Sema::TDK_InvalidExplicitArguments
:
12001 case Sema::TDK_TooManyArguments
:
12002 case Sema::TDK_TooFewArguments
:
12005 llvm_unreachable("Unhandled deduction result");
12010 struct CompareOverloadCandidatesForDisplay
{
12012 SourceLocation Loc
;
12014 OverloadCandidateSet::CandidateSetKind CSK
;
12016 CompareOverloadCandidatesForDisplay(
12017 Sema
&S
, SourceLocation Loc
, size_t NArgs
,
12018 OverloadCandidateSet::CandidateSetKind CSK
)
12019 : S(S
), NumArgs(NArgs
), CSK(CSK
) {}
12021 OverloadFailureKind
EffectiveFailureKind(const OverloadCandidate
*C
) const {
12022 // If there are too many or too few arguments, that's the high-order bit we
12023 // want to sort by, even if the immediate failure kind was something else.
12024 if (C
->FailureKind
== ovl_fail_too_many_arguments
||
12025 C
->FailureKind
== ovl_fail_too_few_arguments
)
12026 return static_cast<OverloadFailureKind
>(C
->FailureKind
);
12029 if (NumArgs
> C
->Function
->getNumParams() && !C
->Function
->isVariadic())
12030 return ovl_fail_too_many_arguments
;
12031 if (NumArgs
< C
->Function
->getMinRequiredArguments())
12032 return ovl_fail_too_few_arguments
;
12035 return static_cast<OverloadFailureKind
>(C
->FailureKind
);
12038 bool operator()(const OverloadCandidate
*L
,
12039 const OverloadCandidate
*R
) {
12040 // Fast-path this check.
12041 if (L
== R
) return false;
12043 // Order first by viability.
12045 if (!R
->Viable
) return true;
12047 if (int Ord
= CompareConversions(*L
, *R
))
12049 // Use other tie breakers.
12050 } else if (R
->Viable
)
12053 assert(L
->Viable
== R
->Viable
);
12055 // Criteria by which we can sort non-viable candidates:
12057 OverloadFailureKind LFailureKind
= EffectiveFailureKind(L
);
12058 OverloadFailureKind RFailureKind
= EffectiveFailureKind(R
);
12060 // 1. Arity mismatches come after other candidates.
12061 if (LFailureKind
== ovl_fail_too_many_arguments
||
12062 LFailureKind
== ovl_fail_too_few_arguments
) {
12063 if (RFailureKind
== ovl_fail_too_many_arguments
||
12064 RFailureKind
== ovl_fail_too_few_arguments
) {
12065 int LDist
= std::abs((int)L
->getNumParams() - (int)NumArgs
);
12066 int RDist
= std::abs((int)R
->getNumParams() - (int)NumArgs
);
12067 if (LDist
== RDist
) {
12068 if (LFailureKind
== RFailureKind
)
12069 // Sort non-surrogates before surrogates.
12070 return !L
->IsSurrogate
&& R
->IsSurrogate
;
12071 // Sort candidates requiring fewer parameters than there were
12072 // arguments given after candidates requiring more parameters
12073 // than there were arguments given.
12074 return LFailureKind
== ovl_fail_too_many_arguments
;
12076 return LDist
< RDist
;
12080 if (RFailureKind
== ovl_fail_too_many_arguments
||
12081 RFailureKind
== ovl_fail_too_few_arguments
)
12084 // 2. Bad conversions come first and are ordered by the number
12085 // of bad conversions and quality of good conversions.
12086 if (LFailureKind
== ovl_fail_bad_conversion
) {
12087 if (RFailureKind
!= ovl_fail_bad_conversion
)
12090 // The conversion that can be fixed with a smaller number of changes,
12092 unsigned numLFixes
= L
->Fix
.NumConversionsFixed
;
12093 unsigned numRFixes
= R
->Fix
.NumConversionsFixed
;
12094 numLFixes
= (numLFixes
== 0) ? UINT_MAX
: numLFixes
;
12095 numRFixes
= (numRFixes
== 0) ? UINT_MAX
: numRFixes
;
12096 if (numLFixes
!= numRFixes
) {
12097 return numLFixes
< numRFixes
;
12100 // If there's any ordering between the defined conversions...
12101 if (int Ord
= CompareConversions(*L
, *R
))
12103 } else if (RFailureKind
== ovl_fail_bad_conversion
)
12106 if (LFailureKind
== ovl_fail_bad_deduction
) {
12107 if (RFailureKind
!= ovl_fail_bad_deduction
)
12110 if (L
->DeductionFailure
.Result
!= R
->DeductionFailure
.Result
)
12111 return RankDeductionFailure(L
->DeductionFailure
)
12112 < RankDeductionFailure(R
->DeductionFailure
);
12113 } else if (RFailureKind
== ovl_fail_bad_deduction
)
12119 // Sort everything else by location.
12120 SourceLocation LLoc
= GetLocationForCandidate(L
);
12121 SourceLocation RLoc
= GetLocationForCandidate(R
);
12123 // Put candidates without locations (e.g. builtins) at the end.
12124 if (LLoc
.isValid() && RLoc
.isValid())
12125 return S
.SourceMgr
.isBeforeInTranslationUnit(LLoc
, RLoc
);
12126 if (LLoc
.isValid() && !RLoc
.isValid())
12128 if (RLoc
.isValid() && !LLoc
.isValid())
12130 assert(!LLoc
.isValid() && !RLoc
.isValid());
12131 // For builtins and other functions without locations, fallback to the order
12132 // in which they were added into the candidate set.
12137 struct ConversionSignals
{
12138 unsigned KindRank
= 0;
12139 ImplicitConversionRank Rank
= ICR_Exact_Match
;
12141 static ConversionSignals
ForSequence(ImplicitConversionSequence
&Seq
) {
12142 ConversionSignals Sig
;
12143 Sig
.KindRank
= Seq
.getKindRank();
12144 if (Seq
.isStandard())
12145 Sig
.Rank
= Seq
.Standard
.getRank();
12146 else if (Seq
.isUserDefined())
12147 Sig
.Rank
= Seq
.UserDefined
.After
.getRank();
12148 // We intend StaticObjectArgumentConversion to compare the same as
12149 // StandardConversion with ICR_ExactMatch rank.
12153 static ConversionSignals
ForObjectArgument() {
12154 // We intend StaticObjectArgumentConversion to compare the same as
12155 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12160 // Returns -1 if conversions in L are considered better.
12161 // 0 if they are considered indistinguishable.
12162 // 1 if conversions in R are better.
12163 int CompareConversions(const OverloadCandidate
&L
,
12164 const OverloadCandidate
&R
) {
12165 // We cannot use `isBetterOverloadCandidate` because it is defined
12166 // according to the C++ standard and provides a partial order, but we need
12167 // a total order as this function is used in sort.
12168 assert(L
.Conversions
.size() == R
.Conversions
.size());
12169 for (unsigned I
= 0, N
= L
.Conversions
.size(); I
!= N
; ++I
) {
12170 auto LS
= L
.IgnoreObjectArgument
&& I
== 0
12171 ? ConversionSignals::ForObjectArgument()
12172 : ConversionSignals::ForSequence(L
.Conversions
[I
]);
12173 auto RS
= R
.IgnoreObjectArgument
12174 ? ConversionSignals::ForObjectArgument()
12175 : ConversionSignals::ForSequence(R
.Conversions
[I
]);
12176 if (std::tie(LS
.KindRank
, LS
.Rank
) != std::tie(RS
.KindRank
, RS
.Rank
))
12177 return std::tie(LS
.KindRank
, LS
.Rank
) < std::tie(RS
.KindRank
, RS
.Rank
)
12181 // FIXME: find a way to compare templates for being more or less
12182 // specialized that provides a strict weak ordering.
12188 /// CompleteNonViableCandidate - Normally, overload resolution only
12189 /// computes up to the first bad conversion. Produces the FixIt set if
12192 CompleteNonViableCandidate(Sema
&S
, OverloadCandidate
*Cand
,
12193 ArrayRef
<Expr
*> Args
,
12194 OverloadCandidateSet::CandidateSetKind CSK
) {
12195 assert(!Cand
->Viable
);
12197 // Don't do anything on failures other than bad conversion.
12198 if (Cand
->FailureKind
!= ovl_fail_bad_conversion
)
12201 // We only want the FixIts if all the arguments can be corrected.
12202 bool Unfixable
= false;
12203 // Use a implicit copy initialization to check conversion fixes.
12204 Cand
->Fix
.setConversionChecker(TryCopyInitialization
);
12206 // Attempt to fix the bad conversion.
12207 unsigned ConvCount
= Cand
->Conversions
.size();
12208 for (unsigned ConvIdx
= (Cand
->IgnoreObjectArgument
? 1 : 0); /**/;
12210 assert(ConvIdx
!= ConvCount
&& "no bad conversion in candidate");
12211 if (Cand
->Conversions
[ConvIdx
].isInitialized() &&
12212 Cand
->Conversions
[ConvIdx
].isBad()) {
12213 Unfixable
= !Cand
->TryToFixBadConversion(ConvIdx
, S
);
12218 // FIXME: this should probably be preserved from the overload
12219 // operation somehow.
12220 bool SuppressUserConversions
= false;
12222 unsigned ConvIdx
= 0;
12223 unsigned ArgIdx
= 0;
12224 ArrayRef
<QualType
> ParamTypes
;
12225 bool Reversed
= Cand
->isReversed();
12227 if (Cand
->IsSurrogate
) {
12229 = Cand
->Surrogate
->getConversionType().getNonReferenceType();
12230 if (const PointerType
*ConvPtrType
= ConvType
->getAs
<PointerType
>())
12231 ConvType
= ConvPtrType
->getPointeeType();
12232 ParamTypes
= ConvType
->castAs
<FunctionProtoType
>()->getParamTypes();
12233 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12235 } else if (Cand
->Function
) {
12237 Cand
->Function
->getType()->castAs
<FunctionProtoType
>()->getParamTypes();
12238 if (isa
<CXXMethodDecl
>(Cand
->Function
) &&
12239 !isa
<CXXConstructorDecl
>(Cand
->Function
) && !Reversed
) {
12240 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12242 if (CSK
== OverloadCandidateSet::CSK_Operator
&&
12243 Cand
->Function
->getDeclName().getCXXOverloadedOperator() != OO_Call
&&
12244 Cand
->Function
->getDeclName().getCXXOverloadedOperator() !=
12246 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12250 // Builtin operator.
12251 assert(ConvCount
<= 3);
12252 ParamTypes
= Cand
->BuiltinParamTypes
;
12255 // Fill in the rest of the conversions.
12256 for (unsigned ParamIdx
= Reversed
? ParamTypes
.size() - 1 : 0;
12257 ConvIdx
!= ConvCount
;
12258 ++ConvIdx
, ++ArgIdx
, ParamIdx
+= (Reversed
? -1 : 1)) {
12259 assert(ArgIdx
< Args
.size() && "no argument for this arg conversion");
12260 if (Cand
->Conversions
[ConvIdx
].isInitialized()) {
12261 // We've already checked this conversion.
12262 } else if (ParamIdx
< ParamTypes
.size()) {
12263 if (ParamTypes
[ParamIdx
]->isDependentType())
12264 Cand
->Conversions
[ConvIdx
].setAsIdentityConversion(
12265 Args
[ArgIdx
]->getType());
12267 Cand
->Conversions
[ConvIdx
] =
12268 TryCopyInitialization(S
, Args
[ArgIdx
], ParamTypes
[ParamIdx
],
12269 SuppressUserConversions
,
12270 /*InOverloadResolution=*/true,
12271 /*AllowObjCWritebackConversion=*/
12272 S
.getLangOpts().ObjCAutoRefCount
);
12273 // Store the FixIt in the candidate if it exists.
12274 if (!Unfixable
&& Cand
->Conversions
[ConvIdx
].isBad())
12275 Unfixable
= !Cand
->TryToFixBadConversion(ConvIdx
, S
);
12278 Cand
->Conversions
[ConvIdx
].setEllipsis();
12282 SmallVector
<OverloadCandidate
*, 32> OverloadCandidateSet::CompleteCandidates(
12283 Sema
&S
, OverloadCandidateDisplayKind OCD
, ArrayRef
<Expr
*> Args
,
12284 SourceLocation OpLoc
,
12285 llvm::function_ref
<bool(OverloadCandidate
&)> Filter
) {
12286 // Sort the candidates by viability and position. Sorting directly would
12287 // be prohibitive, so we make a set of pointers and sort those.
12288 SmallVector
<OverloadCandidate
*, 32> Cands
;
12289 if (OCD
== OCD_AllCandidates
) Cands
.reserve(size());
12290 for (iterator Cand
= begin(), LastCand
= end(); Cand
!= LastCand
; ++Cand
) {
12291 if (!Filter(*Cand
))
12294 case OCD_AllCandidates
:
12295 if (!Cand
->Viable
) {
12296 if (!Cand
->Function
&& !Cand
->IsSurrogate
) {
12297 // This a non-viable builtin candidate. We do not, in general,
12298 // want to list every possible builtin candidate.
12301 CompleteNonViableCandidate(S
, Cand
, Args
, Kind
);
12305 case OCD_ViableCandidates
:
12310 case OCD_AmbiguousCandidates
:
12316 Cands
.push_back(Cand
);
12320 Cands
, CompareOverloadCandidatesForDisplay(S
, OpLoc
, Args
.size(), Kind
));
12325 bool OverloadCandidateSet::shouldDeferDiags(Sema
&S
, ArrayRef
<Expr
*> Args
,
12326 SourceLocation OpLoc
) {
12327 bool DeferHint
= false;
12328 if (S
.getLangOpts().CUDA
&& S
.getLangOpts().GPUDeferDiag
) {
12329 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12330 // host device candidates.
12331 auto WrongSidedCands
=
12332 CompleteCandidates(S
, OCD_AllCandidates
, Args
, OpLoc
, [](auto &Cand
) {
12333 return (Cand
.Viable
== false &&
12334 Cand
.FailureKind
== ovl_fail_bad_target
) ||
12336 Cand
.Function
->template hasAttr
<CUDAHostAttr
>() &&
12337 Cand
.Function
->template hasAttr
<CUDADeviceAttr
>());
12339 DeferHint
= !WrongSidedCands
.empty();
12344 /// When overload resolution fails, prints diagnostic messages containing the
12345 /// candidates in the candidate set.
12346 void OverloadCandidateSet::NoteCandidates(
12347 PartialDiagnosticAt PD
, Sema
&S
, OverloadCandidateDisplayKind OCD
,
12348 ArrayRef
<Expr
*> Args
, StringRef Opc
, SourceLocation OpLoc
,
12349 llvm::function_ref
<bool(OverloadCandidate
&)> Filter
) {
12351 auto Cands
= CompleteCandidates(S
, OCD
, Args
, OpLoc
, Filter
);
12353 S
.Diag(PD
.first
, PD
.second
, shouldDeferDiags(S
, Args
, OpLoc
));
12355 // In WebAssembly we don't want to emit further diagnostics if a table is
12356 // passed as an argument to a function.
12357 bool NoteCands
= true;
12358 for (const Expr
*Arg
: Args
) {
12359 if (Arg
->getType()->isWebAssemblyTableType())
12364 NoteCandidates(S
, Args
, Cands
, Opc
, OpLoc
);
12366 if (OCD
== OCD_AmbiguousCandidates
)
12367 MaybeDiagnoseAmbiguousConstraints(S
, {begin(), end()});
12370 void OverloadCandidateSet::NoteCandidates(Sema
&S
, ArrayRef
<Expr
*> Args
,
12371 ArrayRef
<OverloadCandidate
*> Cands
,
12372 StringRef Opc
, SourceLocation OpLoc
) {
12373 bool ReportedAmbiguousConversions
= false;
12375 const OverloadsShown ShowOverloads
= S
.Diags
.getShowOverloads();
12376 unsigned CandsShown
= 0;
12377 auto I
= Cands
.begin(), E
= Cands
.end();
12378 for (; I
!= E
; ++I
) {
12379 OverloadCandidate
*Cand
= *I
;
12381 if (CandsShown
>= S
.Diags
.getNumOverloadCandidatesToShow() &&
12382 ShowOverloads
== Ovl_Best
) {
12387 if (Cand
->Function
)
12388 NoteFunctionCandidate(S
, Cand
, Args
.size(),
12389 /*TakingCandidateAddress=*/false, DestAS
);
12390 else if (Cand
->IsSurrogate
)
12391 NoteSurrogateCandidate(S
, Cand
);
12393 assert(Cand
->Viable
&&
12394 "Non-viable built-in candidates are not added to Cands.");
12395 // Generally we only see ambiguities including viable builtin
12396 // operators if overload resolution got screwed up by an
12397 // ambiguous user-defined conversion.
12399 // FIXME: It's quite possible for different conversions to see
12400 // different ambiguities, though.
12401 if (!ReportedAmbiguousConversions
) {
12402 NoteAmbiguousUserConversions(S
, OpLoc
, Cand
);
12403 ReportedAmbiguousConversions
= true;
12406 // If this is a viable builtin, print it.
12407 NoteBuiltinOperatorCandidate(S
, Opc
, OpLoc
, Cand
);
12411 // Inform S.Diags that we've shown an overload set with N elements. This may
12412 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12413 S
.Diags
.overloadCandidatesShown(CandsShown
);
12416 S
.Diag(OpLoc
, diag::note_ovl_too_many_candidates
,
12417 shouldDeferDiags(S
, Args
, OpLoc
))
12421 static SourceLocation
12422 GetLocationForCandidate(const TemplateSpecCandidate
*Cand
) {
12423 return Cand
->Specialization
? Cand
->Specialization
->getLocation()
12424 : SourceLocation();
12428 struct CompareTemplateSpecCandidatesForDisplay
{
12430 CompareTemplateSpecCandidatesForDisplay(Sema
&S
) : S(S
) {}
12432 bool operator()(const TemplateSpecCandidate
*L
,
12433 const TemplateSpecCandidate
*R
) {
12434 // Fast-path this check.
12438 // Assuming that both candidates are not matches...
12440 // Sort by the ranking of deduction failures.
12441 if (L
->DeductionFailure
.Result
!= R
->DeductionFailure
.Result
)
12442 return RankDeductionFailure(L
->DeductionFailure
) <
12443 RankDeductionFailure(R
->DeductionFailure
);
12445 // Sort everything else by location.
12446 SourceLocation LLoc
= GetLocationForCandidate(L
);
12447 SourceLocation RLoc
= GetLocationForCandidate(R
);
12449 // Put candidates without locations (e.g. builtins) at the end.
12450 if (LLoc
.isInvalid())
12452 if (RLoc
.isInvalid())
12455 return S
.SourceMgr
.isBeforeInTranslationUnit(LLoc
, RLoc
);
12460 /// Diagnose a template argument deduction failure.
12461 /// We are treating these failures as overload failures due to bad
12463 void TemplateSpecCandidate::NoteDeductionFailure(Sema
&S
,
12464 bool ForTakingAddress
) {
12465 DiagnoseBadDeduction(S
, FoundDecl
, Specialization
, // pattern
12466 DeductionFailure
, /*NumArgs=*/0, ForTakingAddress
);
12469 void TemplateSpecCandidateSet::destroyCandidates() {
12470 for (iterator i
= begin(), e
= end(); i
!= e
; ++i
) {
12471 i
->DeductionFailure
.Destroy();
12475 void TemplateSpecCandidateSet::clear() {
12476 destroyCandidates();
12477 Candidates
.clear();
12480 /// NoteCandidates - When no template specialization match is found, prints
12481 /// diagnostic messages containing the non-matching specializations that form
12482 /// the candidate set.
12483 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12484 /// OCD == OCD_AllCandidates and Cand->Viable == false.
12485 void TemplateSpecCandidateSet::NoteCandidates(Sema
&S
, SourceLocation Loc
) {
12486 // Sort the candidates by position (assuming no candidate is a match).
12487 // Sorting directly would be prohibitive, so we make a set of pointers
12489 SmallVector
<TemplateSpecCandidate
*, 32> Cands
;
12490 Cands
.reserve(size());
12491 for (iterator Cand
= begin(), LastCand
= end(); Cand
!= LastCand
; ++Cand
) {
12492 if (Cand
->Specialization
)
12493 Cands
.push_back(Cand
);
12494 // Otherwise, this is a non-matching builtin candidate. We do not,
12495 // in general, want to list every possible builtin candidate.
12498 llvm::sort(Cands
, CompareTemplateSpecCandidatesForDisplay(S
));
12500 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12501 // for generalization purposes (?).
12502 const OverloadsShown ShowOverloads
= S
.Diags
.getShowOverloads();
12504 SmallVectorImpl
<TemplateSpecCandidate
*>::iterator I
, E
;
12505 unsigned CandsShown
= 0;
12506 for (I
= Cands
.begin(), E
= Cands
.end(); I
!= E
; ++I
) {
12507 TemplateSpecCandidate
*Cand
= *I
;
12509 // Set an arbitrary limit on the number of candidates we'll spam
12510 // the user with. FIXME: This limit should depend on details of the
12512 if (CandsShown
>= 4 && ShowOverloads
== Ovl_Best
)
12516 assert(Cand
->Specialization
&&
12517 "Non-matching built-in candidates are not added to Cands.");
12518 Cand
->NoteDeductionFailure(S
, ForTakingAddress
);
12522 S
.Diag(Loc
, diag::note_ovl_too_many_candidates
) << int(E
- I
);
12525 // [PossiblyAFunctionType] --> [Return]
12526 // NonFunctionType --> NonFunctionType
12528 // R (*)(A) --> R (A)
12529 // R (&)(A) --> R (A)
12530 // R (S::*)(A) --> R (A)
12531 QualType
Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType
) {
12532 QualType Ret
= PossiblyAFunctionType
;
12533 if (const PointerType
*ToTypePtr
=
12534 PossiblyAFunctionType
->getAs
<PointerType
>())
12535 Ret
= ToTypePtr
->getPointeeType();
12536 else if (const ReferenceType
*ToTypeRef
=
12537 PossiblyAFunctionType
->getAs
<ReferenceType
>())
12538 Ret
= ToTypeRef
->getPointeeType();
12539 else if (const MemberPointerType
*MemTypePtr
=
12540 PossiblyAFunctionType
->getAs
<MemberPointerType
>())
12541 Ret
= MemTypePtr
->getPointeeType();
12543 Context
.getCanonicalType(Ret
).getUnqualifiedType();
12547 static bool completeFunctionType(Sema
&S
, FunctionDecl
*FD
, SourceLocation Loc
,
12548 bool Complain
= true) {
12549 if (S
.getLangOpts().CPlusPlus14
&& FD
->getReturnType()->isUndeducedType() &&
12550 S
.DeduceReturnType(FD
, Loc
, Complain
))
12553 auto *FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
12554 if (S
.getLangOpts().CPlusPlus17
&&
12555 isUnresolvedExceptionSpec(FPT
->getExceptionSpecType()) &&
12556 !S
.ResolveExceptionSpec(Loc
, FPT
))
12563 // A helper class to help with address of function resolution
12564 // - allows us to avoid passing around all those ugly parameters
12565 class AddressOfFunctionResolver
{
12568 const QualType
& TargetType
;
12569 QualType TargetFunctionType
; // Extracted function type from target type
12572 //DeclAccessPair& ResultFunctionAccessPair;
12573 ASTContext
& Context
;
12575 bool TargetTypeIsNonStaticMemberFunction
;
12576 bool FoundNonTemplateFunction
;
12577 bool StaticMemberFunctionFromBoundPointer
;
12578 bool HasComplained
;
12580 OverloadExpr::FindResult OvlExprInfo
;
12581 OverloadExpr
*OvlExpr
;
12582 TemplateArgumentListInfo OvlExplicitTemplateArgs
;
12583 SmallVector
<std::pair
<DeclAccessPair
, FunctionDecl
*>, 4> Matches
;
12584 TemplateSpecCandidateSet FailedCandidates
;
12587 AddressOfFunctionResolver(Sema
&S
, Expr
*SourceExpr
,
12588 const QualType
&TargetType
, bool Complain
)
12589 : S(S
), SourceExpr(SourceExpr
), TargetType(TargetType
),
12590 Complain(Complain
), Context(S
.getASTContext()),
12591 TargetTypeIsNonStaticMemberFunction(
12592 !!TargetType
->getAs
<MemberPointerType
>()),
12593 FoundNonTemplateFunction(false),
12594 StaticMemberFunctionFromBoundPointer(false),
12595 HasComplained(false),
12596 OvlExprInfo(OverloadExpr::find(SourceExpr
)),
12597 OvlExpr(OvlExprInfo
.Expression
),
12598 FailedCandidates(OvlExpr
->getNameLoc(), /*ForTakingAddress=*/true) {
12599 ExtractUnqualifiedFunctionTypeFromTargetType();
12601 if (TargetFunctionType
->isFunctionType()) {
12602 if (UnresolvedMemberExpr
*UME
= dyn_cast
<UnresolvedMemberExpr
>(OvlExpr
))
12603 if (!UME
->isImplicitAccess() &&
12604 !S
.ResolveSingleFunctionTemplateSpecialization(UME
))
12605 StaticMemberFunctionFromBoundPointer
= true;
12606 } else if (OvlExpr
->hasExplicitTemplateArgs()) {
12607 DeclAccessPair dap
;
12608 if (FunctionDecl
*Fn
= S
.ResolveSingleFunctionTemplateSpecialization(
12609 OvlExpr
, false, &dap
)) {
12610 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
))
12611 if (!Method
->isStatic()) {
12612 // If the target type is a non-function type and the function found
12613 // is a non-static member function, pretend as if that was the
12614 // target, it's the only possible type to end up with.
12615 TargetTypeIsNonStaticMemberFunction
= true;
12617 // And skip adding the function if its not in the proper form.
12618 // We'll diagnose this due to an empty set of functions.
12619 if (!OvlExprInfo
.HasFormOfMemberPointer
)
12623 Matches
.push_back(std::make_pair(dap
, Fn
));
12628 if (OvlExpr
->hasExplicitTemplateArgs())
12629 OvlExpr
->copyTemplateArgumentsInto(OvlExplicitTemplateArgs
);
12631 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12632 // C++ [over.over]p4:
12633 // If more than one function is selected, [...]
12634 if (Matches
.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12635 if (FoundNonTemplateFunction
)
12636 EliminateAllTemplateMatches();
12638 EliminateAllExceptMostSpecializedTemplate();
12642 if (S
.getLangOpts().CUDA
&& Matches
.size() > 1)
12643 EliminateSuboptimalCudaMatches();
12646 bool hasComplained() const { return HasComplained
; }
12649 bool candidateHasExactlyCorrectType(const FunctionDecl
*FD
) {
12651 return Context
.hasSameUnqualifiedType(TargetFunctionType
, FD
->getType()) ||
12652 S
.IsFunctionConversion(FD
->getType(), TargetFunctionType
, Discard
);
12655 /// \return true if A is considered a better overload candidate for the
12656 /// desired type than B.
12657 bool isBetterCandidate(const FunctionDecl
*A
, const FunctionDecl
*B
) {
12658 // If A doesn't have exactly the correct type, we don't want to classify it
12659 // as "better" than anything else. This way, the user is required to
12660 // disambiguate for us if there are multiple candidates and no exact match.
12661 return candidateHasExactlyCorrectType(A
) &&
12662 (!candidateHasExactlyCorrectType(B
) ||
12663 compareEnableIfAttrs(S
, A
, B
) == Comparison::Better
);
12666 /// \return true if we were able to eliminate all but one overload candidate,
12667 /// false otherwise.
12668 bool eliminiateSuboptimalOverloadCandidates() {
12669 // Same algorithm as overload resolution -- one pass to pick the "best",
12670 // another pass to be sure that nothing is better than the best.
12671 auto Best
= Matches
.begin();
12672 for (auto I
= Matches
.begin()+1, E
= Matches
.end(); I
!= E
; ++I
)
12673 if (isBetterCandidate(I
->second
, Best
->second
))
12676 const FunctionDecl
*BestFn
= Best
->second
;
12677 auto IsBestOrInferiorToBest
= [this, BestFn
](
12678 const std::pair
<DeclAccessPair
, FunctionDecl
*> &Pair
) {
12679 return BestFn
== Pair
.second
|| isBetterCandidate(BestFn
, Pair
.second
);
12682 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12683 // option, so we can potentially give the user a better error
12684 if (!llvm::all_of(Matches
, IsBestOrInferiorToBest
))
12686 Matches
[0] = *Best
;
12691 bool isTargetTypeAFunction() const {
12692 return TargetFunctionType
->isFunctionType();
12695 // [ToType] [Return]
12697 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12698 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12699 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12700 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12701 TargetFunctionType
= S
.ExtractUnqualifiedFunctionType(TargetType
);
12704 // return true if any matching specializations were found
12705 bool AddMatchingTemplateFunction(FunctionTemplateDecl
* FunctionTemplate
,
12706 const DeclAccessPair
& CurAccessFunPair
) {
12707 if (CXXMethodDecl
*Method
12708 = dyn_cast
<CXXMethodDecl
>(FunctionTemplate
->getTemplatedDecl())) {
12709 // Skip non-static function templates when converting to pointer, and
12710 // static when converting to member pointer.
12711 bool CanConvertToFunctionPointer
=
12712 Method
->isStatic() || Method
->isExplicitObjectMemberFunction();
12713 if (CanConvertToFunctionPointer
== TargetTypeIsNonStaticMemberFunction
)
12716 else if (TargetTypeIsNonStaticMemberFunction
)
12719 // C++ [over.over]p2:
12720 // If the name is a function template, template argument deduction is
12721 // done (14.8.2.2), and if the argument deduction succeeds, the
12722 // resulting template argument list is used to generate a single
12723 // function template specialization, which is added to the set of
12724 // overloaded functions considered.
12725 FunctionDecl
*Specialization
= nullptr;
12726 TemplateDeductionInfo
Info(FailedCandidates
.getLocation());
12727 if (Sema::TemplateDeductionResult Result
12728 = S
.DeduceTemplateArguments(FunctionTemplate
,
12729 &OvlExplicitTemplateArgs
,
12730 TargetFunctionType
, Specialization
,
12731 Info
, /*IsAddressOfFunction*/true)) {
12732 // Make a note of the failed deduction for diagnostics.
12733 FailedCandidates
.addCandidate()
12734 .set(CurAccessFunPair
, FunctionTemplate
->getTemplatedDecl(),
12735 MakeDeductionFailureInfo(Context
, Result
, Info
));
12739 // Template argument deduction ensures that we have an exact match or
12740 // compatible pointer-to-function arguments that would be adjusted by ICS.
12741 // This function template specicalization works.
12742 assert(S
.isSameOrCompatibleFunctionType(
12743 Context
.getCanonicalType(Specialization
->getType()),
12744 Context
.getCanonicalType(TargetFunctionType
)));
12746 if (!S
.checkAddressOfFunctionIsAvailable(Specialization
))
12749 Matches
.push_back(std::make_pair(CurAccessFunPair
, Specialization
));
12753 bool AddMatchingNonTemplateFunction(NamedDecl
* Fn
,
12754 const DeclAccessPair
& CurAccessFunPair
) {
12755 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
)) {
12756 // Skip non-static functions when converting to pointer, and static
12757 // when converting to member pointer.
12758 bool CanConvertToFunctionPointer
=
12759 Method
->isStatic() || Method
->isExplicitObjectMemberFunction();
12760 if (CanConvertToFunctionPointer
== TargetTypeIsNonStaticMemberFunction
)
12763 else if (TargetTypeIsNonStaticMemberFunction
)
12766 if (FunctionDecl
*FunDecl
= dyn_cast
<FunctionDecl
>(Fn
)) {
12767 if (S
.getLangOpts().CUDA
) {
12768 FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true);
12769 if (!(Caller
&& Caller
->isImplicit()) &&
12770 !S
.IsAllowedCUDACall(Caller
, FunDecl
))
12773 if (FunDecl
->isMultiVersion()) {
12774 const auto *TA
= FunDecl
->getAttr
<TargetAttr
>();
12775 if (TA
&& !TA
->isDefaultVersion())
12777 const auto *TVA
= FunDecl
->getAttr
<TargetVersionAttr
>();
12778 if (TVA
&& !TVA
->isDefaultVersion())
12782 // If any candidate has a placeholder return type, trigger its deduction
12784 if (completeFunctionType(S
, FunDecl
, SourceExpr
->getBeginLoc(),
12786 HasComplained
|= Complain
;
12790 if (!S
.checkAddressOfFunctionIsAvailable(FunDecl
))
12793 // If we're in C, we need to support types that aren't exactly identical.
12794 if (!S
.getLangOpts().CPlusPlus
||
12795 candidateHasExactlyCorrectType(FunDecl
)) {
12796 Matches
.push_back(std::make_pair(
12797 CurAccessFunPair
, cast
<FunctionDecl
>(FunDecl
->getCanonicalDecl())));
12798 FoundNonTemplateFunction
= true;
12806 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12809 // If the overload expression doesn't have the form of a pointer to
12810 // member, don't try to convert it to a pointer-to-member type.
12811 if (IsInvalidFormOfPointerToMemberFunction())
12814 for (UnresolvedSetIterator I
= OvlExpr
->decls_begin(),
12815 E
= OvlExpr
->decls_end();
12817 // Look through any using declarations to find the underlying function.
12818 NamedDecl
*Fn
= (*I
)->getUnderlyingDecl();
12820 // C++ [over.over]p3:
12821 // Non-member functions and static member functions match
12822 // targets of type "pointer-to-function" or "reference-to-function."
12823 // Nonstatic member functions match targets of
12824 // type "pointer-to-member-function."
12825 // Note that according to DR 247, the containing class does not matter.
12826 if (FunctionTemplateDecl
*FunctionTemplate
12827 = dyn_cast
<FunctionTemplateDecl
>(Fn
)) {
12828 if (AddMatchingTemplateFunction(FunctionTemplate
, I
.getPair()))
12831 // If we have explicit template arguments supplied, skip non-templates.
12832 else if (!OvlExpr
->hasExplicitTemplateArgs() &&
12833 AddMatchingNonTemplateFunction(Fn
, I
.getPair()))
12836 assert(Ret
|| Matches
.empty());
12840 void EliminateAllExceptMostSpecializedTemplate() {
12841 // [...] and any given function template specialization F1 is
12842 // eliminated if the set contains a second function template
12843 // specialization whose function template is more specialized
12844 // than the function template of F1 according to the partial
12845 // ordering rules of 14.5.5.2.
12847 // The algorithm specified above is quadratic. We instead use a
12848 // two-pass algorithm (similar to the one used to identify the
12849 // best viable function in an overload set) that identifies the
12850 // best function template (if it exists).
12852 UnresolvedSet
<4> MatchesCopy
; // TODO: avoid!
12853 for (unsigned I
= 0, E
= Matches
.size(); I
!= E
; ++I
)
12854 MatchesCopy
.addDecl(Matches
[I
].second
, Matches
[I
].first
.getAccess());
12856 // TODO: It looks like FailedCandidates does not serve much purpose
12857 // here, since the no_viable diagnostic has index 0.
12858 UnresolvedSetIterator Result
= S
.getMostSpecialized(
12859 MatchesCopy
.begin(), MatchesCopy
.end(), FailedCandidates
,
12860 SourceExpr
->getBeginLoc(), S
.PDiag(),
12861 S
.PDiag(diag::err_addr_ovl_ambiguous
)
12862 << Matches
[0].second
->getDeclName(),
12863 S
.PDiag(diag::note_ovl_candidate
)
12864 << (unsigned)oc_function
<< (unsigned)ocs_described_template
,
12865 Complain
, TargetFunctionType
);
12867 if (Result
!= MatchesCopy
.end()) {
12868 // Make it the first and only element
12869 Matches
[0].first
= Matches
[Result
- MatchesCopy
.begin()].first
;
12870 Matches
[0].second
= cast
<FunctionDecl
>(*Result
);
12873 HasComplained
|= Complain
;
12876 void EliminateAllTemplateMatches() {
12877 // [...] any function template specializations in the set are
12878 // eliminated if the set also contains a non-template function, [...]
12879 for (unsigned I
= 0, N
= Matches
.size(); I
!= N
; ) {
12880 if (Matches
[I
].second
->getPrimaryTemplate() == nullptr)
12883 Matches
[I
] = Matches
[--N
];
12889 void EliminateSuboptimalCudaMatches() {
12890 S
.EraseUnwantedCUDAMatches(S
.getCurFunctionDecl(/*AllowLambda=*/true),
12895 void ComplainNoMatchesFound() const {
12896 assert(Matches
.empty());
12897 S
.Diag(OvlExpr
->getBeginLoc(), diag::err_addr_ovl_no_viable
)
12898 << OvlExpr
->getName() << TargetFunctionType
12899 << OvlExpr
->getSourceRange();
12900 if (FailedCandidates
.empty())
12901 S
.NoteAllOverloadCandidates(OvlExpr
, TargetFunctionType
,
12902 /*TakingAddress=*/true);
12904 // We have some deduction failure messages. Use them to diagnose
12905 // the function templates, and diagnose the non-template candidates
12907 for (UnresolvedSetIterator I
= OvlExpr
->decls_begin(),
12908 IEnd
= OvlExpr
->decls_end();
12910 if (FunctionDecl
*Fun
=
12911 dyn_cast
<FunctionDecl
>((*I
)->getUnderlyingDecl()))
12912 if (!functionHasPassObjectSizeParams(Fun
))
12913 S
.NoteOverloadCandidate(*I
, Fun
, CRK_None
, TargetFunctionType
,
12914 /*TakingAddress=*/true);
12915 FailedCandidates
.NoteCandidates(S
, OvlExpr
->getBeginLoc());
12919 bool IsInvalidFormOfPointerToMemberFunction() const {
12920 return TargetTypeIsNonStaticMemberFunction
&&
12921 !OvlExprInfo
.HasFormOfMemberPointer
;
12924 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12925 // TODO: Should we condition this on whether any functions might
12926 // have matched, or is it more appropriate to do that in callers?
12927 // TODO: a fixit wouldn't hurt.
12928 S
.Diag(OvlExpr
->getNameLoc(), diag::err_addr_ovl_no_qualifier
)
12929 << TargetType
<< OvlExpr
->getSourceRange();
12932 bool IsStaticMemberFunctionFromBoundPointer() const {
12933 return StaticMemberFunctionFromBoundPointer
;
12936 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12937 S
.Diag(OvlExpr
->getBeginLoc(),
12938 diag::err_invalid_form_pointer_member_function
)
12939 << OvlExpr
->getSourceRange();
12942 void ComplainOfInvalidConversion() const {
12943 S
.Diag(OvlExpr
->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref
)
12944 << OvlExpr
->getName() << TargetType
;
12947 void ComplainMultipleMatchesFound() const {
12948 assert(Matches
.size() > 1);
12949 S
.Diag(OvlExpr
->getBeginLoc(), diag::err_addr_ovl_ambiguous
)
12950 << OvlExpr
->getName() << OvlExpr
->getSourceRange();
12951 S
.NoteAllOverloadCandidates(OvlExpr
, TargetFunctionType
,
12952 /*TakingAddress=*/true);
12955 bool hadMultipleCandidates() const { return (OvlExpr
->getNumDecls() > 1); }
12957 int getNumMatches() const { return Matches
.size(); }
12959 FunctionDecl
* getMatchingFunctionDecl() const {
12960 if (Matches
.size() != 1) return nullptr;
12961 return Matches
[0].second
;
12964 const DeclAccessPair
* getMatchingFunctionAccessPair() const {
12965 if (Matches
.size() != 1) return nullptr;
12966 return &Matches
[0].first
;
12971 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12972 /// an overloaded function (C++ [over.over]), where @p From is an
12973 /// expression with overloaded function type and @p ToType is the type
12974 /// we're trying to resolve to. For example:
12980 /// int (*pfd)(double) = f; // selects f(double)
12983 /// This routine returns the resulting FunctionDecl if it could be
12984 /// resolved, and NULL otherwise. When @p Complain is true, this
12985 /// routine will emit diagnostics if there is an error.
12987 Sema::ResolveAddressOfOverloadedFunction(Expr
*AddressOfExpr
,
12988 QualType TargetType
,
12990 DeclAccessPair
&FoundResult
,
12991 bool *pHadMultipleCandidates
) {
12992 assert(AddressOfExpr
->getType() == Context
.OverloadTy
);
12994 AddressOfFunctionResolver
Resolver(*this, AddressOfExpr
, TargetType
,
12996 int NumMatches
= Resolver
.getNumMatches();
12997 FunctionDecl
*Fn
= nullptr;
12998 bool ShouldComplain
= Complain
&& !Resolver
.hasComplained();
12999 if (NumMatches
== 0 && ShouldComplain
) {
13000 if (Resolver
.IsInvalidFormOfPointerToMemberFunction())
13001 Resolver
.ComplainIsInvalidFormOfPointerToMemberFunction();
13003 Resolver
.ComplainNoMatchesFound();
13005 else if (NumMatches
> 1 && ShouldComplain
)
13006 Resolver
.ComplainMultipleMatchesFound();
13007 else if (NumMatches
== 1) {
13008 Fn
= Resolver
.getMatchingFunctionDecl();
13010 if (auto *FPT
= Fn
->getType()->getAs
<FunctionProtoType
>())
13011 ResolveExceptionSpec(AddressOfExpr
->getExprLoc(), FPT
);
13012 FoundResult
= *Resolver
.getMatchingFunctionAccessPair();
13014 if (Resolver
.IsStaticMemberFunctionFromBoundPointer())
13015 Resolver
.ComplainIsStaticMemberFunctionFromBoundPointer();
13017 CheckAddressOfMemberAccess(AddressOfExpr
, FoundResult
);
13021 if (pHadMultipleCandidates
)
13022 *pHadMultipleCandidates
= Resolver
.hadMultipleCandidates();
13026 /// Given an expression that refers to an overloaded function, try to
13027 /// resolve that function to a single function that can have its address taken.
13028 /// This will modify `Pair` iff it returns non-null.
13030 /// This routine can only succeed if from all of the candidates in the overload
13031 /// set for SrcExpr that can have their addresses taken, there is one candidate
13032 /// that is more constrained than the rest.
13034 Sema::resolveAddressOfSingleOverloadCandidate(Expr
*E
, DeclAccessPair
&Pair
) {
13035 OverloadExpr::FindResult R
= OverloadExpr::find(E
);
13036 OverloadExpr
*Ovl
= R
.Expression
;
13037 bool IsResultAmbiguous
= false;
13038 FunctionDecl
*Result
= nullptr;
13039 DeclAccessPair DAP
;
13040 SmallVector
<FunctionDecl
*, 2> AmbiguousDecls
;
13042 // Return positive for better, negative for worse, 0 for equal preference.
13043 auto CheckCUDAPreference
= [&](FunctionDecl
*FD1
, FunctionDecl
*FD2
) {
13044 FunctionDecl
*Caller
= getCurFunctionDecl(/*AllowLambda=*/true);
13045 return static_cast<int>(IdentifyCUDAPreference(Caller
, FD1
)) -
13046 static_cast<int>(IdentifyCUDAPreference(Caller
, FD2
));
13049 auto CheckMoreConstrained
= [&](FunctionDecl
*FD1
,
13050 FunctionDecl
*FD2
) -> std::optional
<bool> {
13051 if (FunctionDecl
*MF
= FD1
->getInstantiatedFromMemberFunction())
13053 if (FunctionDecl
*MF
= FD2
->getInstantiatedFromMemberFunction())
13055 SmallVector
<const Expr
*, 1> AC1
, AC2
;
13056 FD1
->getAssociatedConstraints(AC1
);
13057 FD2
->getAssociatedConstraints(AC2
);
13058 bool AtLeastAsConstrained1
, AtLeastAsConstrained2
;
13059 if (IsAtLeastAsConstrained(FD1
, AC1
, FD2
, AC2
, AtLeastAsConstrained1
))
13060 return std::nullopt
;
13061 if (IsAtLeastAsConstrained(FD2
, AC2
, FD1
, AC1
, AtLeastAsConstrained2
))
13062 return std::nullopt
;
13063 if (AtLeastAsConstrained1
== AtLeastAsConstrained2
)
13064 return std::nullopt
;
13065 return AtLeastAsConstrained1
;
13068 // Don't use the AddressOfResolver because we're specifically looking for
13069 // cases where we have one overload candidate that lacks
13070 // enable_if/pass_object_size/...
13071 for (auto I
= Ovl
->decls_begin(), E
= Ovl
->decls_end(); I
!= E
; ++I
) {
13072 auto *FD
= dyn_cast
<FunctionDecl
>(I
->getUnderlyingDecl());
13076 if (!checkAddressOfFunctionIsAvailable(FD
))
13079 // If we found a better result, update Result.
13080 auto FoundBetter
= [&]() {
13081 IsResultAmbiguous
= false;
13086 // We have more than one result - see if it is more constrained than the
13089 // Check CUDA preference first. If the candidates have differennt CUDA
13090 // preference, choose the one with higher CUDA preference. Otherwise,
13091 // choose the one with more constraints.
13092 if (getLangOpts().CUDA
) {
13093 int PreferenceByCUDA
= CheckCUDAPreference(FD
, Result
);
13094 // FD has different preference than Result.
13095 if (PreferenceByCUDA
!= 0) {
13096 // FD is more preferable than Result.
13097 if (PreferenceByCUDA
> 0)
13102 // FD has the same CUDA prefernece than Result. Continue check
13104 std::optional
<bool> MoreConstrainedThanPrevious
=
13105 CheckMoreConstrained(FD
, Result
);
13106 if (!MoreConstrainedThanPrevious
) {
13107 IsResultAmbiguous
= true;
13108 AmbiguousDecls
.push_back(FD
);
13111 if (!*MoreConstrainedThanPrevious
)
13113 // FD is more constrained - replace Result with it.
13118 if (IsResultAmbiguous
)
13122 SmallVector
<const Expr
*, 1> ResultAC
;
13123 // We skipped over some ambiguous declarations which might be ambiguous with
13124 // the selected result.
13125 for (FunctionDecl
*Skipped
: AmbiguousDecls
) {
13126 // If skipped candidate has different CUDA preference than the result,
13127 // there is no ambiguity. Otherwise check whether they have different
13129 if (getLangOpts().CUDA
&& CheckCUDAPreference(Skipped
, Result
) != 0)
13131 if (!CheckMoreConstrained(Skipped
, Result
))
13139 /// Given an overloaded function, tries to turn it into a non-overloaded
13140 /// function reference using resolveAddressOfSingleOverloadCandidate. This
13141 /// will perform access checks, diagnose the use of the resultant decl, and, if
13142 /// requested, potentially perform a function-to-pointer decay.
13144 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13145 /// Otherwise, returns true. This may emit diagnostics and return true.
13146 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
13147 ExprResult
&SrcExpr
, bool DoFunctionPointerConversion
) {
13148 Expr
*E
= SrcExpr
.get();
13149 assert(E
->getType() == Context
.OverloadTy
&& "SrcExpr must be an overload");
13151 DeclAccessPair DAP
;
13152 FunctionDecl
*Found
= resolveAddressOfSingleOverloadCandidate(E
, DAP
);
13153 if (!Found
|| Found
->isCPUDispatchMultiVersion() ||
13154 Found
->isCPUSpecificMultiVersion())
13157 // Emitting multiple diagnostics for a function that is both inaccessible and
13158 // unavailable is consistent with our behavior elsewhere. So, always check
13160 DiagnoseUseOfDecl(Found
, E
->getExprLoc());
13161 CheckAddressOfMemberAccess(E
, DAP
);
13162 ExprResult Res
= FixOverloadedFunctionReference(E
, DAP
, Found
);
13163 if (Res
.isInvalid())
13165 Expr
*Fixed
= Res
.get();
13166 if (DoFunctionPointerConversion
&& Fixed
->getType()->isFunctionType())
13167 SrcExpr
= DefaultFunctionArrayConversion(Fixed
, /*Diagnose=*/false);
13173 /// Given an expression that refers to an overloaded function, try to
13174 /// resolve that overloaded function expression down to a single function.
13176 /// This routine can only resolve template-ids that refer to a single function
13177 /// template, where that template-id refers to a single template whose template
13178 /// arguments are either provided by the template-id or have defaults,
13179 /// as described in C++0x [temp.arg.explicit]p3.
13181 /// If no template-ids are found, no diagnostics are emitted and NULL is
13183 FunctionDecl
*Sema::ResolveSingleFunctionTemplateSpecialization(
13184 OverloadExpr
*ovl
, bool Complain
, DeclAccessPair
*FoundResult
,
13185 TemplateSpecCandidateSet
*FailedTSC
) {
13186 // C++ [over.over]p1:
13187 // [...] [Note: any redundant set of parentheses surrounding the
13188 // overloaded function name is ignored (5.1). ]
13189 // C++ [over.over]p1:
13190 // [...] The overloaded function name can be preceded by the &
13193 // If we didn't actually find any template-ids, we're done.
13194 if (!ovl
->hasExplicitTemplateArgs())
13197 TemplateArgumentListInfo ExplicitTemplateArgs
;
13198 ovl
->copyTemplateArgumentsInto(ExplicitTemplateArgs
);
13200 // Look through all of the overloaded functions, searching for one
13201 // whose type matches exactly.
13202 FunctionDecl
*Matched
= nullptr;
13203 for (UnresolvedSetIterator I
= ovl
->decls_begin(),
13204 E
= ovl
->decls_end(); I
!= E
; ++I
) {
13205 // C++0x [temp.arg.explicit]p3:
13206 // [...] In contexts where deduction is done and fails, or in contexts
13207 // where deduction is not done, if a template argument list is
13208 // specified and it, along with any default template arguments,
13209 // identifies a single function template specialization, then the
13210 // template-id is an lvalue for the function template specialization.
13211 FunctionTemplateDecl
*FunctionTemplate
13212 = cast
<FunctionTemplateDecl
>((*I
)->getUnderlyingDecl());
13214 // C++ [over.over]p2:
13215 // If the name is a function template, template argument deduction is
13216 // done (14.8.2.2), and if the argument deduction succeeds, the
13217 // resulting template argument list is used to generate a single
13218 // function template specialization, which is added to the set of
13219 // overloaded functions considered.
13220 FunctionDecl
*Specialization
= nullptr;
13221 TemplateDeductionInfo
Info(ovl
->getNameLoc());
13222 if (TemplateDeductionResult Result
13223 = DeduceTemplateArguments(FunctionTemplate
, &ExplicitTemplateArgs
,
13224 Specialization
, Info
,
13225 /*IsAddressOfFunction*/true)) {
13226 // Make a note of the failed deduction for diagnostics.
13228 FailedTSC
->addCandidate().set(
13229 I
.getPair(), FunctionTemplate
->getTemplatedDecl(),
13230 MakeDeductionFailureInfo(Context
, Result
, Info
));
13234 assert(Specialization
&& "no specialization and no error?");
13236 // Multiple matches; we can't resolve to a single declaration.
13239 Diag(ovl
->getExprLoc(), diag::err_addr_ovl_ambiguous
)
13241 NoteAllOverloadCandidates(ovl
);
13246 Matched
= Specialization
;
13247 if (FoundResult
) *FoundResult
= I
.getPair();
13251 completeFunctionType(*this, Matched
, ovl
->getExprLoc(), Complain
))
13257 // Resolve and fix an overloaded expression that can be resolved
13258 // because it identifies a single function template specialization.
13260 // Last three arguments should only be supplied if Complain = true
13262 // Return true if it was logically possible to so resolve the
13263 // expression, regardless of whether or not it succeeded. Always
13264 // returns true if 'complain' is set.
13265 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
13266 ExprResult
&SrcExpr
, bool doFunctionPointerConversion
, bool complain
,
13267 SourceRange OpRangeForComplaining
, QualType DestTypeForComplaining
,
13268 unsigned DiagIDForComplaining
) {
13269 assert(SrcExpr
.get()->getType() == Context
.OverloadTy
);
13271 OverloadExpr::FindResult ovl
= OverloadExpr::find(SrcExpr
.get());
13273 DeclAccessPair found
;
13274 ExprResult SingleFunctionExpression
;
13275 if (FunctionDecl
*fn
= ResolveSingleFunctionTemplateSpecialization(
13276 ovl
.Expression
, /*complain*/ false, &found
)) {
13277 if (DiagnoseUseOfDecl(fn
, SrcExpr
.get()->getBeginLoc())) {
13278 SrcExpr
= ExprError();
13282 // It is only correct to resolve to an instance method if we're
13283 // resolving a form that's permitted to be a pointer to member.
13284 // Otherwise we'll end up making a bound member expression, which
13285 // is illegal in all the contexts we resolve like this.
13286 if (!ovl
.HasFormOfMemberPointer
&&
13287 isa
<CXXMethodDecl
>(fn
) &&
13288 cast
<CXXMethodDecl
>(fn
)->isInstance()) {
13289 if (!complain
) return false;
13291 Diag(ovl
.Expression
->getExprLoc(),
13292 diag::err_bound_member_function
)
13293 << 0 << ovl
.Expression
->getSourceRange();
13295 // TODO: I believe we only end up here if there's a mix of
13296 // static and non-static candidates (otherwise the expression
13297 // would have 'bound member' type, not 'overload' type).
13298 // Ideally we would note which candidate was chosen and why
13299 // the static candidates were rejected.
13300 SrcExpr
= ExprError();
13304 // Fix the expression to refer to 'fn'.
13305 SingleFunctionExpression
=
13306 FixOverloadedFunctionReference(SrcExpr
.get(), found
, fn
);
13308 // If desired, do function-to-pointer decay.
13309 if (doFunctionPointerConversion
) {
13310 SingleFunctionExpression
=
13311 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression
.get());
13312 if (SingleFunctionExpression
.isInvalid()) {
13313 SrcExpr
= ExprError();
13319 if (!SingleFunctionExpression
.isUsable()) {
13321 Diag(OpRangeForComplaining
.getBegin(), DiagIDForComplaining
)
13322 << ovl
.Expression
->getName()
13323 << DestTypeForComplaining
13324 << OpRangeForComplaining
13325 << ovl
.Expression
->getQualifierLoc().getSourceRange();
13326 NoteAllOverloadCandidates(SrcExpr
.get());
13328 SrcExpr
= ExprError();
13335 SrcExpr
= SingleFunctionExpression
;
13339 /// Add a single candidate to the overload set.
13340 static void AddOverloadedCallCandidate(Sema
&S
,
13341 DeclAccessPair FoundDecl
,
13342 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
13343 ArrayRef
<Expr
*> Args
,
13344 OverloadCandidateSet
&CandidateSet
,
13345 bool PartialOverloading
,
13347 NamedDecl
*Callee
= FoundDecl
.getDecl();
13348 if (isa
<UsingShadowDecl
>(Callee
))
13349 Callee
= cast
<UsingShadowDecl
>(Callee
)->getTargetDecl();
13351 if (FunctionDecl
*Func
= dyn_cast
<FunctionDecl
>(Callee
)) {
13352 if (ExplicitTemplateArgs
) {
13353 assert(!KnownValid
&& "Explicit template arguments?");
13356 // Prevent ill-formed function decls to be added as overload candidates.
13357 if (!isa
<FunctionProtoType
>(Func
->getType()->getAs
<FunctionType
>()))
13360 S
.AddOverloadCandidate(Func
, FoundDecl
, Args
, CandidateSet
,
13361 /*SuppressUserConversions=*/false,
13362 PartialOverloading
);
13366 if (FunctionTemplateDecl
*FuncTemplate
13367 = dyn_cast
<FunctionTemplateDecl
>(Callee
)) {
13368 S
.AddTemplateOverloadCandidate(FuncTemplate
, FoundDecl
,
13369 ExplicitTemplateArgs
, Args
, CandidateSet
,
13370 /*SuppressUserConversions=*/false,
13371 PartialOverloading
);
13375 assert(!KnownValid
&& "unhandled case in overloaded call candidate");
13378 /// Add the overload candidates named by callee and/or found by argument
13379 /// dependent lookup to the given overload set.
13380 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr
*ULE
,
13381 ArrayRef
<Expr
*> Args
,
13382 OverloadCandidateSet
&CandidateSet
,
13383 bool PartialOverloading
) {
13386 // Verify that ArgumentDependentLookup is consistent with the rules
13387 // in C++0x [basic.lookup.argdep]p3:
13389 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13390 // and let Y be the lookup set produced by argument dependent
13391 // lookup (defined as follows). If X contains
13393 // -- a declaration of a class member, or
13395 // -- a block-scope function declaration that is not a
13396 // using-declaration, or
13398 // -- a declaration that is neither a function or a function
13401 // then Y is empty.
13403 if (ULE
->requiresADL()) {
13404 for (UnresolvedLookupExpr::decls_iterator I
= ULE
->decls_begin(),
13405 E
= ULE
->decls_end(); I
!= E
; ++I
) {
13406 assert(!(*I
)->getDeclContext()->isRecord());
13407 assert(isa
<UsingShadowDecl
>(*I
) ||
13408 !(*I
)->getDeclContext()->isFunctionOrMethod());
13409 assert((*I
)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13414 // It would be nice to avoid this copy.
13415 TemplateArgumentListInfo TABuffer
;
13416 TemplateArgumentListInfo
*ExplicitTemplateArgs
= nullptr;
13417 if (ULE
->hasExplicitTemplateArgs()) {
13418 ULE
->copyTemplateArgumentsInto(TABuffer
);
13419 ExplicitTemplateArgs
= &TABuffer
;
13422 for (UnresolvedLookupExpr::decls_iterator I
= ULE
->decls_begin(),
13423 E
= ULE
->decls_end(); I
!= E
; ++I
)
13424 AddOverloadedCallCandidate(*this, I
.getPair(), ExplicitTemplateArgs
, Args
,
13425 CandidateSet
, PartialOverloading
,
13426 /*KnownValid*/ true);
13428 if (ULE
->requiresADL())
13429 AddArgumentDependentLookupCandidates(ULE
->getName(), ULE
->getExprLoc(),
13430 Args
, ExplicitTemplateArgs
,
13431 CandidateSet
, PartialOverloading
);
13434 /// Add the call candidates from the given set of lookup results to the given
13435 /// overload set. Non-function lookup results are ignored.
13436 void Sema::AddOverloadedCallCandidates(
13437 LookupResult
&R
, TemplateArgumentListInfo
*ExplicitTemplateArgs
,
13438 ArrayRef
<Expr
*> Args
, OverloadCandidateSet
&CandidateSet
) {
13439 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
)
13440 AddOverloadedCallCandidate(*this, I
.getPair(), ExplicitTemplateArgs
, Args
,
13441 CandidateSet
, false, /*KnownValid*/ false);
13444 /// Determine whether a declaration with the specified name could be moved into
13445 /// a different namespace.
13446 static bool canBeDeclaredInNamespace(const DeclarationName
&Name
) {
13447 switch (Name
.getCXXOverloadedOperator()) {
13448 case OO_New
: case OO_Array_New
:
13449 case OO_Delete
: case OO_Array_Delete
:
13457 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13458 /// template, where the non-dependent name was declared after the template
13459 /// was defined. This is common in code written for a compilers which do not
13460 /// correctly implement two-stage name lookup.
13462 /// Returns true if a viable candidate was found and a diagnostic was issued.
13463 static bool DiagnoseTwoPhaseLookup(
13464 Sema
&SemaRef
, SourceLocation FnLoc
, const CXXScopeSpec
&SS
,
13465 LookupResult
&R
, OverloadCandidateSet::CandidateSetKind CSK
,
13466 TemplateArgumentListInfo
*ExplicitTemplateArgs
, ArrayRef
<Expr
*> Args
,
13467 CXXRecordDecl
**FoundInClass
= nullptr) {
13468 if (!SemaRef
.inTemplateInstantiation() || !SS
.isEmpty())
13471 for (DeclContext
*DC
= SemaRef
.CurContext
; DC
; DC
= DC
->getParent()) {
13472 if (DC
->isTransparentContext())
13475 SemaRef
.LookupQualifiedName(R
, DC
);
13478 R
.suppressDiagnostics();
13480 OverloadCandidateSet
Candidates(FnLoc
, CSK
);
13481 SemaRef
.AddOverloadedCallCandidates(R
, ExplicitTemplateArgs
, Args
,
13484 OverloadCandidateSet::iterator Best
;
13485 OverloadingResult OR
=
13486 Candidates
.BestViableFunction(SemaRef
, FnLoc
, Best
);
13488 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
)) {
13489 // We either found non-function declarations or a best viable function
13490 // at class scope. A class-scope lookup result disables ADL. Don't
13491 // look past this, but let the caller know that we found something that
13492 // either is, or might be, usable in this class.
13493 if (FoundInClass
) {
13494 *FoundInClass
= RD
;
13495 if (OR
== OR_Success
) {
13497 R
.addDecl(Best
->FoundDecl
.getDecl(), Best
->FoundDecl
.getAccess());
13504 if (OR
!= OR_Success
) {
13505 // There wasn't a unique best function or function template.
13509 // Find the namespaces where ADL would have looked, and suggest
13510 // declaring the function there instead.
13511 Sema::AssociatedNamespaceSet AssociatedNamespaces
;
13512 Sema::AssociatedClassSet AssociatedClasses
;
13513 SemaRef
.FindAssociatedClassesAndNamespaces(FnLoc
, Args
,
13514 AssociatedNamespaces
,
13515 AssociatedClasses
);
13516 Sema::AssociatedNamespaceSet SuggestedNamespaces
;
13517 if (canBeDeclaredInNamespace(R
.getLookupName())) {
13518 DeclContext
*Std
= SemaRef
.getStdNamespace();
13519 for (Sema::AssociatedNamespaceSet::iterator
13520 it
= AssociatedNamespaces
.begin(),
13521 end
= AssociatedNamespaces
.end(); it
!= end
; ++it
) {
13522 // Never suggest declaring a function within namespace 'std'.
13523 if (Std
&& Std
->Encloses(*it
))
13526 // Never suggest declaring a function within a namespace with a
13527 // reserved name, like __gnu_cxx.
13528 NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(*it
);
13530 NS
->getQualifiedNameAsString().find("__") != std::string::npos
)
13533 SuggestedNamespaces
.insert(*it
);
13537 SemaRef
.Diag(R
.getNameLoc(), diag::err_not_found_by_two_phase_lookup
)
13538 << R
.getLookupName();
13539 if (SuggestedNamespaces
.empty()) {
13540 SemaRef
.Diag(Best
->Function
->getLocation(),
13541 diag::note_not_found_by_two_phase_lookup
)
13542 << R
.getLookupName() << 0;
13543 } else if (SuggestedNamespaces
.size() == 1) {
13544 SemaRef
.Diag(Best
->Function
->getLocation(),
13545 diag::note_not_found_by_two_phase_lookup
)
13546 << R
.getLookupName() << 1 << *SuggestedNamespaces
.begin();
13548 // FIXME: It would be useful to list the associated namespaces here,
13549 // but the diagnostics infrastructure doesn't provide a way to produce
13550 // a localized representation of a list of items.
13551 SemaRef
.Diag(Best
->Function
->getLocation(),
13552 diag::note_not_found_by_two_phase_lookup
)
13553 << R
.getLookupName() << 2;
13556 // Try to recover by calling this function.
13566 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13567 /// template, where the non-dependent operator was declared after the template
13570 /// Returns true if a viable candidate was found and a diagnostic was issued.
13572 DiagnoseTwoPhaseOperatorLookup(Sema
&SemaRef
, OverloadedOperatorKind Op
,
13573 SourceLocation OpLoc
,
13574 ArrayRef
<Expr
*> Args
) {
13575 DeclarationName OpName
=
13576 SemaRef
.Context
.DeclarationNames
.getCXXOperatorName(Op
);
13577 LookupResult
R(SemaRef
, OpName
, OpLoc
, Sema::LookupOperatorName
);
13578 return DiagnoseTwoPhaseLookup(SemaRef
, OpLoc
, CXXScopeSpec(), R
,
13579 OverloadCandidateSet::CSK_Operator
,
13580 /*ExplicitTemplateArgs=*/nullptr, Args
);
13584 class BuildRecoveryCallExprRAII
{
13586 Sema::SatisfactionStackResetRAII SatStack
;
13589 BuildRecoveryCallExprRAII(Sema
&S
) : SemaRef(S
), SatStack(S
) {
13590 assert(SemaRef
.IsBuildingRecoveryCallExpr
== false);
13591 SemaRef
.IsBuildingRecoveryCallExpr
= true;
13594 ~BuildRecoveryCallExprRAII() { SemaRef
.IsBuildingRecoveryCallExpr
= false; }
13598 /// Attempts to recover from a call where no functions were found.
13600 /// This function will do one of three things:
13601 /// * Diagnose, recover, and return a recovery expression.
13602 /// * Diagnose, fail to recover, and return ExprError().
13603 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13604 /// expected to diagnose as appropriate.
13606 BuildRecoveryCallExpr(Sema
&SemaRef
, Scope
*S
, Expr
*Fn
,
13607 UnresolvedLookupExpr
*ULE
,
13608 SourceLocation LParenLoc
,
13609 MutableArrayRef
<Expr
*> Args
,
13610 SourceLocation RParenLoc
,
13611 bool EmptyLookup
, bool AllowTypoCorrection
) {
13612 // Do not try to recover if it is already building a recovery call.
13613 // This stops infinite loops for template instantiations like
13615 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13616 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13617 if (SemaRef
.IsBuildingRecoveryCallExpr
)
13618 return ExprResult();
13619 BuildRecoveryCallExprRAII
RCE(SemaRef
);
13622 SS
.Adopt(ULE
->getQualifierLoc());
13623 SourceLocation TemplateKWLoc
= ULE
->getTemplateKeywordLoc();
13625 TemplateArgumentListInfo TABuffer
;
13626 TemplateArgumentListInfo
*ExplicitTemplateArgs
= nullptr;
13627 if (ULE
->hasExplicitTemplateArgs()) {
13628 ULE
->copyTemplateArgumentsInto(TABuffer
);
13629 ExplicitTemplateArgs
= &TABuffer
;
13632 LookupResult
R(SemaRef
, ULE
->getName(), ULE
->getNameLoc(),
13633 Sema::LookupOrdinaryName
);
13634 CXXRecordDecl
*FoundInClass
= nullptr;
13635 if (DiagnoseTwoPhaseLookup(SemaRef
, Fn
->getExprLoc(), SS
, R
,
13636 OverloadCandidateSet::CSK_Normal
,
13637 ExplicitTemplateArgs
, Args
, &FoundInClass
)) {
13638 // OK, diagnosed a two-phase lookup issue.
13639 } else if (EmptyLookup
) {
13640 // Try to recover from an empty lookup with typo correction.
13642 NoTypoCorrectionCCC NoTypoValidator
{};
13643 FunctionCallFilterCCC
FunctionCallValidator(SemaRef
, Args
.size(),
13644 ExplicitTemplateArgs
!= nullptr,
13645 dyn_cast
<MemberExpr
>(Fn
));
13646 CorrectionCandidateCallback
&Validator
=
13647 AllowTypoCorrection
13648 ? static_cast<CorrectionCandidateCallback
&>(FunctionCallValidator
)
13649 : static_cast<CorrectionCandidateCallback
&>(NoTypoValidator
);
13650 if (SemaRef
.DiagnoseEmptyLookup(S
, SS
, R
, Validator
, ExplicitTemplateArgs
,
13652 return ExprError();
13653 } else if (FoundInClass
&& SemaRef
.getLangOpts().MSVCCompat
) {
13654 // We found a usable declaration of the name in a dependent base of some
13655 // enclosing class.
13656 // FIXME: We should also explain why the candidates found by name lookup
13657 // were not viable.
13658 if (SemaRef
.DiagnoseDependentMemberLookup(R
))
13659 return ExprError();
13661 // We had viable candidates and couldn't recover; let the caller diagnose
13663 return ExprResult();
13666 // If we get here, we should have issued a diagnostic and formed a recovery
13668 assert(!R
.empty() && "lookup results empty despite recovery");
13670 // If recovery created an ambiguity, just bail out.
13671 if (R
.isAmbiguous()) {
13672 R
.suppressDiagnostics();
13673 return ExprError();
13676 // Build an implicit member call if appropriate. Just drop the
13677 // casts and such from the call, we don't really care.
13678 ExprResult NewFn
= ExprError();
13679 if ((*R
.begin())->isCXXClassMember())
13680 NewFn
= SemaRef
.BuildPossibleImplicitMemberExpr(SS
, TemplateKWLoc
, R
,
13681 ExplicitTemplateArgs
, S
);
13682 else if (ExplicitTemplateArgs
|| TemplateKWLoc
.isValid())
13683 NewFn
= SemaRef
.BuildTemplateIdExpr(SS
, TemplateKWLoc
, R
, false,
13684 ExplicitTemplateArgs
);
13686 NewFn
= SemaRef
.BuildDeclarationNameExpr(SS
, R
, false);
13688 if (NewFn
.isInvalid())
13689 return ExprError();
13691 // This shouldn't cause an infinite loop because we're giving it
13692 // an expression with viable lookup results, which should never
13694 return SemaRef
.BuildCallExpr(/*Scope*/ nullptr, NewFn
.get(), LParenLoc
,
13695 MultiExprArg(Args
.data(), Args
.size()),
13699 /// Constructs and populates an OverloadedCandidateSet from
13700 /// the given function.
13701 /// \returns true when an the ExprResult output parameter has been set.
13702 bool Sema::buildOverloadedCallSet(Scope
*S
, Expr
*Fn
,
13703 UnresolvedLookupExpr
*ULE
,
13705 SourceLocation RParenLoc
,
13706 OverloadCandidateSet
*CandidateSet
,
13707 ExprResult
*Result
) {
13709 if (ULE
->requiresADL()) {
13710 // To do ADL, we must have found an unqualified name.
13711 assert(!ULE
->getQualifier() && "qualified name with ADL");
13713 // We don't perform ADL for implicit declarations of builtins.
13714 // Verify that this was correctly set up.
13716 if (ULE
->decls_begin() != ULE
->decls_end() &&
13717 ULE
->decls_begin() + 1 == ULE
->decls_end() &&
13718 (F
= dyn_cast
<FunctionDecl
>(*ULE
->decls_begin())) &&
13719 F
->getBuiltinID() && F
->isImplicit())
13720 llvm_unreachable("performing ADL for builtin");
13722 // We don't perform ADL in C.
13723 assert(getLangOpts().CPlusPlus
&& "ADL enabled in C");
13727 UnbridgedCastsSet UnbridgedCasts
;
13728 if (checkArgPlaceholdersForOverload(*this, Args
, UnbridgedCasts
)) {
13729 *Result
= ExprError();
13733 // Add the functions denoted by the callee to the set of candidate
13734 // functions, including those from argument-dependent lookup.
13735 AddOverloadedCallCandidates(ULE
, Args
, *CandidateSet
);
13737 if (getLangOpts().MSVCCompat
&&
13738 CurContext
->isDependentContext() && !isSFINAEContext() &&
13739 (isa
<FunctionDecl
>(CurContext
) || isa
<CXXRecordDecl
>(CurContext
))) {
13741 OverloadCandidateSet::iterator Best
;
13742 if (CandidateSet
->empty() ||
13743 CandidateSet
->BestViableFunction(*this, Fn
->getBeginLoc(), Best
) ==
13744 OR_No_Viable_Function
) {
13745 // In Microsoft mode, if we are inside a template class member function
13746 // then create a type dependent CallExpr. The goal is to postpone name
13747 // lookup to instantiation time to be able to search into type dependent
13750 CallExpr::Create(Context
, Fn
, Args
, Context
.DependentTy
, VK_PRValue
,
13751 RParenLoc
, CurFPFeatureOverrides());
13752 CE
->markDependentForPostponedNameLookup();
13758 if (CandidateSet
->empty())
13761 UnbridgedCasts
.restore();
13765 // Guess at what the return type for an unresolvable overload should be.
13766 static QualType
chooseRecoveryType(OverloadCandidateSet
&CS
,
13767 OverloadCandidateSet::iterator
*Best
) {
13768 std::optional
<QualType
> Result
;
13769 // Adjust Type after seeing a candidate.
13770 auto ConsiderCandidate
= [&](const OverloadCandidate
&Candidate
) {
13771 if (!Candidate
.Function
)
13773 if (Candidate
.Function
->isInvalidDecl())
13775 QualType T
= Candidate
.Function
->getReturnType();
13780 else if (Result
!= T
)
13781 Result
= QualType();
13784 // Look for an unambiguous type from a progressively larger subset.
13785 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13787 // First, consider only the best candidate.
13788 if (Best
&& *Best
!= CS
.end())
13789 ConsiderCandidate(**Best
);
13790 // Next, consider only viable candidates.
13792 for (const auto &C
: CS
)
13794 ConsiderCandidate(C
);
13795 // Finally, consider all candidates.
13797 for (const auto &C
: CS
)
13798 ConsiderCandidate(C
);
13802 auto Value
= *Result
;
13803 if (Value
.isNull() || Value
->isUndeducedType())
13808 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13809 /// the completed call expression. If overload resolution fails, emits
13810 /// diagnostics and returns ExprError()
13811 static ExprResult
FinishOverloadedCallExpr(Sema
&SemaRef
, Scope
*S
, Expr
*Fn
,
13812 UnresolvedLookupExpr
*ULE
,
13813 SourceLocation LParenLoc
,
13815 SourceLocation RParenLoc
,
13817 OverloadCandidateSet
*CandidateSet
,
13818 OverloadCandidateSet::iterator
*Best
,
13819 OverloadingResult OverloadResult
,
13820 bool AllowTypoCorrection
) {
13821 switch (OverloadResult
) {
13823 FunctionDecl
*FDecl
= (*Best
)->Function
;
13824 SemaRef
.CheckUnresolvedLookupAccess(ULE
, (*Best
)->FoundDecl
);
13825 if (SemaRef
.DiagnoseUseOfDecl(FDecl
, ULE
->getNameLoc()))
13826 return ExprError();
13828 SemaRef
.FixOverloadedFunctionReference(Fn
, (*Best
)->FoundDecl
, FDecl
);
13829 if (Res
.isInvalid())
13830 return ExprError();
13831 return SemaRef
.BuildResolvedCallExpr(
13832 Res
.get(), FDecl
, LParenLoc
, Args
, RParenLoc
, ExecConfig
,
13833 /*IsExecConfig=*/false, (*Best
)->IsADLCandidate
);
13836 case OR_No_Viable_Function
: {
13837 // Try to recover by looking for viable functions which the user might
13838 // have meant to call.
13839 ExprResult Recovery
= BuildRecoveryCallExpr(SemaRef
, S
, Fn
, ULE
, LParenLoc
,
13841 CandidateSet
->empty(),
13842 AllowTypoCorrection
);
13843 if (Recovery
.isInvalid() || Recovery
.isUsable())
13846 // If the user passes in a function that we can't take the address of, we
13847 // generally end up emitting really bad error messages. Here, we attempt to
13848 // emit better ones.
13849 for (const Expr
*Arg
: Args
) {
13850 if (!Arg
->getType()->isFunctionType())
13852 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(Arg
->IgnoreParenImpCasts())) {
13853 auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
13855 !SemaRef
.checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
13856 Arg
->getExprLoc()))
13857 return ExprError();
13861 CandidateSet
->NoteCandidates(
13862 PartialDiagnosticAt(
13864 SemaRef
.PDiag(diag::err_ovl_no_viable_function_in_call
)
13865 << ULE
->getName() << Fn
->getSourceRange()),
13866 SemaRef
, OCD_AllCandidates
, Args
);
13871 CandidateSet
->NoteCandidates(
13872 PartialDiagnosticAt(Fn
->getBeginLoc(),
13873 SemaRef
.PDiag(diag::err_ovl_ambiguous_call
)
13874 << ULE
->getName() << Fn
->getSourceRange()),
13875 SemaRef
, OCD_AmbiguousCandidates
, Args
);
13879 CandidateSet
->NoteCandidates(
13880 PartialDiagnosticAt(Fn
->getBeginLoc(),
13881 SemaRef
.PDiag(diag::err_ovl_deleted_call
)
13882 << ULE
->getName() << Fn
->getSourceRange()),
13883 SemaRef
, OCD_AllCandidates
, Args
);
13885 // We emitted an error for the unavailable/deleted function call but keep
13886 // the call in the AST.
13887 FunctionDecl
*FDecl
= (*Best
)->Function
;
13889 SemaRef
.FixOverloadedFunctionReference(Fn
, (*Best
)->FoundDecl
, FDecl
);
13890 if (Res
.isInvalid())
13891 return ExprError();
13892 return SemaRef
.BuildResolvedCallExpr(
13893 Res
.get(), FDecl
, LParenLoc
, Args
, RParenLoc
, ExecConfig
,
13894 /*IsExecConfig=*/false, (*Best
)->IsADLCandidate
);
13898 // Overload resolution failed, try to recover.
13899 SmallVector
<Expr
*, 8> SubExprs
= {Fn
};
13900 SubExprs
.append(Args
.begin(), Args
.end());
13901 return SemaRef
.CreateRecoveryExpr(Fn
->getBeginLoc(), RParenLoc
, SubExprs
,
13902 chooseRecoveryType(*CandidateSet
, Best
));
13905 static void markUnaddressableCandidatesUnviable(Sema
&S
,
13906 OverloadCandidateSet
&CS
) {
13907 for (auto I
= CS
.begin(), E
= CS
.end(); I
!= E
; ++I
) {
13909 !S
.checkAddressOfFunctionIsAvailable(I
->Function
, /*Complain=*/false)) {
13911 I
->FailureKind
= ovl_fail_addr_not_available
;
13916 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13917 /// (which eventually refers to the declaration Func) and the call
13918 /// arguments Args/NumArgs, attempt to resolve the function call down
13919 /// to a specific function. If overload resolution succeeds, returns
13920 /// the call expression produced by overload resolution.
13921 /// Otherwise, emits diagnostics and returns ExprError.
13922 ExprResult
Sema::BuildOverloadedCallExpr(Scope
*S
, Expr
*Fn
,
13923 UnresolvedLookupExpr
*ULE
,
13924 SourceLocation LParenLoc
,
13926 SourceLocation RParenLoc
,
13928 bool AllowTypoCorrection
,
13929 bool CalleesAddressIsTaken
) {
13930 OverloadCandidateSet
CandidateSet(Fn
->getExprLoc(),
13931 OverloadCandidateSet::CSK_Normal
);
13934 if (buildOverloadedCallSet(S
, Fn
, ULE
, Args
, LParenLoc
, &CandidateSet
,
13938 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13939 // functions that aren't addressible are considered unviable.
13940 if (CalleesAddressIsTaken
)
13941 markUnaddressableCandidatesUnviable(*this, CandidateSet
);
13943 OverloadCandidateSet::iterator Best
;
13944 OverloadingResult OverloadResult
=
13945 CandidateSet
.BestViableFunction(*this, Fn
->getBeginLoc(), Best
);
13947 return FinishOverloadedCallExpr(*this, S
, Fn
, ULE
, LParenLoc
, Args
, RParenLoc
,
13948 ExecConfig
, &CandidateSet
, &Best
,
13949 OverloadResult
, AllowTypoCorrection
);
13952 static bool IsOverloaded(const UnresolvedSetImpl
&Functions
) {
13953 return Functions
.size() > 1 ||
13954 (Functions
.size() == 1 &&
13955 isa
<FunctionTemplateDecl
>((*Functions
.begin())->getUnderlyingDecl()));
13958 ExprResult
Sema::CreateUnresolvedLookupExpr(CXXRecordDecl
*NamingClass
,
13959 NestedNameSpecifierLoc NNSLoc
,
13960 DeclarationNameInfo DNI
,
13961 const UnresolvedSetImpl
&Fns
,
13963 return UnresolvedLookupExpr::Create(Context
, NamingClass
, NNSLoc
, DNI
,
13964 PerformADL
, IsOverloaded(Fns
),
13965 Fns
.begin(), Fns
.end());
13968 ExprResult
Sema::BuildCXXMemberCallExpr(Expr
*E
, NamedDecl
*FoundDecl
,
13969 CXXConversionDecl
*Method
,
13970 bool HadMultipleCandidates
) {
13971 // Convert the expression to match the conversion function's implicit object
13974 if (Method
->isExplicitObjectMemberFunction())
13975 Exp
= InitializeExplicitObjectArgument(*this, E
, Method
);
13977 Exp
= PerformImplicitObjectArgumentInitialization(E
, /*Qualifier=*/nullptr,
13978 FoundDecl
, Method
);
13979 if (Exp
.isInvalid())
13982 if (Method
->getParent()->isLambda() &&
13983 Method
->getConversionType()->isBlockPointerType()) {
13984 // This is a lambda conversion to block pointer; check if the argument
13985 // was a LambdaExpr.
13987 auto *CE
= dyn_cast
<CastExpr
>(SubE
);
13988 if (CE
&& CE
->getCastKind() == CK_NoOp
)
13989 SubE
= CE
->getSubExpr();
13990 SubE
= SubE
->IgnoreParens();
13991 if (auto *BE
= dyn_cast
<CXXBindTemporaryExpr
>(SubE
))
13992 SubE
= BE
->getSubExpr();
13993 if (isa
<LambdaExpr
>(SubE
)) {
13994 // For the conversion to block pointer on a lambda expression, we
13995 // construct a special BlockLiteral instead; this doesn't really make
13996 // a difference in ARC, but outside of ARC the resulting block literal
13997 // follows the normal lifetime rules for block literals instead of being
13999 PushExpressionEvaluationContext(
14000 ExpressionEvaluationContext::PotentiallyEvaluated
);
14001 ExprResult BlockExp
= BuildBlockForLambdaConversion(
14002 Exp
.get()->getExprLoc(), Exp
.get()->getExprLoc(), Method
, Exp
.get());
14003 PopExpressionEvaluationContext();
14005 // FIXME: This note should be produced by a CodeSynthesisContext.
14006 if (BlockExp
.isInvalid())
14007 Diag(Exp
.get()->getExprLoc(), diag::note_lambda_to_block_conv
);
14012 QualType ResultType
= Method
->getReturnType();
14013 ExprValueKind VK
= Expr::getValueKindForType(ResultType
);
14014 ResultType
= ResultType
.getNonLValueExprType(Context
);
14015 if (Method
->isExplicitObjectMemberFunction()) {
14016 ExprResult FnExpr
=
14017 CreateFunctionRefExpr(*this, Method
, FoundDecl
, Exp
.get(),
14018 HadMultipleCandidates
, E
->getBeginLoc());
14019 if (FnExpr
.isInvalid())
14020 return ExprError();
14021 Expr
*ObjectParam
= Exp
.get();
14022 CE
= CallExpr::Create(Context
, FnExpr
.get(), MultiExprArg(&ObjectParam
, 1),
14023 ResultType
, VK
, Exp
.get()->getEndLoc(),
14024 CurFPFeatureOverrides());
14027 BuildMemberExpr(Exp
.get(), /*IsArrow=*/false, SourceLocation(),
14028 NestedNameSpecifierLoc(), SourceLocation(), Method
,
14029 DeclAccessPair::make(FoundDecl
, FoundDecl
->getAccess()),
14030 HadMultipleCandidates
, DeclarationNameInfo(),
14031 Context
.BoundMemberTy
, VK_PRValue
, OK_Ordinary
);
14033 CE
= CXXMemberCallExpr::Create(Context
, ME
, /*Args=*/{}, ResultType
, VK
,
14034 Exp
.get()->getEndLoc(),
14035 CurFPFeatureOverrides());
14038 if (CheckFunctionCall(Method
, CE
,
14039 Method
->getType()->castAs
<FunctionProtoType
>()))
14040 return ExprError();
14042 return CheckForImmediateInvocation(CE
, CE
->getDirectCallee());
14045 /// Create a unary operation that may resolve to an overloaded
14048 /// \param OpLoc The location of the operator itself (e.g., '*').
14050 /// \param Opc The UnaryOperatorKind that describes this operator.
14052 /// \param Fns The set of non-member functions that will be
14053 /// considered by overload resolution. The caller needs to build this
14054 /// set based on the context using, e.g.,
14055 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14056 /// set should not contain any member functions; those will be added
14057 /// by CreateOverloadedUnaryOp().
14059 /// \param Input The input argument.
14061 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc
, UnaryOperatorKind Opc
,
14062 const UnresolvedSetImpl
&Fns
,
14063 Expr
*Input
, bool PerformADL
) {
14064 OverloadedOperatorKind Op
= UnaryOperator::getOverloadedOperator(Opc
);
14065 assert(Op
!= OO_None
&& "Invalid opcode for overloaded unary operator");
14066 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
14067 // TODO: provide better source location info.
14068 DeclarationNameInfo
OpNameInfo(OpName
, OpLoc
);
14070 if (checkPlaceholderForOverload(*this, Input
))
14071 return ExprError();
14073 Expr
*Args
[2] = { Input
, nullptr };
14074 unsigned NumArgs
= 1;
14076 // For post-increment and post-decrement, add the implicit '0' as
14077 // the second argument, so that we know this is a post-increment or
14079 if (Opc
== UO_PostInc
|| Opc
== UO_PostDec
) {
14080 llvm::APSInt
Zero(Context
.getTypeSize(Context
.IntTy
), false);
14081 Args
[1] = IntegerLiteral::Create(Context
, Zero
, Context
.IntTy
,
14086 ArrayRef
<Expr
*> ArgsArray(Args
, NumArgs
);
14088 if (Input
->isTypeDependent()) {
14090 return UnaryOperator::Create(Context
, Input
, Opc
, Context
.DependentTy
,
14091 VK_PRValue
, OK_Ordinary
, OpLoc
, false,
14092 CurFPFeatureOverrides());
14094 CXXRecordDecl
*NamingClass
= nullptr; // lookup ignores member operators
14095 ExprResult Fn
= CreateUnresolvedLookupExpr(
14096 NamingClass
, NestedNameSpecifierLoc(), OpNameInfo
, Fns
);
14097 if (Fn
.isInvalid())
14098 return ExprError();
14099 return CXXOperatorCallExpr::Create(Context
, Op
, Fn
.get(), ArgsArray
,
14100 Context
.DependentTy
, VK_PRValue
, OpLoc
,
14101 CurFPFeatureOverrides());
14104 // Build an empty overload set.
14105 OverloadCandidateSet
CandidateSet(OpLoc
, OverloadCandidateSet::CSK_Operator
);
14107 // Add the candidates from the given function set.
14108 AddNonMemberOperatorCandidates(Fns
, ArgsArray
, CandidateSet
);
14110 // Add operator candidates that are member functions.
14111 AddMemberOperatorCandidates(Op
, OpLoc
, ArgsArray
, CandidateSet
);
14113 // Add candidates from ADL.
14115 AddArgumentDependentLookupCandidates(OpName
, OpLoc
, ArgsArray
,
14116 /*ExplicitTemplateArgs*/nullptr,
14120 // Add builtin operator candidates.
14121 AddBuiltinOperatorCandidates(Op
, OpLoc
, ArgsArray
, CandidateSet
);
14123 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
14125 // Perform overload resolution.
14126 OverloadCandidateSet::iterator Best
;
14127 switch (CandidateSet
.BestViableFunction(*this, OpLoc
, Best
)) {
14129 // We found a built-in operator or an overloaded operator.
14130 FunctionDecl
*FnDecl
= Best
->Function
;
14133 Expr
*Base
= nullptr;
14134 // We matched an overloaded operator. Build a call to that
14137 // Convert the arguments.
14138 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(FnDecl
)) {
14139 CheckMemberOperatorAccess(OpLoc
, Input
, nullptr, Best
->FoundDecl
);
14141 ExprResult InputInit
;
14142 if (Method
->isExplicitObjectMemberFunction())
14143 InputInit
= InitializeExplicitObjectArgument(*this, Input
, Method
);
14145 InputInit
= PerformImplicitObjectArgumentInitialization(
14146 Input
, /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
14147 if (InputInit
.isInvalid())
14148 return ExprError();
14149 Base
= Input
= InputInit
.get();
14151 // Convert the arguments.
14152 ExprResult InputInit
14153 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14155 FnDecl
->getParamDecl(0)),
14158 if (InputInit
.isInvalid())
14159 return ExprError();
14160 Input
= InputInit
.get();
14163 // Build the actual expression node.
14164 ExprResult FnExpr
= CreateFunctionRefExpr(*this, FnDecl
, Best
->FoundDecl
,
14165 Base
, HadMultipleCandidates
,
14167 if (FnExpr
.isInvalid())
14168 return ExprError();
14170 // Determine the result type.
14171 QualType ResultTy
= FnDecl
->getReturnType();
14172 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
14173 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
14176 CallExpr
*TheCall
= CXXOperatorCallExpr::Create(
14177 Context
, Op
, FnExpr
.get(), ArgsArray
, ResultTy
, VK
, OpLoc
,
14178 CurFPFeatureOverrides(), Best
->IsADLCandidate
);
14180 if (CheckCallReturnType(FnDecl
->getReturnType(), OpLoc
, TheCall
, FnDecl
))
14181 return ExprError();
14183 if (CheckFunctionCall(FnDecl
, TheCall
,
14184 FnDecl
->getType()->castAs
<FunctionProtoType
>()))
14185 return ExprError();
14186 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), FnDecl
);
14188 // We matched a built-in operator. Convert the arguments, then
14189 // break out so that we will build the appropriate built-in
14191 ExprResult InputRes
= PerformImplicitConversion(
14192 Input
, Best
->BuiltinParamTypes
[0], Best
->Conversions
[0], AA_Passing
,
14193 CCK_ForBuiltinOverloadedOp
);
14194 if (InputRes
.isInvalid())
14195 return ExprError();
14196 Input
= InputRes
.get();
14201 case OR_No_Viable_Function
:
14202 // This is an erroneous use of an operator which can be overloaded by
14203 // a non-member function. Check for non-member operators which were
14204 // defined too late to be candidates.
14205 if (DiagnoseTwoPhaseOperatorLookup(*this, Op
, OpLoc
, ArgsArray
))
14206 // FIXME: Recover by calling the found function.
14207 return ExprError();
14209 // No viable function; fall through to handling this as a
14210 // built-in operator, which will produce an error message for us.
14214 CandidateSet
.NoteCandidates(
14215 PartialDiagnosticAt(OpLoc
,
14216 PDiag(diag::err_ovl_ambiguous_oper_unary
)
14217 << UnaryOperator::getOpcodeStr(Opc
)
14218 << Input
->getType() << Input
->getSourceRange()),
14219 *this, OCD_AmbiguousCandidates
, ArgsArray
,
14220 UnaryOperator::getOpcodeStr(Opc
), OpLoc
);
14221 return ExprError();
14224 CandidateSet
.NoteCandidates(
14225 PartialDiagnosticAt(OpLoc
, PDiag(diag::err_ovl_deleted_oper
)
14226 << UnaryOperator::getOpcodeStr(Opc
)
14227 << Input
->getSourceRange()),
14228 *this, OCD_AllCandidates
, ArgsArray
, UnaryOperator::getOpcodeStr(Opc
),
14230 return ExprError();
14233 // Either we found no viable overloaded operator or we matched a
14234 // built-in operator. In either case, fall through to trying to
14235 // build a built-in operation.
14236 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
14239 /// Perform lookup for an overloaded binary operator.
14240 void Sema::LookupOverloadedBinOp(OverloadCandidateSet
&CandidateSet
,
14241 OverloadedOperatorKind Op
,
14242 const UnresolvedSetImpl
&Fns
,
14243 ArrayRef
<Expr
*> Args
, bool PerformADL
) {
14244 SourceLocation OpLoc
= CandidateSet
.getLocation();
14246 OverloadedOperatorKind ExtraOp
=
14247 CandidateSet
.getRewriteInfo().AllowRewrittenCandidates
14248 ? getRewrittenOverloadedOperator(Op
)
14251 // Add the candidates from the given function set. This also adds the
14252 // rewritten candidates using these functions if necessary.
14253 AddNonMemberOperatorCandidates(Fns
, Args
, CandidateSet
);
14255 // Add operator candidates that are member functions.
14256 AddMemberOperatorCandidates(Op
, OpLoc
, Args
, CandidateSet
);
14257 if (CandidateSet
.getRewriteInfo().allowsReversed(Op
))
14258 AddMemberOperatorCandidates(Op
, OpLoc
, {Args
[1], Args
[0]}, CandidateSet
,
14259 OverloadCandidateParamOrder::Reversed
);
14261 // In C++20, also add any rewritten member candidates.
14263 AddMemberOperatorCandidates(ExtraOp
, OpLoc
, Args
, CandidateSet
);
14264 if (CandidateSet
.getRewriteInfo().allowsReversed(ExtraOp
))
14265 AddMemberOperatorCandidates(ExtraOp
, OpLoc
, {Args
[1], Args
[0]},
14267 OverloadCandidateParamOrder::Reversed
);
14270 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14271 // performed for an assignment operator (nor for operator[] nor operator->,
14272 // which don't get here).
14273 if (Op
!= OO_Equal
&& PerformADL
) {
14274 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
14275 AddArgumentDependentLookupCandidates(OpName
, OpLoc
, Args
,
14276 /*ExplicitTemplateArgs*/ nullptr,
14279 DeclarationName ExtraOpName
=
14280 Context
.DeclarationNames
.getCXXOperatorName(ExtraOp
);
14281 AddArgumentDependentLookupCandidates(ExtraOpName
, OpLoc
, Args
,
14282 /*ExplicitTemplateArgs*/ nullptr,
14287 // Add builtin operator candidates.
14289 // FIXME: We don't add any rewritten candidates here. This is strictly
14290 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14291 // resulting in our selecting a rewritten builtin candidate. For example:
14293 // enum class E { e };
14294 // bool operator!=(E, E) requires false;
14295 // bool k = E::e != E::e;
14297 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14298 // it seems unreasonable to consider rewritten builtin candidates. A core
14299 // issue has been filed proposing to removed this requirement.
14300 AddBuiltinOperatorCandidates(Op
, OpLoc
, Args
, CandidateSet
);
14303 /// Create a binary operation that may resolve to an overloaded
14306 /// \param OpLoc The location of the operator itself (e.g., '+').
14308 /// \param Opc The BinaryOperatorKind that describes this operator.
14310 /// \param Fns The set of non-member functions that will be
14311 /// considered by overload resolution. The caller needs to build this
14312 /// set based on the context using, e.g.,
14313 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14314 /// set should not contain any member functions; those will be added
14315 /// by CreateOverloadedBinOp().
14317 /// \param LHS Left-hand argument.
14318 /// \param RHS Right-hand argument.
14319 /// \param PerformADL Whether to consider operator candidates found by ADL.
14320 /// \param AllowRewrittenCandidates Whether to consider candidates found by
14321 /// C++20 operator rewrites.
14322 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
14323 /// the function in question. Such a function is never a candidate in
14324 /// our overload resolution. This also enables synthesizing a three-way
14325 /// comparison from < and == as described in C++20 [class.spaceship]p1.
14326 ExprResult
Sema::CreateOverloadedBinOp(SourceLocation OpLoc
,
14327 BinaryOperatorKind Opc
,
14328 const UnresolvedSetImpl
&Fns
, Expr
*LHS
,
14329 Expr
*RHS
, bool PerformADL
,
14330 bool AllowRewrittenCandidates
,
14331 FunctionDecl
*DefaultedFn
) {
14332 Expr
*Args
[2] = { LHS
, RHS
};
14333 LHS
=RHS
=nullptr; // Please use only Args instead of LHS/RHS couple
14335 if (!getLangOpts().CPlusPlus20
)
14336 AllowRewrittenCandidates
= false;
14338 OverloadedOperatorKind Op
= BinaryOperator::getOverloadedOperator(Opc
);
14340 // If either side is type-dependent, create an appropriate dependent
14342 if (Args
[0]->isTypeDependent() || Args
[1]->isTypeDependent()) {
14344 // If there are no functions to store, just build a dependent
14345 // BinaryOperator or CompoundAssignment.
14346 if (BinaryOperator::isCompoundAssignmentOp(Opc
))
14347 return CompoundAssignOperator::Create(
14348 Context
, Args
[0], Args
[1], Opc
, Context
.DependentTy
, VK_LValue
,
14349 OK_Ordinary
, OpLoc
, CurFPFeatureOverrides(), Context
.DependentTy
,
14350 Context
.DependentTy
);
14351 return BinaryOperator::Create(
14352 Context
, Args
[0], Args
[1], Opc
, Context
.DependentTy
, VK_PRValue
,
14353 OK_Ordinary
, OpLoc
, CurFPFeatureOverrides());
14356 // FIXME: save results of ADL from here?
14357 CXXRecordDecl
*NamingClass
= nullptr; // lookup ignores member operators
14358 // TODO: provide better source location info in DNLoc component.
14359 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
14360 DeclarationNameInfo
OpNameInfo(OpName
, OpLoc
);
14361 ExprResult Fn
= CreateUnresolvedLookupExpr(
14362 NamingClass
, NestedNameSpecifierLoc(), OpNameInfo
, Fns
, PerformADL
);
14363 if (Fn
.isInvalid())
14364 return ExprError();
14365 return CXXOperatorCallExpr::Create(Context
, Op
, Fn
.get(), Args
,
14366 Context
.DependentTy
, VK_PRValue
, OpLoc
,
14367 CurFPFeatureOverrides());
14370 // Always do placeholder-like conversions on the RHS.
14371 if (checkPlaceholderForOverload(*this, Args
[1]))
14372 return ExprError();
14374 // Do placeholder-like conversion on the LHS; note that we should
14375 // not get here with a PseudoObject LHS.
14376 assert(Args
[0]->getObjectKind() != OK_ObjCProperty
);
14377 if (checkPlaceholderForOverload(*this, Args
[0]))
14378 return ExprError();
14380 // If this is the assignment operator, we only perform overload resolution
14381 // if the left-hand side is a class or enumeration type. This is actually
14382 // a hack. The standard requires that we do overload resolution between the
14383 // various built-in candidates, but as DR507 points out, this can lead to
14384 // problems. So we do it this way, which pretty much follows what GCC does.
14385 // Note that we go the traditional code path for compound assignment forms.
14386 if (Opc
== BO_Assign
&& !Args
[0]->getType()->isOverloadableType())
14387 return CreateBuiltinBinOp(OpLoc
, Opc
, Args
[0], Args
[1]);
14389 // If this is the .* operator, which is not overloadable, just
14390 // create a built-in binary operator.
14391 if (Opc
== BO_PtrMemD
)
14392 return CreateBuiltinBinOp(OpLoc
, Opc
, Args
[0], Args
[1]);
14394 // Build the overload set.
14395 OverloadCandidateSet
CandidateSet(OpLoc
, OverloadCandidateSet::CSK_Operator
,
14396 OverloadCandidateSet::OperatorRewriteInfo(
14397 Op
, OpLoc
, AllowRewrittenCandidates
));
14399 CandidateSet
.exclude(DefaultedFn
);
14400 LookupOverloadedBinOp(CandidateSet
, Op
, Fns
, Args
, PerformADL
);
14402 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
14404 // Perform overload resolution.
14405 OverloadCandidateSet::iterator Best
;
14406 switch (CandidateSet
.BestViableFunction(*this, OpLoc
, Best
)) {
14408 // We found a built-in operator or an overloaded operator.
14409 FunctionDecl
*FnDecl
= Best
->Function
;
14411 bool IsReversed
= Best
->isReversed();
14413 std::swap(Args
[0], Args
[1]);
14417 if (FnDecl
->isInvalidDecl())
14418 return ExprError();
14420 Expr
*Base
= nullptr;
14421 // We matched an overloaded operator. Build a call to that
14424 OverloadedOperatorKind ChosenOp
=
14425 FnDecl
->getDeclName().getCXXOverloadedOperator();
14427 // C++2a [over.match.oper]p9:
14428 // If a rewritten operator== candidate is selected by overload
14429 // resolution for an operator@, its return type shall be cv bool
14430 if (Best
->RewriteKind
&& ChosenOp
== OO_EqualEqual
&&
14431 !FnDecl
->getReturnType()->isBooleanType()) {
14433 FnDecl
->getReturnType()->isIntegralOrUnscopedEnumerationType();
14434 Diag(OpLoc
, IsExtension
? diag::ext_ovl_rewrite_equalequal_not_bool
14435 : diag::err_ovl_rewrite_equalequal_not_bool
)
14436 << FnDecl
->getReturnType() << BinaryOperator::getOpcodeStr(Opc
)
14437 << Args
[0]->getSourceRange() << Args
[1]->getSourceRange();
14438 Diag(FnDecl
->getLocation(), diag::note_declared_at
);
14440 return ExprError();
14443 if (AllowRewrittenCandidates
&& !IsReversed
&&
14444 CandidateSet
.getRewriteInfo().isReversible()) {
14445 // We could have reversed this operator, but didn't. Check if some
14446 // reversed form was a viable candidate, and if so, if it had a
14447 // better conversion for either parameter. If so, this call is
14448 // formally ambiguous, and allowing it is an extension.
14449 llvm::SmallVector
<FunctionDecl
*, 4> AmbiguousWith
;
14450 for (OverloadCandidate
&Cand
: CandidateSet
) {
14451 if (Cand
.Viable
&& Cand
.Function
&& Cand
.isReversed() &&
14452 haveSameParameterTypes(Context
, Cand
.Function
, FnDecl
)) {
14453 for (unsigned ArgIdx
= 0; ArgIdx
< 2; ++ArgIdx
) {
14454 if (CompareImplicitConversionSequences(
14455 *this, OpLoc
, Cand
.Conversions
[ArgIdx
],
14456 Best
->Conversions
[ArgIdx
]) ==
14457 ImplicitConversionSequence::Better
) {
14458 AmbiguousWith
.push_back(Cand
.Function
);
14465 if (!AmbiguousWith
.empty()) {
14466 bool AmbiguousWithSelf
=
14467 AmbiguousWith
.size() == 1 &&
14468 declaresSameEntity(AmbiguousWith
.front(), FnDecl
);
14469 Diag(OpLoc
, diag::ext_ovl_ambiguous_oper_binary_reversed
)
14470 << BinaryOperator::getOpcodeStr(Opc
)
14471 << Args
[0]->getType() << Args
[1]->getType() << AmbiguousWithSelf
14472 << Args
[0]->getSourceRange() << Args
[1]->getSourceRange();
14473 if (AmbiguousWithSelf
) {
14474 Diag(FnDecl
->getLocation(),
14475 diag::note_ovl_ambiguous_oper_binary_reversed_self
);
14476 // Mark member== const or provide matching != to disallow reversed
14478 // struct S { bool operator==(const S&); };
14480 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FnDecl
))
14481 if (Op
== OverloadedOperatorKind::OO_EqualEqual
&&
14483 !MD
->hasCXXExplicitFunctionObjectParameter() &&
14484 Context
.hasSameUnqualifiedType(
14485 MD
->getFunctionObjectParameterType(),
14486 MD
->getParamDecl(0)->getType().getNonReferenceType()) &&
14487 Context
.hasSameUnqualifiedType(
14488 MD
->getFunctionObjectParameterType(),
14489 Args
[0]->getType()) &&
14490 Context
.hasSameUnqualifiedType(
14491 MD
->getFunctionObjectParameterType(),
14492 Args
[1]->getType()))
14493 Diag(FnDecl
->getLocation(),
14494 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const
);
14496 Diag(FnDecl
->getLocation(),
14497 diag::note_ovl_ambiguous_oper_binary_selected_candidate
);
14498 for (auto *F
: AmbiguousWith
)
14499 Diag(F
->getLocation(),
14500 diag::note_ovl_ambiguous_oper_binary_reversed_candidate
);
14505 // Convert the arguments.
14506 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(FnDecl
)) {
14507 // Best->Access is only meaningful for class members.
14508 CheckMemberOperatorAccess(OpLoc
, Args
[0], Args
[1], Best
->FoundDecl
);
14510 ExprResult Arg0
, Arg1
;
14511 unsigned ParamIdx
= 0;
14512 if (Method
->isExplicitObjectMemberFunction()) {
14513 Arg0
= InitializeExplicitObjectArgument(*this, Args
[0], FnDecl
);
14516 Arg0
= PerformImplicitObjectArgumentInitialization(
14517 Args
[0], /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
14519 Arg1
= PerformCopyInitialization(
14520 InitializedEntity::InitializeParameter(
14521 Context
, FnDecl
->getParamDecl(ParamIdx
)),
14522 SourceLocation(), Args
[1]);
14523 if (Arg0
.isInvalid() || Arg1
.isInvalid())
14524 return ExprError();
14526 Base
= Args
[0] = Arg0
.getAs
<Expr
>();
14527 Args
[1] = RHS
= Arg1
.getAs
<Expr
>();
14529 // Convert the arguments.
14530 ExprResult Arg0
= PerformCopyInitialization(
14531 InitializedEntity::InitializeParameter(Context
,
14532 FnDecl
->getParamDecl(0)),
14533 SourceLocation(), Args
[0]);
14534 if (Arg0
.isInvalid())
14535 return ExprError();
14538 PerformCopyInitialization(
14539 InitializedEntity::InitializeParameter(Context
,
14540 FnDecl
->getParamDecl(1)),
14541 SourceLocation(), Args
[1]);
14542 if (Arg1
.isInvalid())
14543 return ExprError();
14544 Args
[0] = LHS
= Arg0
.getAs
<Expr
>();
14545 Args
[1] = RHS
= Arg1
.getAs
<Expr
>();
14548 // Build the actual expression node.
14549 ExprResult FnExpr
= CreateFunctionRefExpr(*this, FnDecl
,
14550 Best
->FoundDecl
, Base
,
14551 HadMultipleCandidates
, OpLoc
);
14552 if (FnExpr
.isInvalid())
14553 return ExprError();
14555 // Determine the result type.
14556 QualType ResultTy
= FnDecl
->getReturnType();
14557 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
14558 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
14561 ArrayRef
<const Expr
*> ArgsArray(Args
, 2);
14562 const Expr
*ImplicitThis
= nullptr;
14564 // We always create a CXXOperatorCallExpr, even for explicit object
14565 // members; CodeGen should take care not to emit the this pointer.
14566 TheCall
= CXXOperatorCallExpr::Create(
14567 Context
, ChosenOp
, FnExpr
.get(), Args
, ResultTy
, VK
, OpLoc
,
14568 CurFPFeatureOverrides(), Best
->IsADLCandidate
);
14570 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(FnDecl
);
14571 Method
&& Method
->isImplicitObjectMemberFunction()) {
14572 // Cut off the implicit 'this'.
14573 ImplicitThis
= ArgsArray
[0];
14574 ArgsArray
= ArgsArray
.slice(1);
14577 if (CheckCallReturnType(FnDecl
->getReturnType(), OpLoc
, TheCall
,
14579 return ExprError();
14581 // Check for a self move.
14582 if (Op
== OO_Equal
)
14583 DiagnoseSelfMove(Args
[0], Args
[1], OpLoc
);
14585 if (ImplicitThis
) {
14586 QualType ThisType
= Context
.getPointerType(ImplicitThis
->getType());
14587 QualType ThisTypeFromDecl
= Context
.getPointerType(
14588 cast
<CXXMethodDecl
>(FnDecl
)->getFunctionObjectParameterType());
14590 CheckArgAlignment(OpLoc
, FnDecl
, "'this'", ThisType
,
14594 checkCall(FnDecl
, nullptr, ImplicitThis
, ArgsArray
,
14595 isa
<CXXMethodDecl
>(FnDecl
), OpLoc
, TheCall
->getSourceRange(),
14596 VariadicDoesNotApply
);
14598 ExprResult R
= MaybeBindToTemporary(TheCall
);
14600 return ExprError();
14602 R
= CheckForImmediateInvocation(R
, FnDecl
);
14604 return ExprError();
14606 // For a rewritten candidate, we've already reversed the arguments
14607 // if needed. Perform the rest of the rewrite now.
14608 if ((Best
->RewriteKind
& CRK_DifferentOperator
) ||
14609 (Op
== OO_Spaceship
&& IsReversed
)) {
14610 if (Op
== OO_ExclaimEqual
) {
14611 assert(ChosenOp
== OO_EqualEqual
&& "unexpected operator name");
14612 R
= CreateBuiltinUnaryOp(OpLoc
, UO_LNot
, R
.get());
14614 assert(ChosenOp
== OO_Spaceship
&& "unexpected operator name");
14615 llvm::APSInt
Zero(Context
.getTypeSize(Context
.IntTy
), false);
14616 Expr
*ZeroLiteral
=
14617 IntegerLiteral::Create(Context
, Zero
, Context
.IntTy
, OpLoc
);
14619 Sema::CodeSynthesisContext Ctx
;
14620 Ctx
.Kind
= Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship
;
14621 Ctx
.Entity
= FnDecl
;
14622 pushCodeSynthesisContext(Ctx
);
14624 R
= CreateOverloadedBinOp(
14625 OpLoc
, Opc
, Fns
, IsReversed
? ZeroLiteral
: R
.get(),
14626 IsReversed
? R
.get() : ZeroLiteral
, /*PerformADL=*/true,
14627 /*AllowRewrittenCandidates=*/false);
14629 popCodeSynthesisContext();
14632 return ExprError();
14634 assert(ChosenOp
== Op
&& "unexpected operator name");
14637 // Make a note in the AST if we did any rewriting.
14638 if (Best
->RewriteKind
!= CRK_None
)
14639 R
= new (Context
) CXXRewrittenBinaryOperator(R
.get(), IsReversed
);
14643 // We matched a built-in operator. Convert the arguments, then
14644 // break out so that we will build the appropriate built-in
14646 ExprResult ArgsRes0
= PerformImplicitConversion(
14647 Args
[0], Best
->BuiltinParamTypes
[0], Best
->Conversions
[0],
14648 AA_Passing
, CCK_ForBuiltinOverloadedOp
);
14649 if (ArgsRes0
.isInvalid())
14650 return ExprError();
14651 Args
[0] = ArgsRes0
.get();
14653 ExprResult ArgsRes1
= PerformImplicitConversion(
14654 Args
[1], Best
->BuiltinParamTypes
[1], Best
->Conversions
[1],
14655 AA_Passing
, CCK_ForBuiltinOverloadedOp
);
14656 if (ArgsRes1
.isInvalid())
14657 return ExprError();
14658 Args
[1] = ArgsRes1
.get();
14663 case OR_No_Viable_Function
: {
14664 // C++ [over.match.oper]p9:
14665 // If the operator is the operator , [...] and there are no
14666 // viable functions, then the operator is assumed to be the
14667 // built-in operator and interpreted according to clause 5.
14668 if (Opc
== BO_Comma
)
14671 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14672 // compare result using '==' and '<'.
14673 if (DefaultedFn
&& Opc
== BO_Cmp
) {
14674 ExprResult E
= BuildSynthesizedThreeWayComparison(OpLoc
, Fns
, Args
[0],
14675 Args
[1], DefaultedFn
);
14676 if (E
.isInvalid() || E
.isUsable())
14680 // For class as left operand for assignment or compound assignment
14681 // operator do not fall through to handling in built-in, but report that
14682 // no overloaded assignment operator found
14683 ExprResult Result
= ExprError();
14684 StringRef OpcStr
= BinaryOperator::getOpcodeStr(Opc
);
14685 auto Cands
= CandidateSet
.CompleteCandidates(*this, OCD_AllCandidates
,
14687 DeferDiagsRAII
DDR(*this,
14688 CandidateSet
.shouldDeferDiags(*this, Args
, OpLoc
));
14689 if (Args
[0]->getType()->isRecordType() &&
14690 Opc
>= BO_Assign
&& Opc
<= BO_OrAssign
) {
14691 Diag(OpLoc
, diag::err_ovl_no_viable_oper
)
14692 << BinaryOperator::getOpcodeStr(Opc
)
14693 << Args
[0]->getSourceRange() << Args
[1]->getSourceRange();
14694 if (Args
[0]->getType()->isIncompleteType()) {
14695 Diag(OpLoc
, diag::note_assign_lhs_incomplete
)
14696 << Args
[0]->getType()
14697 << Args
[0]->getSourceRange() << Args
[1]->getSourceRange();
14700 // This is an erroneous use of an operator which can be overloaded by
14701 // a non-member function. Check for non-member operators which were
14702 // defined too late to be candidates.
14703 if (DiagnoseTwoPhaseOperatorLookup(*this, Op
, OpLoc
, Args
))
14704 // FIXME: Recover by calling the found function.
14705 return ExprError();
14707 // No viable function; try to create a built-in operation, which will
14708 // produce an error. Then, show the non-viable candidates.
14709 Result
= CreateBuiltinBinOp(OpLoc
, Opc
, Args
[0], Args
[1]);
14711 assert(Result
.isInvalid() &&
14712 "C++ binary operator overloading is missing candidates!");
14713 CandidateSet
.NoteCandidates(*this, Args
, Cands
, OpcStr
, OpLoc
);
14718 CandidateSet
.NoteCandidates(
14719 PartialDiagnosticAt(OpLoc
, PDiag(diag::err_ovl_ambiguous_oper_binary
)
14720 << BinaryOperator::getOpcodeStr(Opc
)
14721 << Args
[0]->getType()
14722 << Args
[1]->getType()
14723 << Args
[0]->getSourceRange()
14724 << Args
[1]->getSourceRange()),
14725 *this, OCD_AmbiguousCandidates
, Args
, BinaryOperator::getOpcodeStr(Opc
),
14727 return ExprError();
14730 if (isImplicitlyDeleted(Best
->Function
)) {
14731 FunctionDecl
*DeletedFD
= Best
->Function
;
14732 DefaultedFunctionKind DFK
= getDefaultedFunctionKind(DeletedFD
);
14733 if (DFK
.isSpecialMember()) {
14734 Diag(OpLoc
, diag::err_ovl_deleted_special_oper
)
14735 << Args
[0]->getType() << DFK
.asSpecialMember();
14737 assert(DFK
.isComparison());
14738 Diag(OpLoc
, diag::err_ovl_deleted_comparison
)
14739 << Args
[0]->getType() << DeletedFD
;
14742 // The user probably meant to call this special member. Just
14743 // explain why it's deleted.
14744 NoteDeletedFunction(DeletedFD
);
14745 return ExprError();
14747 CandidateSet
.NoteCandidates(
14748 PartialDiagnosticAt(
14749 OpLoc
, PDiag(diag::err_ovl_deleted_oper
)
14750 << getOperatorSpelling(Best
->Function
->getDeclName()
14751 .getCXXOverloadedOperator())
14752 << Args
[0]->getSourceRange()
14753 << Args
[1]->getSourceRange()),
14754 *this, OCD_AllCandidates
, Args
, BinaryOperator::getOpcodeStr(Opc
),
14756 return ExprError();
14759 // We matched a built-in operator; build it.
14760 return CreateBuiltinBinOp(OpLoc
, Opc
, Args
[0], Args
[1]);
14763 ExprResult
Sema::BuildSynthesizedThreeWayComparison(
14764 SourceLocation OpLoc
, const UnresolvedSetImpl
&Fns
, Expr
*LHS
, Expr
*RHS
,
14765 FunctionDecl
*DefaultedFn
) {
14766 const ComparisonCategoryInfo
*Info
=
14767 Context
.CompCategories
.lookupInfoForType(DefaultedFn
->getReturnType());
14768 // If we're not producing a known comparison category type, we can't
14769 // synthesize a three-way comparison. Let the caller diagnose this.
14771 return ExprResult((Expr
*)nullptr);
14773 // If we ever want to perform this synthesis more generally, we will need to
14774 // apply the temporary materialization conversion to the operands.
14775 assert(LHS
->isGLValue() && RHS
->isGLValue() &&
14776 "cannot use prvalue expressions more than once");
14777 Expr
*OrigLHS
= LHS
;
14778 Expr
*OrigRHS
= RHS
;
14780 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14781 // each of them multiple times below.
14782 LHS
= new (Context
)
14783 OpaqueValueExpr(LHS
->getExprLoc(), LHS
->getType(), LHS
->getValueKind(),
14784 LHS
->getObjectKind(), LHS
);
14785 RHS
= new (Context
)
14786 OpaqueValueExpr(RHS
->getExprLoc(), RHS
->getType(), RHS
->getValueKind(),
14787 RHS
->getObjectKind(), RHS
);
14789 ExprResult Eq
= CreateOverloadedBinOp(OpLoc
, BO_EQ
, Fns
, LHS
, RHS
, true, true,
14791 if (Eq
.isInvalid())
14792 return ExprError();
14794 ExprResult Less
= CreateOverloadedBinOp(OpLoc
, BO_LT
, Fns
, LHS
, RHS
, true,
14795 true, DefaultedFn
);
14796 if (Less
.isInvalid())
14797 return ExprError();
14799 ExprResult Greater
;
14800 if (Info
->isPartial()) {
14801 Greater
= CreateOverloadedBinOp(OpLoc
, BO_LT
, Fns
, RHS
, LHS
, true, true,
14803 if (Greater
.isInvalid())
14804 return ExprError();
14807 // Form the list of comparisons we're going to perform.
14808 struct Comparison
{
14810 ComparisonCategoryResult Result
;
14812 { {Eq
, Info
->isStrong() ? ComparisonCategoryResult::Equal
14813 : ComparisonCategoryResult::Equivalent
},
14814 {Less
, ComparisonCategoryResult::Less
},
14815 {Greater
, ComparisonCategoryResult::Greater
},
14816 {ExprResult(), ComparisonCategoryResult::Unordered
},
14819 int I
= Info
->isPartial() ? 3 : 2;
14821 // Combine the comparisons with suitable conditional expressions.
14823 for (; I
>= 0; --I
) {
14824 // Build a reference to the comparison category constant.
14825 auto *VI
= Info
->lookupValueInfo(Comparisons
[I
].Result
);
14826 // FIXME: Missing a constant for a comparison category. Diagnose this?
14828 return ExprResult((Expr
*)nullptr);
14829 ExprResult ThisResult
=
14830 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI
->VD
);
14831 if (ThisResult
.isInvalid())
14832 return ExprError();
14834 // Build a conditional unless this is the final case.
14835 if (Result
.get()) {
14836 Result
= ActOnConditionalOp(OpLoc
, OpLoc
, Comparisons
[I
].Cmp
.get(),
14837 ThisResult
.get(), Result
.get());
14838 if (Result
.isInvalid())
14839 return ExprError();
14841 Result
= ThisResult
;
14845 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14846 // bind the OpaqueValueExprs before they're (repeatedly) used.
14847 Expr
*SyntacticForm
= BinaryOperator::Create(
14848 Context
, OrigLHS
, OrigRHS
, BO_Cmp
, Result
.get()->getType(),
14849 Result
.get()->getValueKind(), Result
.get()->getObjectKind(), OpLoc
,
14850 CurFPFeatureOverrides());
14851 Expr
*SemanticForm
[] = {LHS
, RHS
, Result
.get()};
14852 return PseudoObjectExpr::Create(Context
, SyntacticForm
, SemanticForm
, 2);
14855 static bool PrepareArgumentsForCallToObjectOfClassType(
14856 Sema
&S
, SmallVectorImpl
<Expr
*> &MethodArgs
, CXXMethodDecl
*Method
,
14857 MultiExprArg Args
, SourceLocation LParenLoc
) {
14859 const auto *Proto
= Method
->getType()->castAs
<FunctionProtoType
>();
14860 unsigned NumParams
= Proto
->getNumParams();
14861 unsigned NumArgsSlots
=
14862 MethodArgs
.size() + std::max
<unsigned>(Args
.size(), NumParams
);
14863 // Build the full argument list for the method call (the implicit object
14864 // parameter is placed at the beginning of the list).
14865 MethodArgs
.reserve(MethodArgs
.size() + NumArgsSlots
);
14866 bool IsError
= false;
14867 // Initialize the implicit object parameter.
14868 // Check the argument types.
14869 for (unsigned i
= 0; i
!= NumParams
; i
++) {
14871 if (i
< Args
.size()) {
14873 ExprResult InputInit
=
14874 S
.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14875 S
.Context
, Method
->getParamDecl(i
)),
14876 SourceLocation(), Arg
);
14877 IsError
|= InputInit
.isInvalid();
14878 Arg
= InputInit
.getAs
<Expr
>();
14880 ExprResult DefArg
=
14881 S
.BuildCXXDefaultArgExpr(LParenLoc
, Method
, Method
->getParamDecl(i
));
14882 if (DefArg
.isInvalid()) {
14886 Arg
= DefArg
.getAs
<Expr
>();
14889 MethodArgs
.push_back(Arg
);
14894 ExprResult
Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc
,
14895 SourceLocation RLoc
,
14897 MultiExprArg ArgExpr
) {
14898 SmallVector
<Expr
*, 2> Args
;
14899 Args
.push_back(Base
);
14900 for (auto *e
: ArgExpr
) {
14903 DeclarationName OpName
=
14904 Context
.DeclarationNames
.getCXXOperatorName(OO_Subscript
);
14906 SourceRange Range
= ArgExpr
.empty()
14908 : SourceRange(ArgExpr
.front()->getBeginLoc(),
14909 ArgExpr
.back()->getEndLoc());
14911 // If either side is type-dependent, create an appropriate dependent
14913 if (Expr::hasAnyTypeDependentArguments(Args
)) {
14915 CXXRecordDecl
*NamingClass
= nullptr; // lookup ignores member operators
14916 // CHECKME: no 'operator' keyword?
14917 DeclarationNameInfo
OpNameInfo(OpName
, LLoc
);
14918 OpNameInfo
.setCXXOperatorNameRange(SourceRange(LLoc
, RLoc
));
14919 ExprResult Fn
= CreateUnresolvedLookupExpr(
14920 NamingClass
, NestedNameSpecifierLoc(), OpNameInfo
, UnresolvedSet
<0>());
14921 if (Fn
.isInvalid())
14922 return ExprError();
14923 // Can't add any actual overloads yet
14925 return CXXOperatorCallExpr::Create(Context
, OO_Subscript
, Fn
.get(), Args
,
14926 Context
.DependentTy
, VK_PRValue
, RLoc
,
14927 CurFPFeatureOverrides());
14930 // Handle placeholders
14931 UnbridgedCastsSet UnbridgedCasts
;
14932 if (checkArgPlaceholdersForOverload(*this, Args
, UnbridgedCasts
)) {
14933 return ExprError();
14935 // Build an empty overload set.
14936 OverloadCandidateSet
CandidateSet(LLoc
, OverloadCandidateSet::CSK_Operator
);
14938 // Subscript can only be overloaded as a member function.
14940 // Add operator candidates that are member functions.
14941 AddMemberOperatorCandidates(OO_Subscript
, LLoc
, Args
, CandidateSet
);
14943 // Add builtin operator candidates.
14944 if (Args
.size() == 2)
14945 AddBuiltinOperatorCandidates(OO_Subscript
, LLoc
, Args
, CandidateSet
);
14947 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
14949 // Perform overload resolution.
14950 OverloadCandidateSet::iterator Best
;
14951 switch (CandidateSet
.BestViableFunction(*this, LLoc
, Best
)) {
14953 // We found a built-in operator or an overloaded operator.
14954 FunctionDecl
*FnDecl
= Best
->Function
;
14957 // We matched an overloaded operator. Build a call to that
14960 CheckMemberOperatorAccess(LLoc
, Args
[0], ArgExpr
, Best
->FoundDecl
);
14962 // Convert the arguments.
14963 CXXMethodDecl
*Method
= cast
<CXXMethodDecl
>(FnDecl
);
14964 SmallVector
<Expr
*, 2> MethodArgs
;
14966 // Handle 'this' parameter if the selected function is not static.
14967 if (Method
->isExplicitObjectMemberFunction()) {
14969 InitializeExplicitObjectArgument(*this, Args
[0], Method
);
14970 if (Res
.isInvalid())
14971 return ExprError();
14972 Args
[0] = Res
.get();
14974 } else if (Method
->isInstance()) {
14975 ExprResult Arg0
= PerformImplicitObjectArgumentInitialization(
14976 Args
[0], /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
14977 if (Arg0
.isInvalid())
14978 return ExprError();
14980 MethodArgs
.push_back(Arg0
.get());
14983 bool IsError
= PrepareArgumentsForCallToObjectOfClassType(
14984 *this, MethodArgs
, Method
, ArgExpr
, LLoc
);
14986 return ExprError();
14988 // Build the actual expression node.
14989 DeclarationNameInfo
OpLocInfo(OpName
, LLoc
);
14990 OpLocInfo
.setCXXOperatorNameRange(SourceRange(LLoc
, RLoc
));
14991 ExprResult FnExpr
= CreateFunctionRefExpr(
14992 *this, FnDecl
, Best
->FoundDecl
, Base
, HadMultipleCandidates
,
14993 OpLocInfo
.getLoc(), OpLocInfo
.getInfo());
14994 if (FnExpr
.isInvalid())
14995 return ExprError();
14997 // Determine the result type
14998 QualType ResultTy
= FnDecl
->getReturnType();
14999 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
15000 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
15003 if (Method
->isInstance())
15004 TheCall
= CXXOperatorCallExpr::Create(
15005 Context
, OO_Subscript
, FnExpr
.get(), MethodArgs
, ResultTy
, VK
,
15006 RLoc
, CurFPFeatureOverrides());
15009 CallExpr::Create(Context
, FnExpr
.get(), MethodArgs
, ResultTy
, VK
,
15010 RLoc
, CurFPFeatureOverrides());
15012 if (CheckCallReturnType(FnDecl
->getReturnType(), LLoc
, TheCall
, FnDecl
))
15013 return ExprError();
15015 if (CheckFunctionCall(Method
, TheCall
,
15016 Method
->getType()->castAs
<FunctionProtoType
>()))
15017 return ExprError();
15019 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
),
15022 // We matched a built-in operator. Convert the arguments, then
15023 // break out so that we will build the appropriate built-in
15025 ExprResult ArgsRes0
= PerformImplicitConversion(
15026 Args
[0], Best
->BuiltinParamTypes
[0], Best
->Conversions
[0],
15027 AA_Passing
, CCK_ForBuiltinOverloadedOp
);
15028 if (ArgsRes0
.isInvalid())
15029 return ExprError();
15030 Args
[0] = ArgsRes0
.get();
15032 ExprResult ArgsRes1
= PerformImplicitConversion(
15033 Args
[1], Best
->BuiltinParamTypes
[1], Best
->Conversions
[1],
15034 AA_Passing
, CCK_ForBuiltinOverloadedOp
);
15035 if (ArgsRes1
.isInvalid())
15036 return ExprError();
15037 Args
[1] = ArgsRes1
.get();
15043 case OR_No_Viable_Function
: {
15044 PartialDiagnostic PD
=
15045 CandidateSet
.empty()
15046 ? (PDiag(diag::err_ovl_no_oper
)
15047 << Args
[0]->getType() << /*subscript*/ 0
15048 << Args
[0]->getSourceRange() << Range
)
15049 : (PDiag(diag::err_ovl_no_viable_subscript
)
15050 << Args
[0]->getType() << Args
[0]->getSourceRange() << Range
);
15051 CandidateSet
.NoteCandidates(PartialDiagnosticAt(LLoc
, PD
), *this,
15052 OCD_AllCandidates
, ArgExpr
, "[]", LLoc
);
15053 return ExprError();
15057 if (Args
.size() == 2) {
15058 CandidateSet
.NoteCandidates(
15059 PartialDiagnosticAt(
15060 LLoc
, PDiag(diag::err_ovl_ambiguous_oper_binary
)
15061 << "[]" << Args
[0]->getType() << Args
[1]->getType()
15062 << Args
[0]->getSourceRange() << Range
),
15063 *this, OCD_AmbiguousCandidates
, Args
, "[]", LLoc
);
15065 CandidateSet
.NoteCandidates(
15066 PartialDiagnosticAt(LLoc
,
15067 PDiag(diag::err_ovl_ambiguous_subscript_call
)
15068 << Args
[0]->getType()
15069 << Args
[0]->getSourceRange() << Range
),
15070 *this, OCD_AmbiguousCandidates
, Args
, "[]", LLoc
);
15072 return ExprError();
15075 CandidateSet
.NoteCandidates(
15076 PartialDiagnosticAt(LLoc
, PDiag(diag::err_ovl_deleted_oper
)
15077 << "[]" << Args
[0]->getSourceRange()
15079 *this, OCD_AllCandidates
, Args
, "[]", LLoc
);
15080 return ExprError();
15083 // We matched a built-in operator; build it.
15084 return CreateBuiltinArraySubscriptExpr(Args
[0], LLoc
, Args
[1], RLoc
);
15087 /// BuildCallToMemberFunction - Build a call to a member
15088 /// function. MemExpr is the expression that refers to the member
15089 /// function (and includes the object parameter), Args/NumArgs are the
15090 /// arguments to the function call (not including the object
15091 /// parameter). The caller needs to validate that the member
15092 /// expression refers to a non-static member function or an overloaded
15093 /// member function.
15094 ExprResult
Sema::BuildCallToMemberFunction(Scope
*S
, Expr
*MemExprE
,
15095 SourceLocation LParenLoc
,
15097 SourceLocation RParenLoc
,
15098 Expr
*ExecConfig
, bool IsExecConfig
,
15099 bool AllowRecovery
) {
15100 assert(MemExprE
->getType() == Context
.BoundMemberTy
||
15101 MemExprE
->getType() == Context
.OverloadTy
);
15103 // Dig out the member expression. This holds both the object
15104 // argument and the member function we're referring to.
15105 Expr
*NakedMemExpr
= MemExprE
->IgnoreParens();
15107 // Determine whether this is a call to a pointer-to-member function.
15108 if (BinaryOperator
*op
= dyn_cast
<BinaryOperator
>(NakedMemExpr
)) {
15109 assert(op
->getType() == Context
.BoundMemberTy
);
15110 assert(op
->getOpcode() == BO_PtrMemD
|| op
->getOpcode() == BO_PtrMemI
);
15113 op
->getRHS()->getType()->castAs
<MemberPointerType
>()->getPointeeType();
15115 const FunctionProtoType
*proto
= fnType
->castAs
<FunctionProtoType
>();
15116 QualType resultType
= proto
->getCallResultType(Context
);
15117 ExprValueKind valueKind
= Expr::getValueKindForType(proto
->getReturnType());
15119 // Check that the object type isn't more qualified than the
15120 // member function we're calling.
15121 Qualifiers funcQuals
= proto
->getMethodQuals();
15123 QualType objectType
= op
->getLHS()->getType();
15124 if (op
->getOpcode() == BO_PtrMemI
)
15125 objectType
= objectType
->castAs
<PointerType
>()->getPointeeType();
15126 Qualifiers objectQuals
= objectType
.getQualifiers();
15128 Qualifiers difference
= objectQuals
- funcQuals
;
15129 difference
.removeObjCGCAttr();
15130 difference
.removeAddressSpace();
15132 std::string qualsString
= difference
.getAsString();
15133 Diag(LParenLoc
, diag::err_pointer_to_member_call_drops_quals
)
15134 << fnType
.getUnqualifiedType()
15136 << (qualsString
.find(' ') == std::string::npos
? 1 : 2);
15139 CXXMemberCallExpr
*call
= CXXMemberCallExpr::Create(
15140 Context
, MemExprE
, Args
, resultType
, valueKind
, RParenLoc
,
15141 CurFPFeatureOverrides(), proto
->getNumParams());
15143 if (CheckCallReturnType(proto
->getReturnType(), op
->getRHS()->getBeginLoc(),
15145 return ExprError();
15147 if (ConvertArgumentsForCall(call
, op
, nullptr, proto
, Args
, RParenLoc
))
15148 return ExprError();
15150 if (CheckOtherCall(call
, proto
))
15151 return ExprError();
15153 return MaybeBindToTemporary(call
);
15156 // We only try to build a recovery expr at this level if we can preserve
15157 // the return type, otherwise we return ExprError() and let the caller
15159 auto BuildRecoveryExpr
= [&](QualType Type
) {
15160 if (!AllowRecovery
)
15161 return ExprError();
15162 std::vector
<Expr
*> SubExprs
= {MemExprE
};
15163 llvm::append_range(SubExprs
, Args
);
15164 return CreateRecoveryExpr(MemExprE
->getBeginLoc(), RParenLoc
, SubExprs
,
15167 if (isa
<CXXPseudoDestructorExpr
>(NakedMemExpr
))
15168 return CallExpr::Create(Context
, MemExprE
, Args
, Context
.VoidTy
, VK_PRValue
,
15169 RParenLoc
, CurFPFeatureOverrides());
15171 UnbridgedCastsSet UnbridgedCasts
;
15172 if (checkArgPlaceholdersForOverload(*this, Args
, UnbridgedCasts
))
15173 return ExprError();
15175 MemberExpr
*MemExpr
;
15176 CXXMethodDecl
*Method
= nullptr;
15177 bool HadMultipleCandidates
= false;
15178 DeclAccessPair FoundDecl
= DeclAccessPair::make(nullptr, AS_public
);
15179 NestedNameSpecifier
*Qualifier
= nullptr;
15180 if (isa
<MemberExpr
>(NakedMemExpr
)) {
15181 MemExpr
= cast
<MemberExpr
>(NakedMemExpr
);
15182 Method
= cast
<CXXMethodDecl
>(MemExpr
->getMemberDecl());
15183 FoundDecl
= MemExpr
->getFoundDecl();
15184 Qualifier
= MemExpr
->getQualifier();
15185 UnbridgedCasts
.restore();
15187 UnresolvedMemberExpr
*UnresExpr
= cast
<UnresolvedMemberExpr
>(NakedMemExpr
);
15188 Qualifier
= UnresExpr
->getQualifier();
15190 QualType ObjectType
= UnresExpr
->getBaseType();
15191 Expr::Classification ObjectClassification
15192 = UnresExpr
->isArrow()? Expr::Classification::makeSimpleLValue()
15193 : UnresExpr
->getBase()->Classify(Context
);
15195 // Add overload candidates
15196 OverloadCandidateSet
CandidateSet(UnresExpr
->getMemberLoc(),
15197 OverloadCandidateSet::CSK_Normal
);
15199 // FIXME: avoid copy.
15200 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
15201 if (UnresExpr
->hasExplicitTemplateArgs()) {
15202 UnresExpr
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
15203 TemplateArgs
= &TemplateArgsBuffer
;
15206 for (UnresolvedMemberExpr::decls_iterator I
= UnresExpr
->decls_begin(),
15207 E
= UnresExpr
->decls_end(); I
!= E
; ++I
) {
15209 QualType ExplicitObjectType
= ObjectType
;
15211 NamedDecl
*Func
= *I
;
15212 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(Func
->getDeclContext());
15213 if (isa
<UsingShadowDecl
>(Func
))
15214 Func
= cast
<UsingShadowDecl
>(Func
)->getTargetDecl();
15216 bool HasExplicitParameter
= false;
15217 if (const auto *M
= dyn_cast
<FunctionDecl
>(Func
);
15218 M
&& M
->hasCXXExplicitFunctionObjectParameter())
15219 HasExplicitParameter
= true;
15220 else if (const auto *M
= dyn_cast
<FunctionTemplateDecl
>(Func
);
15222 M
->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15223 HasExplicitParameter
= true;
15225 if (HasExplicitParameter
)
15226 ExplicitObjectType
= GetExplicitObjectType(*this, UnresExpr
);
15228 // Microsoft supports direct constructor calls.
15229 if (getLangOpts().MicrosoftExt
&& isa
<CXXConstructorDecl
>(Func
)) {
15230 AddOverloadCandidate(cast
<CXXConstructorDecl
>(Func
), I
.getPair(), Args
,
15232 /*SuppressUserConversions*/ false);
15233 } else if ((Method
= dyn_cast
<CXXMethodDecl
>(Func
))) {
15234 // If explicit template arguments were provided, we can't call a
15235 // non-template member function.
15239 AddMethodCandidate(Method
, I
.getPair(), ActingDC
, ExplicitObjectType
,
15240 ObjectClassification
, Args
, CandidateSet
,
15241 /*SuppressUserConversions=*/false);
15243 AddMethodTemplateCandidate(cast
<FunctionTemplateDecl
>(Func
),
15244 I
.getPair(), ActingDC
, TemplateArgs
,
15245 ExplicitObjectType
, ObjectClassification
,
15246 Args
, CandidateSet
,
15247 /*SuppressUserConversions=*/false);
15251 HadMultipleCandidates
= (CandidateSet
.size() > 1);
15253 DeclarationName DeclName
= UnresExpr
->getMemberName();
15255 UnbridgedCasts
.restore();
15257 OverloadCandidateSet::iterator Best
;
15258 bool Succeeded
= false;
15259 switch (CandidateSet
.BestViableFunction(*this, UnresExpr
->getBeginLoc(),
15262 Method
= cast
<CXXMethodDecl
>(Best
->Function
);
15263 FoundDecl
= Best
->FoundDecl
;
15264 CheckUnresolvedMemberAccess(UnresExpr
, Best
->FoundDecl
);
15265 if (DiagnoseUseOfOverloadedDecl(Best
->FoundDecl
, UnresExpr
->getNameLoc()))
15267 // If FoundDecl is different from Method (such as if one is a template
15268 // and the other a specialization), make sure DiagnoseUseOfDecl is
15270 // FIXME: This would be more comprehensively addressed by modifying
15271 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15273 if (Method
!= FoundDecl
.getDecl() &&
15274 DiagnoseUseOfOverloadedDecl(Method
, UnresExpr
->getNameLoc()))
15279 case OR_No_Viable_Function
:
15280 CandidateSet
.NoteCandidates(
15281 PartialDiagnosticAt(
15282 UnresExpr
->getMemberLoc(),
15283 PDiag(diag::err_ovl_no_viable_member_function_in_call
)
15284 << DeclName
<< MemExprE
->getSourceRange()),
15285 *this, OCD_AllCandidates
, Args
);
15288 CandidateSet
.NoteCandidates(
15289 PartialDiagnosticAt(UnresExpr
->getMemberLoc(),
15290 PDiag(diag::err_ovl_ambiguous_member_call
)
15291 << DeclName
<< MemExprE
->getSourceRange()),
15292 *this, OCD_AmbiguousCandidates
, Args
);
15295 CandidateSet
.NoteCandidates(
15296 PartialDiagnosticAt(UnresExpr
->getMemberLoc(),
15297 PDiag(diag::err_ovl_deleted_member_call
)
15298 << DeclName
<< MemExprE
->getSourceRange()),
15299 *this, OCD_AllCandidates
, Args
);
15302 // Overload resolution fails, try to recover.
15304 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet
, &Best
));
15307 FixOverloadedFunctionReference(MemExprE
, FoundDecl
, Method
);
15308 if (Res
.isInvalid())
15309 return ExprError();
15310 MemExprE
= Res
.get();
15312 // If overload resolution picked a static member
15313 // build a non-member call based on that function.
15314 if (Method
->isStatic()) {
15315 return BuildResolvedCallExpr(MemExprE
, Method
, LParenLoc
, Args
, RParenLoc
,
15316 ExecConfig
, IsExecConfig
);
15319 MemExpr
= cast
<MemberExpr
>(MemExprE
->IgnoreParens());
15322 QualType ResultType
= Method
->getReturnType();
15323 ExprValueKind VK
= Expr::getValueKindForType(ResultType
);
15324 ResultType
= ResultType
.getNonLValueExprType(Context
);
15326 assert(Method
&& "Member call to something that isn't a method?");
15327 const auto *Proto
= Method
->getType()->castAs
<FunctionProtoType
>();
15329 CallExpr
*TheCall
= nullptr;
15330 llvm::SmallVector
<Expr
*, 8> NewArgs
;
15331 if (Method
->isExplicitObjectMemberFunction()) {
15332 PrepareExplicitObjectArgument(*this, Method
, MemExpr
->getBase(), Args
,
15334 // Build the actual expression node.
15335 ExprResult FnExpr
=
15336 CreateFunctionRefExpr(*this, Method
, FoundDecl
, MemExpr
,
15337 HadMultipleCandidates
, MemExpr
->getExprLoc());
15338 if (FnExpr
.isInvalid())
15339 return ExprError();
15342 CallExpr::Create(Context
, FnExpr
.get(), Args
, ResultType
, VK
, RParenLoc
,
15343 CurFPFeatureOverrides(), Proto
->getNumParams());
15345 // Convert the object argument (for a non-static member function call).
15346 // We only need to do this if there was actually an overload; otherwise
15347 // it was done at lookup.
15348 ExprResult ObjectArg
= PerformImplicitObjectArgumentInitialization(
15349 MemExpr
->getBase(), Qualifier
, FoundDecl
, Method
);
15350 if (ObjectArg
.isInvalid())
15351 return ExprError();
15352 MemExpr
->setBase(ObjectArg
.get());
15353 TheCall
= CXXMemberCallExpr::Create(Context
, MemExprE
, Args
, ResultType
, VK
,
15354 RParenLoc
, CurFPFeatureOverrides(),
15355 Proto
->getNumParams());
15358 // Check for a valid return type.
15359 if (CheckCallReturnType(Method
->getReturnType(), MemExpr
->getMemberLoc(),
15361 return BuildRecoveryExpr(ResultType
);
15363 // Convert the rest of the arguments
15364 if (ConvertArgumentsForCall(TheCall
, MemExpr
, Method
, Proto
, Args
,
15366 return BuildRecoveryExpr(ResultType
);
15368 DiagnoseSentinelCalls(Method
, LParenLoc
, Args
);
15370 if (CheckFunctionCall(Method
, TheCall
, Proto
))
15371 return ExprError();
15373 // In the case the method to call was not selected by the overloading
15374 // resolution process, we still need to handle the enable_if attribute. Do
15375 // that here, so it will not hide previous -- and more relevant -- errors.
15376 if (auto *MemE
= dyn_cast
<MemberExpr
>(NakedMemExpr
)) {
15377 if (const EnableIfAttr
*Attr
=
15378 CheckEnableIf(Method
, LParenLoc
, Args
, true)) {
15379 Diag(MemE
->getMemberLoc(),
15380 diag::err_ovl_no_viable_member_function_in_call
)
15381 << Method
<< Method
->getSourceRange();
15382 Diag(Method
->getLocation(),
15383 diag::note_ovl_candidate_disabled_by_function_cond_attr
)
15384 << Attr
->getCond()->getSourceRange() << Attr
->getMessage();
15385 return ExprError();
15389 if (isa
<CXXConstructorDecl
, CXXDestructorDecl
>(CurContext
) &&
15390 TheCall
->getDirectCallee()->isPure()) {
15391 const FunctionDecl
*MD
= TheCall
->getDirectCallee();
15393 if (isa
<CXXThisExpr
>(MemExpr
->getBase()->IgnoreParenCasts()) &&
15394 MemExpr
->performsVirtualDispatch(getLangOpts())) {
15395 Diag(MemExpr
->getBeginLoc(),
15396 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor
)
15397 << MD
->getDeclName() << isa
<CXXDestructorDecl
>(CurContext
)
15398 << MD
->getParent();
15400 Diag(MD
->getBeginLoc(), diag::note_previous_decl
) << MD
->getDeclName();
15401 if (getLangOpts().AppleKext
)
15402 Diag(MemExpr
->getBeginLoc(), diag::note_pure_qualified_call_kext
)
15403 << MD
->getParent() << MD
->getDeclName();
15407 if (auto *DD
= dyn_cast
<CXXDestructorDecl
>(TheCall
->getDirectCallee())) {
15408 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15409 bool CallCanBeVirtual
= !MemExpr
->hasQualifier() || getLangOpts().AppleKext
;
15410 CheckVirtualDtorCall(DD
, MemExpr
->getBeginLoc(), /*IsDelete=*/false,
15411 CallCanBeVirtual
, /*WarnOnNonAbstractTypes=*/true,
15412 MemExpr
->getMemberLoc());
15415 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
),
15416 TheCall
->getDirectCallee());
15419 /// BuildCallToObjectOfClassType - Build a call to an object of class
15420 /// type (C++ [over.call.object]), which can end up invoking an
15421 /// overloaded function call operator (@c operator()) or performing a
15422 /// user-defined conversion on the object argument.
15424 Sema::BuildCallToObjectOfClassType(Scope
*S
, Expr
*Obj
,
15425 SourceLocation LParenLoc
,
15427 SourceLocation RParenLoc
) {
15428 if (checkPlaceholderForOverload(*this, Obj
))
15429 return ExprError();
15430 ExprResult Object
= Obj
;
15432 UnbridgedCastsSet UnbridgedCasts
;
15433 if (checkArgPlaceholdersForOverload(*this, Args
, UnbridgedCasts
))
15434 return ExprError();
15436 assert(Object
.get()->getType()->isRecordType() &&
15437 "Requires object type argument");
15439 // C++ [over.call.object]p1:
15440 // If the primary-expression E in the function call syntax
15441 // evaluates to a class object of type "cv T", then the set of
15442 // candidate functions includes at least the function call
15443 // operators of T. The function call operators of T are obtained by
15444 // ordinary lookup of the name operator() in the context of
15446 OverloadCandidateSet
CandidateSet(LParenLoc
,
15447 OverloadCandidateSet::CSK_Operator
);
15448 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(OO_Call
);
15450 if (RequireCompleteType(LParenLoc
, Object
.get()->getType(),
15451 diag::err_incomplete_object_call
, Object
.get()))
15454 const auto *Record
= Object
.get()->getType()->castAs
<RecordType
>();
15455 LookupResult
R(*this, OpName
, LParenLoc
, LookupOrdinaryName
);
15456 LookupQualifiedName(R
, Record
->getDecl());
15457 R
.suppressAccessDiagnostics();
15459 for (LookupResult::iterator Oper
= R
.begin(), OperEnd
= R
.end();
15460 Oper
!= OperEnd
; ++Oper
) {
15461 AddMethodCandidate(Oper
.getPair(), Object
.get()->getType(),
15462 Object
.get()->Classify(Context
), Args
, CandidateSet
,
15463 /*SuppressUserConversion=*/false);
15466 // When calling a lambda, both the call operator, and
15467 // the conversion operator to function pointer
15468 // are considered. But when constraint checking
15469 // on the call operator fails, it will also fail on the
15470 // conversion operator as the constraints are always the same.
15471 // As the user probably does not intend to perform a surrogate call,
15472 // we filter them out to produce better error diagnostics, ie to avoid
15473 // showing 2 failed overloads instead of one.
15474 bool IgnoreSurrogateFunctions
= false;
15475 if (CandidateSet
.size() == 1 && Record
->getAsCXXRecordDecl()->isLambda()) {
15476 const OverloadCandidate
&Candidate
= *CandidateSet
.begin();
15477 if (!Candidate
.Viable
&&
15478 Candidate
.FailureKind
== ovl_fail_constraints_not_satisfied
)
15479 IgnoreSurrogateFunctions
= true;
15482 // C++ [over.call.object]p2:
15483 // In addition, for each (non-explicit in C++0x) conversion function
15484 // declared in T of the form
15486 // operator conversion-type-id () cv-qualifier;
15488 // where cv-qualifier is the same cv-qualification as, or a
15489 // greater cv-qualification than, cv, and where conversion-type-id
15490 // denotes the type "pointer to function of (P1,...,Pn) returning
15491 // R", or the type "reference to pointer to function of
15492 // (P1,...,Pn) returning R", or the type "reference to function
15493 // of (P1,...,Pn) returning R", a surrogate call function [...]
15494 // is also considered as a candidate function. Similarly,
15495 // surrogate call functions are added to the set of candidate
15496 // functions for each conversion function declared in an
15497 // accessible base class provided the function is not hidden
15498 // within T by another intervening declaration.
15499 const auto &Conversions
=
15500 cast
<CXXRecordDecl
>(Record
->getDecl())->getVisibleConversionFunctions();
15501 for (auto I
= Conversions
.begin(), E
= Conversions
.end();
15502 !IgnoreSurrogateFunctions
&& I
!= E
; ++I
) {
15504 CXXRecordDecl
*ActingContext
= cast
<CXXRecordDecl
>(D
->getDeclContext());
15505 if (isa
<UsingShadowDecl
>(D
))
15506 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
15508 // Skip over templated conversion functions; they aren't
15510 if (isa
<FunctionTemplateDecl
>(D
))
15513 CXXConversionDecl
*Conv
= cast
<CXXConversionDecl
>(D
);
15514 if (!Conv
->isExplicit()) {
15515 // Strip the reference type (if any) and then the pointer type (if
15516 // any) to get down to what might be a function type.
15517 QualType ConvType
= Conv
->getConversionType().getNonReferenceType();
15518 if (const PointerType
*ConvPtrType
= ConvType
->getAs
<PointerType
>())
15519 ConvType
= ConvPtrType
->getPointeeType();
15521 if (const FunctionProtoType
*Proto
= ConvType
->getAs
<FunctionProtoType
>())
15523 AddSurrogateCandidate(Conv
, I
.getPair(), ActingContext
, Proto
,
15524 Object
.get(), Args
, CandidateSet
);
15529 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
15531 // Perform overload resolution.
15532 OverloadCandidateSet::iterator Best
;
15533 switch (CandidateSet
.BestViableFunction(*this, Object
.get()->getBeginLoc(),
15536 // Overload resolution succeeded; we'll build the appropriate call
15540 case OR_No_Viable_Function
: {
15541 PartialDiagnostic PD
=
15542 CandidateSet
.empty()
15543 ? (PDiag(diag::err_ovl_no_oper
)
15544 << Object
.get()->getType() << /*call*/ 1
15545 << Object
.get()->getSourceRange())
15546 : (PDiag(diag::err_ovl_no_viable_object_call
)
15547 << Object
.get()->getType() << Object
.get()->getSourceRange());
15548 CandidateSet
.NoteCandidates(
15549 PartialDiagnosticAt(Object
.get()->getBeginLoc(), PD
), *this,
15550 OCD_AllCandidates
, Args
);
15554 if (!R
.isAmbiguous())
15555 CandidateSet
.NoteCandidates(
15556 PartialDiagnosticAt(Object
.get()->getBeginLoc(),
15557 PDiag(diag::err_ovl_ambiguous_object_call
)
15558 << Object
.get()->getType()
15559 << Object
.get()->getSourceRange()),
15560 *this, OCD_AmbiguousCandidates
, Args
);
15564 CandidateSet
.NoteCandidates(
15565 PartialDiagnosticAt(Object
.get()->getBeginLoc(),
15566 PDiag(diag::err_ovl_deleted_object_call
)
15567 << Object
.get()->getType()
15568 << Object
.get()->getSourceRange()),
15569 *this, OCD_AllCandidates
, Args
);
15573 if (Best
== CandidateSet
.end())
15576 UnbridgedCasts
.restore();
15578 if (Best
->Function
== nullptr) {
15579 // Since there is no function declaration, this is one of the
15580 // surrogate candidates. Dig out the conversion function.
15581 CXXConversionDecl
*Conv
15582 = cast
<CXXConversionDecl
>(
15583 Best
->Conversions
[0].UserDefined
.ConversionFunction
);
15585 CheckMemberOperatorAccess(LParenLoc
, Object
.get(), nullptr,
15587 if (DiagnoseUseOfDecl(Best
->FoundDecl
, LParenLoc
))
15588 return ExprError();
15589 assert(Conv
== Best
->FoundDecl
.getDecl() &&
15590 "Found Decl & conversion-to-functionptr should be same, right?!");
15591 // We selected one of the surrogate functions that converts the
15592 // object parameter to a function pointer. Perform the conversion
15593 // on the object argument, then let BuildCallExpr finish the job.
15595 // Create an implicit member expr to refer to the conversion operator.
15596 // and then call it.
15597 ExprResult Call
= BuildCXXMemberCallExpr(Object
.get(), Best
->FoundDecl
,
15598 Conv
, HadMultipleCandidates
);
15599 if (Call
.isInvalid())
15600 return ExprError();
15601 // Record usage of conversion in an implicit cast.
15602 Call
= ImplicitCastExpr::Create(
15603 Context
, Call
.get()->getType(), CK_UserDefinedConversion
, Call
.get(),
15604 nullptr, VK_PRValue
, CurFPFeatureOverrides());
15606 return BuildCallExpr(S
, Call
.get(), LParenLoc
, Args
, RParenLoc
);
15609 CheckMemberOperatorAccess(LParenLoc
, Object
.get(), nullptr, Best
->FoundDecl
);
15611 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15612 // that calls this method, using Object for the implicit object
15613 // parameter and passing along the remaining arguments.
15614 CXXMethodDecl
*Method
= cast
<CXXMethodDecl
>(Best
->Function
);
15616 // An error diagnostic has already been printed when parsing the declaration.
15617 if (Method
->isInvalidDecl())
15618 return ExprError();
15620 const auto *Proto
= Method
->getType()->castAs
<FunctionProtoType
>();
15621 unsigned NumParams
= Proto
->getNumParams();
15623 DeclarationNameInfo
OpLocInfo(
15624 Context
.DeclarationNames
.getCXXOperatorName(OO_Call
), LParenLoc
);
15625 OpLocInfo
.setCXXOperatorNameRange(SourceRange(LParenLoc
, RParenLoc
));
15626 ExprResult NewFn
= CreateFunctionRefExpr(*this, Method
, Best
->FoundDecl
,
15627 Obj
, HadMultipleCandidates
,
15628 OpLocInfo
.getLoc(),
15629 OpLocInfo
.getInfo());
15630 if (NewFn
.isInvalid())
15633 SmallVector
<Expr
*, 8> MethodArgs
;
15634 MethodArgs
.reserve(NumParams
+ 1);
15636 bool IsError
= false;
15638 // Initialize the implicit object parameter if needed.
15639 // Since C++23, this could also be a call to a static call operator
15640 // which we emit as a regular CallExpr.
15641 llvm::SmallVector
<Expr
*, 8> NewArgs
;
15642 if (Method
->isExplicitObjectMemberFunction()) {
15643 // FIXME: we should do that during the definition of the lambda when we can.
15644 DiagnoseInvalidExplicitObjectParameterInLambda(Method
);
15645 PrepareExplicitObjectArgument(*this, Method
, Obj
, Args
, NewArgs
);
15646 } else if (Method
->isInstance()) {
15647 ExprResult ObjRes
= PerformImplicitObjectArgumentInitialization(
15648 Object
.get(), /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
15649 if (ObjRes
.isInvalid())
15653 MethodArgs
.push_back(Object
.get());
15656 IsError
|= PrepareArgumentsForCallToObjectOfClassType(
15657 *this, MethodArgs
, Method
, Args
, LParenLoc
);
15659 // If this is a variadic call, handle args passed through "...".
15660 if (Proto
->isVariadic()) {
15661 // Promote the arguments (C99 6.5.2.2p7).
15662 for (unsigned i
= NumParams
, e
= Args
.size(); i
< e
; i
++) {
15663 ExprResult Arg
= DefaultVariadicArgumentPromotion(Args
[i
], VariadicMethod
,
15665 IsError
|= Arg
.isInvalid();
15666 MethodArgs
.push_back(Arg
.get());
15673 DiagnoseSentinelCalls(Method
, LParenLoc
, Args
);
15675 // Once we've built TheCall, all of the expressions are properly owned.
15676 QualType ResultTy
= Method
->getReturnType();
15677 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
15678 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
15681 if (Method
->isInstance())
15682 TheCall
= CXXOperatorCallExpr::Create(Context
, OO_Call
, NewFn
.get(),
15683 MethodArgs
, ResultTy
, VK
, RParenLoc
,
15684 CurFPFeatureOverrides());
15686 TheCall
= CallExpr::Create(Context
, NewFn
.get(), MethodArgs
, ResultTy
, VK
,
15687 RParenLoc
, CurFPFeatureOverrides());
15689 if (CheckCallReturnType(Method
->getReturnType(), LParenLoc
, TheCall
, Method
))
15692 if (CheckFunctionCall(Method
, TheCall
, Proto
))
15695 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), Method
);
15698 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15699 /// (if one exists), where @c Base is an expression of class type and
15700 /// @c Member is the name of the member we're trying to find.
15702 Sema::BuildOverloadedArrowExpr(Scope
*S
, Expr
*Base
, SourceLocation OpLoc
,
15703 bool *NoArrowOperatorFound
) {
15704 assert(Base
->getType()->isRecordType() &&
15705 "left-hand side must have class type");
15707 if (checkPlaceholderForOverload(*this, Base
))
15708 return ExprError();
15710 SourceLocation Loc
= Base
->getExprLoc();
15712 // C++ [over.ref]p1:
15714 // [...] An expression x->m is interpreted as (x.operator->())->m
15715 // for a class object x of type T if T::operator->() exists and if
15716 // the operator is selected as the best match function by the
15717 // overload resolution mechanism (13.3).
15718 DeclarationName OpName
=
15719 Context
.DeclarationNames
.getCXXOperatorName(OO_Arrow
);
15720 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Operator
);
15722 if (RequireCompleteType(Loc
, Base
->getType(),
15723 diag::err_typecheck_incomplete_tag
, Base
))
15724 return ExprError();
15726 LookupResult
R(*this, OpName
, OpLoc
, LookupOrdinaryName
);
15727 LookupQualifiedName(R
, Base
->getType()->castAs
<RecordType
>()->getDecl());
15728 R
.suppressAccessDiagnostics();
15730 for (LookupResult::iterator Oper
= R
.begin(), OperEnd
= R
.end();
15731 Oper
!= OperEnd
; ++Oper
) {
15732 AddMethodCandidate(Oper
.getPair(), Base
->getType(), Base
->Classify(Context
),
15733 std::nullopt
, CandidateSet
,
15734 /*SuppressUserConversion=*/false);
15737 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
15739 // Perform overload resolution.
15740 OverloadCandidateSet::iterator Best
;
15741 switch (CandidateSet
.BestViableFunction(*this, OpLoc
, Best
)) {
15743 // Overload resolution succeeded; we'll build the call below.
15746 case OR_No_Viable_Function
: {
15747 auto Cands
= CandidateSet
.CompleteCandidates(*this, OCD_AllCandidates
, Base
);
15748 if (CandidateSet
.empty()) {
15749 QualType BaseType
= Base
->getType();
15750 if (NoArrowOperatorFound
) {
15751 // Report this specific error to the caller instead of emitting a
15752 // diagnostic, as requested.
15753 *NoArrowOperatorFound
= true;
15754 return ExprError();
15756 Diag(OpLoc
, diag::err_typecheck_member_reference_arrow
)
15757 << BaseType
<< Base
->getSourceRange();
15758 if (BaseType
->isRecordType() && !BaseType
->isPointerType()) {
15759 Diag(OpLoc
, diag::note_typecheck_member_reference_suggestion
)
15760 << FixItHint::CreateReplacement(OpLoc
, ".");
15763 Diag(OpLoc
, diag::err_ovl_no_viable_oper
)
15764 << "operator->" << Base
->getSourceRange();
15765 CandidateSet
.NoteCandidates(*this, Base
, Cands
);
15766 return ExprError();
15769 if (!R
.isAmbiguous())
15770 CandidateSet
.NoteCandidates(
15771 PartialDiagnosticAt(OpLoc
, PDiag(diag::err_ovl_ambiguous_oper_unary
)
15772 << "->" << Base
->getType()
15773 << Base
->getSourceRange()),
15774 *this, OCD_AmbiguousCandidates
, Base
);
15775 return ExprError();
15778 CandidateSet
.NoteCandidates(
15779 PartialDiagnosticAt(OpLoc
, PDiag(diag::err_ovl_deleted_oper
)
15780 << "->" << Base
->getSourceRange()),
15781 *this, OCD_AllCandidates
, Base
);
15782 return ExprError();
15785 CheckMemberOperatorAccess(OpLoc
, Base
, nullptr, Best
->FoundDecl
);
15787 // Convert the object parameter.
15788 CXXMethodDecl
*Method
= cast
<CXXMethodDecl
>(Best
->Function
);
15790 if (Method
->isExplicitObjectMemberFunction()) {
15791 ExprResult R
= InitializeExplicitObjectArgument(*this, Base
, Method
);
15793 return ExprError();
15796 ExprResult BaseResult
= PerformImplicitObjectArgumentInitialization(
15797 Base
, /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
15798 if (BaseResult
.isInvalid())
15799 return ExprError();
15800 Base
= BaseResult
.get();
15803 // Build the operator call.
15804 ExprResult FnExpr
= CreateFunctionRefExpr(*this, Method
, Best
->FoundDecl
,
15805 Base
, HadMultipleCandidates
, OpLoc
);
15806 if (FnExpr
.isInvalid())
15807 return ExprError();
15809 QualType ResultTy
= Method
->getReturnType();
15810 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
15811 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
15813 CallExpr
*TheCall
=
15814 CXXOperatorCallExpr::Create(Context
, OO_Arrow
, FnExpr
.get(), Base
,
15815 ResultTy
, VK
, OpLoc
, CurFPFeatureOverrides());
15817 if (CheckCallReturnType(Method
->getReturnType(), OpLoc
, TheCall
, Method
))
15818 return ExprError();
15820 if (CheckFunctionCall(Method
, TheCall
,
15821 Method
->getType()->castAs
<FunctionProtoType
>()))
15822 return ExprError();
15824 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), Method
);
15827 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15828 /// a literal operator described by the provided lookup results.
15829 ExprResult
Sema::BuildLiteralOperatorCall(LookupResult
&R
,
15830 DeclarationNameInfo
&SuffixInfo
,
15831 ArrayRef
<Expr
*> Args
,
15832 SourceLocation LitEndLoc
,
15833 TemplateArgumentListInfo
*TemplateArgs
) {
15834 SourceLocation UDSuffixLoc
= SuffixInfo
.getCXXLiteralOperatorNameLoc();
15836 OverloadCandidateSet
CandidateSet(UDSuffixLoc
,
15837 OverloadCandidateSet::CSK_Normal
);
15838 AddNonMemberOperatorCandidates(R
.asUnresolvedSet(), Args
, CandidateSet
,
15841 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
15843 // Perform overload resolution. This will usually be trivial, but might need
15844 // to perform substitutions for a literal operator template.
15845 OverloadCandidateSet::iterator Best
;
15846 switch (CandidateSet
.BestViableFunction(*this, UDSuffixLoc
, Best
)) {
15851 case OR_No_Viable_Function
:
15852 CandidateSet
.NoteCandidates(
15853 PartialDiagnosticAt(UDSuffixLoc
,
15854 PDiag(diag::err_ovl_no_viable_function_in_call
)
15855 << R
.getLookupName()),
15856 *this, OCD_AllCandidates
, Args
);
15857 return ExprError();
15860 CandidateSet
.NoteCandidates(
15861 PartialDiagnosticAt(R
.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call
)
15862 << R
.getLookupName()),
15863 *this, OCD_AmbiguousCandidates
, Args
);
15864 return ExprError();
15867 FunctionDecl
*FD
= Best
->Function
;
15868 ExprResult Fn
= CreateFunctionRefExpr(*this, FD
, Best
->FoundDecl
,
15869 nullptr, HadMultipleCandidates
,
15870 SuffixInfo
.getLoc(),
15871 SuffixInfo
.getInfo());
15872 if (Fn
.isInvalid())
15875 // Check the argument types. This should almost always be a no-op, except
15876 // that array-to-pointer decay is applied to string literals.
15878 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
15879 ExprResult InputInit
= PerformCopyInitialization(
15880 InitializedEntity::InitializeParameter(Context
, FD
->getParamDecl(ArgIdx
)),
15881 SourceLocation(), Args
[ArgIdx
]);
15882 if (InputInit
.isInvalid())
15884 ConvArgs
[ArgIdx
] = InputInit
.get();
15887 QualType ResultTy
= FD
->getReturnType();
15888 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
15889 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
15891 UserDefinedLiteral
*UDL
= UserDefinedLiteral::Create(
15892 Context
, Fn
.get(), llvm::ArrayRef(ConvArgs
, Args
.size()), ResultTy
, VK
,
15893 LitEndLoc
, UDSuffixLoc
, CurFPFeatureOverrides());
15895 if (CheckCallReturnType(FD
->getReturnType(), UDSuffixLoc
, UDL
, FD
))
15896 return ExprError();
15898 if (CheckFunctionCall(FD
, UDL
, nullptr))
15899 return ExprError();
15901 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL
), FD
);
15904 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15905 /// given LookupResult is non-empty, it is assumed to describe a member which
15906 /// will be invoked. Otherwise, the function will be found via argument
15907 /// dependent lookup.
15908 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15909 /// otherwise CallExpr is set to ExprError() and some non-success value
15911 Sema::ForRangeStatus
15912 Sema::BuildForRangeBeginEndCall(SourceLocation Loc
,
15913 SourceLocation RangeLoc
,
15914 const DeclarationNameInfo
&NameInfo
,
15915 LookupResult
&MemberLookup
,
15916 OverloadCandidateSet
*CandidateSet
,
15917 Expr
*Range
, ExprResult
*CallExpr
) {
15918 Scope
*S
= nullptr;
15920 CandidateSet
->clear(OverloadCandidateSet::CSK_Normal
);
15921 if (!MemberLookup
.empty()) {
15922 ExprResult MemberRef
=
15923 BuildMemberReferenceExpr(Range
, Range
->getType(), Loc
,
15924 /*IsPtr=*/false, CXXScopeSpec(),
15925 /*TemplateKWLoc=*/SourceLocation(),
15926 /*FirstQualifierInScope=*/nullptr,
15928 /*TemplateArgs=*/nullptr, S
);
15929 if (MemberRef
.isInvalid()) {
15930 *CallExpr
= ExprError();
15931 return FRS_DiagnosticIssued
;
15934 BuildCallExpr(S
, MemberRef
.get(), Loc
, std::nullopt
, Loc
, nullptr);
15935 if (CallExpr
->isInvalid()) {
15936 *CallExpr
= ExprError();
15937 return FRS_DiagnosticIssued
;
15940 ExprResult FnR
= CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15941 NestedNameSpecifierLoc(),
15942 NameInfo
, UnresolvedSet
<0>());
15943 if (FnR
.isInvalid())
15944 return FRS_DiagnosticIssued
;
15945 UnresolvedLookupExpr
*Fn
= cast
<UnresolvedLookupExpr
>(FnR
.get());
15947 bool CandidateSetError
= buildOverloadedCallSet(S
, Fn
, Fn
, Range
, Loc
,
15948 CandidateSet
, CallExpr
);
15949 if (CandidateSet
->empty() || CandidateSetError
) {
15950 *CallExpr
= ExprError();
15951 return FRS_NoViableFunction
;
15953 OverloadCandidateSet::iterator Best
;
15954 OverloadingResult OverloadResult
=
15955 CandidateSet
->BestViableFunction(*this, Fn
->getBeginLoc(), Best
);
15957 if (OverloadResult
== OR_No_Viable_Function
) {
15958 *CallExpr
= ExprError();
15959 return FRS_NoViableFunction
;
15961 *CallExpr
= FinishOverloadedCallExpr(*this, S
, Fn
, Fn
, Loc
, Range
,
15962 Loc
, nullptr, CandidateSet
, &Best
,
15964 /*AllowTypoCorrection=*/false);
15965 if (CallExpr
->isInvalid() || OverloadResult
!= OR_Success
) {
15966 *CallExpr
= ExprError();
15967 return FRS_DiagnosticIssued
;
15970 return FRS_Success
;
15974 /// FixOverloadedFunctionReference - E is an expression that refers to
15975 /// a C++ overloaded function (possibly with some parentheses and
15976 /// perhaps a '&' around it). We have resolved the overloaded function
15977 /// to the function declaration Fn, so patch up the expression E to
15978 /// refer (possibly indirectly) to Fn. Returns the new expr.
15979 ExprResult
Sema::FixOverloadedFunctionReference(Expr
*E
, DeclAccessPair Found
,
15980 FunctionDecl
*Fn
) {
15981 if (ParenExpr
*PE
= dyn_cast
<ParenExpr
>(E
)) {
15982 ExprResult SubExpr
=
15983 FixOverloadedFunctionReference(PE
->getSubExpr(), Found
, Fn
);
15984 if (SubExpr
.isInvalid())
15985 return ExprError();
15986 if (SubExpr
.get() == PE
->getSubExpr())
15989 return new (Context
)
15990 ParenExpr(PE
->getLParen(), PE
->getRParen(), SubExpr
.get());
15993 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
15994 ExprResult SubExpr
=
15995 FixOverloadedFunctionReference(ICE
->getSubExpr(), Found
, Fn
);
15996 if (SubExpr
.isInvalid())
15997 return ExprError();
15998 assert(Context
.hasSameType(ICE
->getSubExpr()->getType(),
15999 SubExpr
.get()->getType()) &&
16000 "Implicit cast type cannot be determined from overload");
16001 assert(ICE
->path_empty() && "fixing up hierarchy conversion?");
16002 if (SubExpr
.get() == ICE
->getSubExpr())
16005 return ImplicitCastExpr::Create(Context
, ICE
->getType(), ICE
->getCastKind(),
16006 SubExpr
.get(), nullptr, ICE
->getValueKind(),
16007 CurFPFeatureOverrides());
16010 if (auto *GSE
= dyn_cast
<GenericSelectionExpr
>(E
)) {
16011 if (!GSE
->isResultDependent()) {
16012 ExprResult SubExpr
=
16013 FixOverloadedFunctionReference(GSE
->getResultExpr(), Found
, Fn
);
16014 if (SubExpr
.isInvalid())
16015 return ExprError();
16016 if (SubExpr
.get() == GSE
->getResultExpr())
16019 // Replace the resulting type information before rebuilding the generic
16020 // selection expression.
16021 ArrayRef
<Expr
*> A
= GSE
->getAssocExprs();
16022 SmallVector
<Expr
*, 4> AssocExprs(A
.begin(), A
.end());
16023 unsigned ResultIdx
= GSE
->getResultIndex();
16024 AssocExprs
[ResultIdx
] = SubExpr
.get();
16026 if (GSE
->isExprPredicate())
16027 return GenericSelectionExpr::Create(
16028 Context
, GSE
->getGenericLoc(), GSE
->getControllingExpr(),
16029 GSE
->getAssocTypeSourceInfos(), AssocExprs
, GSE
->getDefaultLoc(),
16030 GSE
->getRParenLoc(), GSE
->containsUnexpandedParameterPack(),
16032 return GenericSelectionExpr::Create(
16033 Context
, GSE
->getGenericLoc(), GSE
->getControllingType(),
16034 GSE
->getAssocTypeSourceInfos(), AssocExprs
, GSE
->getDefaultLoc(),
16035 GSE
->getRParenLoc(), GSE
->containsUnexpandedParameterPack(),
16038 // Rather than fall through to the unreachable, return the original generic
16039 // selection expression.
16043 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(E
)) {
16044 assert(UnOp
->getOpcode() == UO_AddrOf
&&
16045 "Can only take the address of an overloaded function");
16046 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
)) {
16047 if (Method
->isStatic()) {
16048 // Do nothing: static member functions aren't any different
16049 // from non-member functions.
16051 // Fix the subexpression, which really has to be an
16052 // UnresolvedLookupExpr holding an overloaded member function
16054 ExprResult SubExpr
=
16055 FixOverloadedFunctionReference(UnOp
->getSubExpr(), Found
, Fn
);
16056 if (SubExpr
.isInvalid())
16057 return ExprError();
16058 if (SubExpr
.get() == UnOp
->getSubExpr())
16061 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp
->getBeginLoc(),
16062 SubExpr
.get(), Method
))
16063 return ExprError();
16065 assert(isa
<DeclRefExpr
>(SubExpr
.get()) &&
16066 "fixed to something other than a decl ref");
16067 assert(cast
<DeclRefExpr
>(SubExpr
.get())->getQualifier() &&
16068 "fixed to a member ref with no nested name qualifier");
16070 // We have taken the address of a pointer to member
16071 // function. Perform the computation here so that we get the
16072 // appropriate pointer to member type.
16074 = Context
.getTypeDeclType(cast
<RecordDecl
>(Method
->getDeclContext()));
16075 QualType MemPtrType
16076 = Context
.getMemberPointerType(Fn
->getType(), ClassType
.getTypePtr());
16077 // Under the MS ABI, lock down the inheritance model now.
16078 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
16079 (void)isCompleteType(UnOp
->getOperatorLoc(), MemPtrType
);
16081 return UnaryOperator::Create(Context
, SubExpr
.get(), UO_AddrOf
,
16082 MemPtrType
, VK_PRValue
, OK_Ordinary
,
16083 UnOp
->getOperatorLoc(), false,
16084 CurFPFeatureOverrides());
16087 ExprResult SubExpr
=
16088 FixOverloadedFunctionReference(UnOp
->getSubExpr(), Found
, Fn
);
16089 if (SubExpr
.isInvalid())
16090 return ExprError();
16091 if (SubExpr
.get() == UnOp
->getSubExpr())
16094 return CreateBuiltinUnaryOp(UnOp
->getOperatorLoc(), UO_AddrOf
,
16098 if (UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(E
)) {
16099 // FIXME: avoid copy.
16100 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
16101 if (ULE
->hasExplicitTemplateArgs()) {
16102 ULE
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
16103 TemplateArgs
= &TemplateArgsBuffer
;
16106 QualType Type
= Fn
->getType();
16107 ExprValueKind ValueKind
= getLangOpts().CPlusPlus
? VK_LValue
: VK_PRValue
;
16109 // FIXME: Duplicated from BuildDeclarationNameExpr.
16110 if (unsigned BID
= Fn
->getBuiltinID()) {
16111 if (!Context
.BuiltinInfo
.isDirectlyAddressable(BID
)) {
16112 Type
= Context
.BuiltinFnTy
;
16113 ValueKind
= VK_PRValue
;
16117 DeclRefExpr
*DRE
= BuildDeclRefExpr(
16118 Fn
, Type
, ValueKind
, ULE
->getNameInfo(), ULE
->getQualifierLoc(),
16119 Found
.getDecl(), ULE
->getTemplateKeywordLoc(), TemplateArgs
);
16120 DRE
->setHadMultipleCandidates(ULE
->getNumDecls() > 1);
16124 if (UnresolvedMemberExpr
*MemExpr
= dyn_cast
<UnresolvedMemberExpr
>(E
)) {
16125 // FIXME: avoid copy.
16126 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
16127 if (MemExpr
->hasExplicitTemplateArgs()) {
16128 MemExpr
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
16129 TemplateArgs
= &TemplateArgsBuffer
;
16134 // If we're filling in a static method where we used to have an
16135 // implicit member access, rewrite to a simple decl ref.
16136 if (MemExpr
->isImplicitAccess()) {
16137 if (cast
<CXXMethodDecl
>(Fn
)->isStatic()) {
16138 DeclRefExpr
*DRE
= BuildDeclRefExpr(
16139 Fn
, Fn
->getType(), VK_LValue
, MemExpr
->getNameInfo(),
16140 MemExpr
->getQualifierLoc(), Found
.getDecl(),
16141 MemExpr
->getTemplateKeywordLoc(), TemplateArgs
);
16142 DRE
->setHadMultipleCandidates(MemExpr
->getNumDecls() > 1);
16145 SourceLocation Loc
= MemExpr
->getMemberLoc();
16146 if (MemExpr
->getQualifier())
16147 Loc
= MemExpr
->getQualifierLoc().getBeginLoc();
16149 BuildCXXThisExpr(Loc
, MemExpr
->getBaseType(), /*IsImplicit=*/true);
16152 Base
= MemExpr
->getBase();
16154 ExprValueKind valueKind
;
16156 if (cast
<CXXMethodDecl
>(Fn
)->isStatic()) {
16157 valueKind
= VK_LValue
;
16158 type
= Fn
->getType();
16160 valueKind
= VK_PRValue
;
16161 type
= Context
.BoundMemberTy
;
16164 return BuildMemberExpr(
16165 Base
, MemExpr
->isArrow(), MemExpr
->getOperatorLoc(),
16166 MemExpr
->getQualifierLoc(), MemExpr
->getTemplateKeywordLoc(), Fn
, Found
,
16167 /*HadMultipleCandidates=*/true, MemExpr
->getMemberNameInfo(),
16168 type
, valueKind
, OK_Ordinary
, TemplateArgs
);
16171 llvm_unreachable("Invalid reference to overloaded function");
16174 ExprResult
Sema::FixOverloadedFunctionReference(ExprResult E
,
16175 DeclAccessPair Found
,
16176 FunctionDecl
*Fn
) {
16177 return FixOverloadedFunctionReference(E
.get(), Found
, Fn
);
16180 bool clang::shouldEnforceArgLimit(bool PartialOverloading
,
16181 FunctionDecl
*Function
) {
16182 if (!PartialOverloading
|| !Function
)
16184 if (Function
->isVariadic())
16186 if (const auto *Proto
=
16187 dyn_cast
<FunctionProtoType
>(Function
->getFunctionType()))
16188 if (Proto
->isTemplateVariadic())
16190 if (auto *Pattern
= Function
->getTemplateInstantiationPattern())
16191 if (const auto *Proto
=
16192 dyn_cast
<FunctionProtoType
>(Pattern
->getFunctionType()))
16193 if (Proto
->isTemplateVariadic())