17102 lines · cpp
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This file provides Sema routines for C++ overloading.10//11//===----------------------------------------------------------------------===//12 13#include "CheckExprLifetime.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/CXXInheritance.h"16#include "clang/AST/Decl.h"17#include "clang/AST/DeclCXX.h"18#include "clang/AST/DeclObjC.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/Basic/Diagnostic.h"24#include "clang/Basic/DiagnosticOptions.h"25#include "clang/Basic/OperatorKinds.h"26#include "clang/Basic/PartialDiagnostic.h"27#include "clang/Basic/SourceManager.h"28#include "clang/Basic/TargetInfo.h"29#include "clang/Sema/EnterExpressionEvaluationContext.h"30#include "clang/Sema/Initialization.h"31#include "clang/Sema/Lookup.h"32#include "clang/Sema/Overload.h"33#include "clang/Sema/SemaARM.h"34#include "clang/Sema/SemaCUDA.h"35#include "clang/Sema/SemaObjC.h"36#include "clang/Sema/Template.h"37#include "clang/Sema/TemplateDeduction.h"38#include "llvm/ADT/DenseSet.h"39#include "llvm/ADT/STLExtras.h"40#include "llvm/ADT/STLForwardCompat.h"41#include "llvm/ADT/ScopeExit.h"42#include "llvm/ADT/SmallPtrSet.h"43#include "llvm/ADT/SmallVector.h"44#include <algorithm>45#include <cassert>46#include <cstddef>47#include <cstdlib>48#include <optional>49 50using namespace clang;51using namespace sema;52 53using AllowedExplicit = Sema::AllowedExplicit;54 55static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {57 return P->hasAttr<PassObjectSizeAttr>();58 });59}60 61/// A convenience routine for creating a decayed reference to a function.62static ExprResult CreateFunctionRefExpr(63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))67 return ExprError();68 // If FoundDecl is different from Fn (such as if one is a template69 // and the other a specialization), make sure DiagnoseUseOfDecl is70 // called on both.71 // FIXME: This would be more comprehensively addressed by modifying72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl73 // being used.74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))75 return ExprError();76 DeclRefExpr *DRE = new (S.Context)77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);78 if (HadMultipleCandidates)79 DRE->setHadMultipleCandidates(true);80 81 S.MarkDeclRefReferenced(DRE, Base);82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {84 S.ResolveExceptionSpec(Loc, FPT);85 DRE->setType(Fn->getType());86 }87 }88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),89 CK_FunctionToPointerDecay);90}91 92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,93 bool InOverloadResolution,94 StandardConversionSequence &SCS,95 bool CStyle,96 bool AllowObjCWritebackConversion);97 98static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,99 QualType &ToType,100 bool InOverloadResolution,101 StandardConversionSequence &SCS,102 bool CStyle);103static OverloadingResult104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,105 UserDefinedConversionSequence& User,106 OverloadCandidateSet& Conversions,107 AllowedExplicit AllowExplicit,108 bool AllowObjCConversionOnExplicit);109 110static ImplicitConversionSequence::CompareKind111CompareStandardConversionSequences(Sema &S, SourceLocation Loc,112 const StandardConversionSequence& SCS1,113 const StandardConversionSequence& SCS2);114 115static ImplicitConversionSequence::CompareKind116CompareQualificationConversions(Sema &S,117 const StandardConversionSequence& SCS1,118 const StandardConversionSequence& SCS2);119 120static ImplicitConversionSequence::CompareKind121CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,122 const StandardConversionSequence& SCS1,123 const StandardConversionSequence& SCS2);124 125/// GetConversionRank - Retrieve the implicit conversion rank126/// corresponding to the given implicit conversion kind.127ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {128 static const ImplicitConversionRank Rank[] = {129 ICR_Exact_Match,130 ICR_Exact_Match,131 ICR_Exact_Match,132 ICR_Exact_Match,133 ICR_Exact_Match,134 ICR_Exact_Match,135 ICR_Promotion,136 ICR_Promotion,137 ICR_Promotion,138 ICR_Conversion,139 ICR_Conversion,140 ICR_Conversion,141 ICR_Conversion,142 ICR_Conversion,143 ICR_Conversion,144 ICR_Conversion,145 ICR_Conversion,146 ICR_Conversion,147 ICR_Conversion,148 ICR_Conversion,149 ICR_Conversion,150 ICR_OCL_Scalar_Widening,151 ICR_Complex_Real_Conversion,152 ICR_Conversion,153 ICR_Conversion,154 ICR_Writeback_Conversion,155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --156 // it was omitted by the patch that added157 // ICK_Zero_Event_Conversion158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --159 // it was omitted by the patch that added160 // ICK_Zero_Queue_Conversion161 ICR_C_Conversion,162 ICR_C_Conversion_Extension,163 ICR_Conversion,164 ICR_HLSL_Dimension_Reduction,165 ICR_Conversion,166 ICR_HLSL_Scalar_Widening,167 };168 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);169 return Rank[(int)Kind];170}171 172ImplicitConversionRank173clang::GetDimensionConversionRank(ImplicitConversionRank Base,174 ImplicitConversionKind Dimension) {175 ImplicitConversionRank Rank = GetConversionRank(Dimension);176 if (Rank == ICR_HLSL_Scalar_Widening) {177 if (Base == ICR_Promotion)178 return ICR_HLSL_Scalar_Widening_Promotion;179 if (Base == ICR_Conversion)180 return ICR_HLSL_Scalar_Widening_Conversion;181 }182 if (Rank == ICR_HLSL_Dimension_Reduction) {183 if (Base == ICR_Promotion)184 return ICR_HLSL_Dimension_Reduction_Promotion;185 if (Base == ICR_Conversion)186 return ICR_HLSL_Dimension_Reduction_Conversion;187 }188 return Rank;189}190 191/// GetImplicitConversionName - Return the name of this kind of192/// implicit conversion.193static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {194 static const char *const Name[] = {195 "No conversion",196 "Lvalue-to-rvalue",197 "Array-to-pointer",198 "Function-to-pointer",199 "Function pointer conversion",200 "Qualification",201 "Integral promotion",202 "Floating point promotion",203 "Complex promotion",204 "Integral conversion",205 "Floating conversion",206 "Complex conversion",207 "Floating-integral conversion",208 "Pointer conversion",209 "Pointer-to-member conversion",210 "Boolean conversion",211 "Compatible-types conversion",212 "Derived-to-base conversion",213 "Vector conversion",214 "SVE Vector conversion",215 "RVV Vector conversion",216 "Vector splat",217 "Complex-real conversion",218 "Block Pointer conversion",219 "Transparent Union Conversion",220 "Writeback conversion",221 "OpenCL Zero Event Conversion",222 "OpenCL Zero Queue Conversion",223 "C specific type conversion",224 "Incompatible pointer conversion",225 "Fixed point conversion",226 "HLSL vector truncation",227 "Non-decaying array conversion",228 "HLSL vector splat",229 };230 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);231 return Name[Kind];232}233 234/// StandardConversionSequence - Set the standard conversion235/// sequence to the identity conversion.236void StandardConversionSequence::setAsIdentityConversion() {237 First = ICK_Identity;238 Second = ICK_Identity;239 Dimension = ICK_Identity;240 Third = ICK_Identity;241 DeprecatedStringLiteralToCharPtr = false;242 QualificationIncludesObjCLifetime = false;243 ReferenceBinding = false;244 DirectBinding = false;245 IsLvalueReference = true;246 BindsToFunctionLvalue = false;247 BindsToRvalue = false;248 BindsImplicitObjectArgumentWithoutRefQualifier = false;249 ObjCLifetimeConversionBinding = false;250 FromBracedInitList = false;251 CopyConstructor = nullptr;252}253 254/// getRank - Retrieve the rank of this standard conversion sequence255/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the256/// implicit conversions.257ImplicitConversionRank StandardConversionSequence::getRank() const {258 ImplicitConversionRank Rank = ICR_Exact_Match;259 if (GetConversionRank(First) > Rank)260 Rank = GetConversionRank(First);261 if (GetConversionRank(Second) > Rank)262 Rank = GetConversionRank(Second);263 if (GetDimensionConversionRank(Rank, Dimension) > Rank)264 Rank = GetDimensionConversionRank(Rank, Dimension);265 if (GetConversionRank(Third) > Rank)266 Rank = GetConversionRank(Third);267 return Rank;268}269 270/// isPointerConversionToBool - Determines whether this conversion is271/// a conversion of a pointer or pointer-to-member to bool. This is272/// used as part of the ranking of standard conversion sequences273/// (C++ 13.3.3.2p4).274bool StandardConversionSequence::isPointerConversionToBool() const {275 // Note that FromType has not necessarily been transformed by the276 // array-to-pointer or function-to-pointer implicit conversions, so277 // check for their presence as well as checking whether FromType is278 // a pointer.279 if (getToType(1)->isBooleanType() &&280 (getFromType()->isPointerType() ||281 getFromType()->isMemberPointerType() ||282 getFromType()->isObjCObjectPointerType() ||283 getFromType()->isBlockPointerType() ||284 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))285 return true;286 287 return false;288}289 290/// isPointerConversionToVoidPointer - Determines whether this291/// conversion is a conversion of a pointer to a void pointer. This is292/// used as part of the ranking of standard conversion sequences (C++293/// 13.3.3.2p4).294bool295StandardConversionSequence::296isPointerConversionToVoidPointer(ASTContext& Context) const {297 QualType FromType = getFromType();298 QualType ToType = getToType(1);299 300 // Note that FromType has not necessarily been transformed by the301 // array-to-pointer implicit conversion, so check for its presence302 // and redo the conversion to get a pointer.303 if (First == ICK_Array_To_Pointer)304 FromType = Context.getArrayDecayedType(FromType);305 306 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())307 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())308 return ToPtrType->getPointeeType()->isVoidType();309 310 return false;311}312 313/// Skip any implicit casts which could be either part of a narrowing conversion314/// or after one in an implicit conversion.315static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,316 const Expr *Converted) {317 // We can have cleanups wrapping the converted expression; these need to be318 // preserved so that destructors run if necessary.319 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {320 Expr *Inner =321 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));322 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),323 EWC->getObjects());324 }325 326 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {327 switch (ICE->getCastKind()) {328 case CK_NoOp:329 case CK_IntegralCast:330 case CK_IntegralToBoolean:331 case CK_IntegralToFloating:332 case CK_BooleanToSignedIntegral:333 case CK_FloatingToIntegral:334 case CK_FloatingToBoolean:335 case CK_FloatingCast:336 Converted = ICE->getSubExpr();337 continue;338 339 default:340 return Converted;341 }342 }343 344 return Converted;345}346 347/// Check if this standard conversion sequence represents a narrowing348/// conversion, according to C++11 [dcl.init.list]p7.349///350/// \param Ctx The AST context.351/// \param Converted The result of applying this standard conversion sequence.352/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the353/// value of the expression prior to the narrowing conversion.354/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the355/// type of the expression prior to the narrowing conversion.356/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions357/// from floating point types to integral types should be ignored.358NarrowingKind StandardConversionSequence::getNarrowingKind(359 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,360 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {361 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&362 "narrowing check outside C++");363 364 // C++11 [dcl.init.list]p7:365 // A narrowing conversion is an implicit conversion ...366 QualType FromType = getToType(0);367 QualType ToType = getToType(1);368 369 // A conversion to an enumeration type is narrowing if the conversion to370 // the underlying type is narrowing. This only arises for expressions of371 // the form 'Enum{init}'.372 if (const auto *ED = ToType->getAsEnumDecl())373 ToType = ED->getIntegerType();374 375 switch (Second) {376 // 'bool' is an integral type; dispatch to the right place to handle it.377 case ICK_Boolean_Conversion:378 if (FromType->isRealFloatingType())379 goto FloatingIntegralConversion;380 if (FromType->isIntegralOrUnscopedEnumerationType())381 goto IntegralConversion;382 // -- from a pointer type or pointer-to-member type to bool, or383 return NK_Type_Narrowing;384 385 // -- from a floating-point type to an integer type, or386 //387 // -- from an integer type or unscoped enumeration type to a floating-point388 // type, except where the source is a constant expression and the actual389 // value after conversion will fit into the target type and will produce390 // the original value when converted back to the original type, or391 case ICK_Floating_Integral:392 FloatingIntegralConversion:393 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {394 return NK_Type_Narrowing;395 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&396 ToType->isRealFloatingType()) {397 if (IgnoreFloatToIntegralConversion)398 return NK_Not_Narrowing;399 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);400 assert(Initializer && "Unknown conversion expression");401 402 // If it's value-dependent, we can't tell whether it's narrowing.403 if (Initializer->isValueDependent())404 return NK_Dependent_Narrowing;405 406 if (std::optional<llvm::APSInt> IntConstantValue =407 Initializer->getIntegerConstantExpr(Ctx)) {408 // Convert the integer to the floating type.409 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));410 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),411 llvm::APFloat::rmNearestTiesToEven);412 // And back.413 llvm::APSInt ConvertedValue = *IntConstantValue;414 bool ignored;415 llvm::APFloat::opStatus Status = Result.convertToInteger(416 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);417 // If the converted-back integer has unspecified value, or if the418 // resulting value is different, this was a narrowing conversion.419 if (Status == llvm::APFloat::opInvalidOp ||420 *IntConstantValue != ConvertedValue) {421 ConstantValue = APValue(*IntConstantValue);422 ConstantType = Initializer->getType();423 return NK_Constant_Narrowing;424 }425 } else {426 // Variables are always narrowings.427 return NK_Variable_Narrowing;428 }429 }430 return NK_Not_Narrowing;431 432 // -- from long double to double or float, or from double to float, except433 // where the source is a constant expression and the actual value after434 // conversion is within the range of values that can be represented (even435 // if it cannot be represented exactly), or436 case ICK_Floating_Conversion:437 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&438 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {439 // FromType is larger than ToType.440 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);441 442 // If it's value-dependent, we can't tell whether it's narrowing.443 if (Initializer->isValueDependent())444 return NK_Dependent_Narrowing;445 446 Expr::EvalResult R;447 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||448 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {449 // Constant!450 if (Ctx.getLangOpts().C23)451 ConstantValue = R.Val;452 assert(ConstantValue.isFloat());453 llvm::APFloat FloatVal = ConstantValue.getFloat();454 // Convert the source value into the target type.455 bool ignored;456 llvm::APFloat Converted = FloatVal;457 llvm::APFloat::opStatus ConvertStatus =458 Converted.convert(Ctx.getFloatTypeSemantics(ToType),459 llvm::APFloat::rmNearestTiesToEven, &ignored);460 Converted.convert(Ctx.getFloatTypeSemantics(FromType),461 llvm::APFloat::rmNearestTiesToEven, &ignored);462 if (Ctx.getLangOpts().C23) {463 if (FloatVal.isNaN() && Converted.isNaN() &&464 !FloatVal.isSignaling() && !Converted.isSignaling()) {465 // Quiet NaNs are considered the same value, regardless of466 // payloads.467 return NK_Not_Narrowing;468 }469 // For normal values, check exact equality.470 if (!Converted.bitwiseIsEqual(FloatVal)) {471 ConstantType = Initializer->getType();472 return NK_Constant_Narrowing;473 }474 } else {475 // If there was no overflow, the source value is within the range of476 // values that can be represented.477 if (ConvertStatus & llvm::APFloat::opOverflow) {478 ConstantType = Initializer->getType();479 return NK_Constant_Narrowing;480 }481 }482 } else {483 return NK_Variable_Narrowing;484 }485 }486 return NK_Not_Narrowing;487 488 // -- from an integer type or unscoped enumeration type to an integer type489 // that cannot represent all the values of the original type, except where490 // (CWG2627) -- the source is a bit-field whose width w is less than that491 // of its type (or, for an enumeration type, its underlying type) and the492 // target type can represent all the values of a hypothetical extended493 // integer type with width w and with the same signedness as the original494 // type or495 // -- the source is a constant expression and the actual value after496 // conversion will fit into the target type and will produce the original497 // value when converted back to the original type.498 case ICK_Integral_Conversion:499 IntegralConversion: {500 assert(FromType->isIntegralOrUnscopedEnumerationType());501 assert(ToType->isIntegralOrUnscopedEnumerationType());502 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();503 unsigned FromWidth = Ctx.getIntWidth(FromType);504 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();505 const unsigned ToWidth = Ctx.getIntWidth(ToType);506 507 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,508 bool ToSigned, unsigned ToWidth) {509 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&510 !(FromSigned && !ToSigned);511 };512 513 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))514 return NK_Not_Narrowing;515 516 // Not all values of FromType can be represented in ToType.517 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);518 519 bool DependentBitField = false;520 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {521 if (BitField->getBitWidth()->isValueDependent())522 DependentBitField = true;523 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();524 BitFieldWidth < FromWidth) {525 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))526 return NK_Not_Narrowing;527 528 // The initializer will be truncated to the bit-field width529 FromWidth = BitFieldWidth;530 }531 }532 533 // If it's value-dependent, we can't tell whether it's narrowing.534 if (Initializer->isValueDependent())535 return NK_Dependent_Narrowing;536 537 std::optional<llvm::APSInt> OptInitializerValue =538 Initializer->getIntegerConstantExpr(Ctx);539 if (!OptInitializerValue) {540 // If the bit-field width was dependent, it might end up being small541 // enough to fit in the target type (unless the target type is unsigned542 // and the source type is signed, in which case it will never fit)543 if (DependentBitField && !(FromSigned && !ToSigned))544 return NK_Dependent_Narrowing;545 546 // Otherwise, such a conversion is always narrowing547 return NK_Variable_Narrowing;548 }549 llvm::APSInt &InitializerValue = *OptInitializerValue;550 bool Narrowing = false;551 if (FromWidth < ToWidth) {552 // Negative -> unsigned is narrowing. Otherwise, more bits is never553 // narrowing.554 if (InitializerValue.isSigned() && InitializerValue.isNegative())555 Narrowing = true;556 } else {557 // Add a bit to the InitializerValue so we don't have to worry about558 // signed vs. unsigned comparisons.559 InitializerValue =560 InitializerValue.extend(InitializerValue.getBitWidth() + 1);561 // Convert the initializer to and from the target width and signed-ness.562 llvm::APSInt ConvertedValue = InitializerValue;563 ConvertedValue = ConvertedValue.trunc(ToWidth);564 ConvertedValue.setIsSigned(ToSigned);565 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());566 ConvertedValue.setIsSigned(InitializerValue.isSigned());567 // If the result is different, this was a narrowing conversion.568 if (ConvertedValue != InitializerValue)569 Narrowing = true;570 }571 if (Narrowing) {572 ConstantType = Initializer->getType();573 ConstantValue = APValue(InitializerValue);574 return NK_Constant_Narrowing;575 }576 577 return NK_Not_Narrowing;578 }579 case ICK_Complex_Real:580 if (FromType->isComplexType() && !ToType->isComplexType())581 return NK_Type_Narrowing;582 return NK_Not_Narrowing;583 584 case ICK_Floating_Promotion:585 if (Ctx.getLangOpts().C23) {586 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);587 Expr::EvalResult R;588 if (Initializer->EvaluateAsRValue(R, Ctx)) {589 ConstantValue = R.Val;590 assert(ConstantValue.isFloat());591 llvm::APFloat FloatVal = ConstantValue.getFloat();592 // C23 6.7.3p6 If the initializer has real type and a signaling NaN593 // value, the unqualified versions of the type of the initializer and594 // the corresponding real type of the object declared shall be595 // compatible.596 if (FloatVal.isNaN() && FloatVal.isSignaling()) {597 ConstantType = Initializer->getType();598 return NK_Constant_Narrowing;599 }600 }601 }602 return NK_Not_Narrowing;603 default:604 // Other kinds of conversions are not narrowings.605 return NK_Not_Narrowing;606 }607}608 609/// dump - Print this standard conversion sequence to standard610/// error. Useful for debugging overloading issues.611LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {612 raw_ostream &OS = llvm::errs();613 bool PrintedSomething = false;614 if (First != ICK_Identity) {615 OS << GetImplicitConversionName(First);616 PrintedSomething = true;617 }618 619 if (Second != ICK_Identity) {620 if (PrintedSomething) {621 OS << " -> ";622 }623 OS << GetImplicitConversionName(Second);624 625 if (CopyConstructor) {626 OS << " (by copy constructor)";627 } else if (DirectBinding) {628 OS << " (direct reference binding)";629 } else if (ReferenceBinding) {630 OS << " (reference binding)";631 }632 PrintedSomething = true;633 }634 635 if (Third != ICK_Identity) {636 if (PrintedSomething) {637 OS << " -> ";638 }639 OS << GetImplicitConversionName(Third);640 PrintedSomething = true;641 }642 643 if (!PrintedSomething) {644 OS << "No conversions required";645 }646}647 648/// dump - Print this user-defined conversion sequence to standard649/// error. Useful for debugging overloading issues.650void UserDefinedConversionSequence::dump() const {651 raw_ostream &OS = llvm::errs();652 if (Before.First || Before.Second || Before.Third) {653 Before.dump();654 OS << " -> ";655 }656 if (ConversionFunction)657 OS << '\'' << *ConversionFunction << '\'';658 else659 OS << "aggregate initialization";660 if (After.First || After.Second || After.Third) {661 OS << " -> ";662 After.dump();663 }664}665 666/// dump - Print this implicit conversion sequence to standard667/// error. Useful for debugging overloading issues.668void ImplicitConversionSequence::dump() const {669 raw_ostream &OS = llvm::errs();670 if (hasInitializerListContainerType())671 OS << "Worst list element conversion: ";672 switch (ConversionKind) {673 case StandardConversion:674 OS << "Standard conversion: ";675 Standard.dump();676 break;677 case UserDefinedConversion:678 OS << "User-defined conversion: ";679 UserDefined.dump();680 break;681 case EllipsisConversion:682 OS << "Ellipsis conversion";683 break;684 case AmbiguousConversion:685 OS << "Ambiguous conversion";686 break;687 case BadConversion:688 OS << "Bad conversion";689 break;690 }691 692 OS << "\n";693}694 695void AmbiguousConversionSequence::construct() {696 new (&conversions()) ConversionSet();697}698 699void AmbiguousConversionSequence::destruct() {700 conversions().~ConversionSet();701}702 703void704AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {705 FromTypePtr = O.FromTypePtr;706 ToTypePtr = O.ToTypePtr;707 new (&conversions()) ConversionSet(O.conversions());708}709 710namespace {711 // Structure used by DeductionFailureInfo to store712 // template argument information.713 struct DFIArguments {714 TemplateArgument FirstArg;715 TemplateArgument SecondArg;716 };717 // Structure used by DeductionFailureInfo to store718 // template parameter and template argument information.719 struct DFIParamWithArguments : DFIArguments {720 TemplateParameter Param;721 };722 // Structure used by DeductionFailureInfo to store template argument723 // information and the index of the problematic call argument.724 struct DFIDeducedMismatchArgs : DFIArguments {725 TemplateArgumentList *TemplateArgs;726 unsigned CallArgIndex;727 };728 // Structure used by DeductionFailureInfo to store information about729 // unsatisfied constraints.730 struct CNSInfo {731 TemplateArgumentList *TemplateArgs;732 ConstraintSatisfaction Satisfaction;733 };734}735 736/// Convert from Sema's representation of template deduction information737/// to the form used in overload-candidate information.738DeductionFailureInfo739clang::MakeDeductionFailureInfo(ASTContext &Context,740 TemplateDeductionResult TDK,741 TemplateDeductionInfo &Info) {742 DeductionFailureInfo Result;743 Result.Result = static_cast<unsigned>(TDK);744 Result.HasDiagnostic = false;745 switch (TDK) {746 case TemplateDeductionResult::Invalid:747 case TemplateDeductionResult::InstantiationDepth:748 case TemplateDeductionResult::TooManyArguments:749 case TemplateDeductionResult::TooFewArguments:750 case TemplateDeductionResult::MiscellaneousDeductionFailure:751 case TemplateDeductionResult::CUDATargetMismatch:752 Result.Data = nullptr;753 break;754 755 case TemplateDeductionResult::Incomplete:756 case TemplateDeductionResult::InvalidExplicitArguments:757 Result.Data = Info.Param.getOpaqueValue();758 break;759 760 case TemplateDeductionResult::DeducedMismatch:761 case TemplateDeductionResult::DeducedMismatchNested: {762 // FIXME: Should allocate from normal heap so that we can free this later.763 auto *Saved = new (Context) DFIDeducedMismatchArgs;764 Saved->FirstArg = Info.FirstArg;765 Saved->SecondArg = Info.SecondArg;766 Saved->TemplateArgs = Info.takeSugared();767 Saved->CallArgIndex = Info.CallArgIndex;768 Result.Data = Saved;769 break;770 }771 772 case TemplateDeductionResult::NonDeducedMismatch: {773 // FIXME: Should allocate from normal heap so that we can free this later.774 DFIArguments *Saved = new (Context) DFIArguments;775 Saved->FirstArg = Info.FirstArg;776 Saved->SecondArg = Info.SecondArg;777 Result.Data = Saved;778 break;779 }780 781 case TemplateDeductionResult::IncompletePack:782 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.783 case TemplateDeductionResult::Inconsistent:784 case TemplateDeductionResult::Underqualified: {785 // FIXME: Should allocate from normal heap so that we can free this later.786 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;787 Saved->Param = Info.Param;788 Saved->FirstArg = Info.FirstArg;789 Saved->SecondArg = Info.SecondArg;790 Result.Data = Saved;791 break;792 }793 794 case TemplateDeductionResult::SubstitutionFailure:795 Result.Data = Info.takeSugared();796 if (Info.hasSFINAEDiagnostic()) {797 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(798 SourceLocation(), PartialDiagnostic::NullDiagnostic());799 Info.takeSFINAEDiagnostic(*Diag);800 Result.HasDiagnostic = true;801 }802 break;803 804 case TemplateDeductionResult::ConstraintsNotSatisfied: {805 CNSInfo *Saved = new (Context) CNSInfo;806 Saved->TemplateArgs = Info.takeSugared();807 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);808 Result.Data = Saved;809 break;810 }811 812 case TemplateDeductionResult::Success:813 case TemplateDeductionResult::NonDependentConversionFailure:814 case TemplateDeductionResult::AlreadyDiagnosed:815 llvm_unreachable("not a deduction failure");816 }817 818 return Result;819}820 821void DeductionFailureInfo::Destroy() {822 switch (static_cast<TemplateDeductionResult>(Result)) {823 case TemplateDeductionResult::Success:824 case TemplateDeductionResult::Invalid:825 case TemplateDeductionResult::InstantiationDepth:826 case TemplateDeductionResult::Incomplete:827 case TemplateDeductionResult::TooManyArguments:828 case TemplateDeductionResult::TooFewArguments:829 case TemplateDeductionResult::InvalidExplicitArguments:830 case TemplateDeductionResult::CUDATargetMismatch:831 case TemplateDeductionResult::NonDependentConversionFailure:832 break;833 834 case TemplateDeductionResult::IncompletePack:835 case TemplateDeductionResult::Inconsistent:836 case TemplateDeductionResult::Underqualified:837 case TemplateDeductionResult::DeducedMismatch:838 case TemplateDeductionResult::DeducedMismatchNested:839 case TemplateDeductionResult::NonDeducedMismatch:840 // FIXME: Destroy the data?841 Data = nullptr;842 break;843 844 case TemplateDeductionResult::SubstitutionFailure:845 // FIXME: Destroy the template argument list?846 Data = nullptr;847 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {848 Diag->~PartialDiagnosticAt();849 HasDiagnostic = false;850 }851 break;852 853 case TemplateDeductionResult::ConstraintsNotSatisfied:854 // FIXME: Destroy the template argument list?855 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();856 Data = nullptr;857 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {858 Diag->~PartialDiagnosticAt();859 HasDiagnostic = false;860 }861 break;862 863 // Unhandled864 case TemplateDeductionResult::MiscellaneousDeductionFailure:865 case TemplateDeductionResult::AlreadyDiagnosed:866 break;867 }868}869 870PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {871 if (HasDiagnostic)872 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));873 return nullptr;874}875 876TemplateParameter DeductionFailureInfo::getTemplateParameter() {877 switch (static_cast<TemplateDeductionResult>(Result)) {878 case TemplateDeductionResult::Success:879 case TemplateDeductionResult::Invalid:880 case TemplateDeductionResult::InstantiationDepth:881 case TemplateDeductionResult::TooManyArguments:882 case TemplateDeductionResult::TooFewArguments:883 case TemplateDeductionResult::SubstitutionFailure:884 case TemplateDeductionResult::DeducedMismatch:885 case TemplateDeductionResult::DeducedMismatchNested:886 case TemplateDeductionResult::NonDeducedMismatch:887 case TemplateDeductionResult::CUDATargetMismatch:888 case TemplateDeductionResult::NonDependentConversionFailure:889 case TemplateDeductionResult::ConstraintsNotSatisfied:890 return TemplateParameter();891 892 case TemplateDeductionResult::Incomplete:893 case TemplateDeductionResult::InvalidExplicitArguments:894 return TemplateParameter::getFromOpaqueValue(Data);895 896 case TemplateDeductionResult::IncompletePack:897 case TemplateDeductionResult::Inconsistent:898 case TemplateDeductionResult::Underqualified:899 return static_cast<DFIParamWithArguments*>(Data)->Param;900 901 // Unhandled902 case TemplateDeductionResult::MiscellaneousDeductionFailure:903 case TemplateDeductionResult::AlreadyDiagnosed:904 break;905 }906 907 return TemplateParameter();908}909 910TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {911 switch (static_cast<TemplateDeductionResult>(Result)) {912 case TemplateDeductionResult::Success:913 case TemplateDeductionResult::Invalid:914 case TemplateDeductionResult::InstantiationDepth:915 case TemplateDeductionResult::TooManyArguments:916 case TemplateDeductionResult::TooFewArguments:917 case TemplateDeductionResult::Incomplete:918 case TemplateDeductionResult::IncompletePack:919 case TemplateDeductionResult::InvalidExplicitArguments:920 case TemplateDeductionResult::Inconsistent:921 case TemplateDeductionResult::Underqualified:922 case TemplateDeductionResult::NonDeducedMismatch:923 case TemplateDeductionResult::CUDATargetMismatch:924 case TemplateDeductionResult::NonDependentConversionFailure:925 return nullptr;926 927 case TemplateDeductionResult::DeducedMismatch:928 case TemplateDeductionResult::DeducedMismatchNested:929 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;930 931 case TemplateDeductionResult::SubstitutionFailure:932 return static_cast<TemplateArgumentList*>(Data);933 934 case TemplateDeductionResult::ConstraintsNotSatisfied:935 return static_cast<CNSInfo*>(Data)->TemplateArgs;936 937 // Unhandled938 case TemplateDeductionResult::MiscellaneousDeductionFailure:939 case TemplateDeductionResult::AlreadyDiagnosed:940 break;941 }942 943 return nullptr;944}945 946const TemplateArgument *DeductionFailureInfo::getFirstArg() {947 switch (static_cast<TemplateDeductionResult>(Result)) {948 case TemplateDeductionResult::Success:949 case TemplateDeductionResult::Invalid:950 case TemplateDeductionResult::InstantiationDepth:951 case TemplateDeductionResult::Incomplete:952 case TemplateDeductionResult::TooManyArguments:953 case TemplateDeductionResult::TooFewArguments:954 case TemplateDeductionResult::InvalidExplicitArguments:955 case TemplateDeductionResult::SubstitutionFailure:956 case TemplateDeductionResult::CUDATargetMismatch:957 case TemplateDeductionResult::NonDependentConversionFailure:958 case TemplateDeductionResult::ConstraintsNotSatisfied:959 return nullptr;960 961 case TemplateDeductionResult::IncompletePack:962 case TemplateDeductionResult::Inconsistent:963 case TemplateDeductionResult::Underqualified:964 case TemplateDeductionResult::DeducedMismatch:965 case TemplateDeductionResult::DeducedMismatchNested:966 case TemplateDeductionResult::NonDeducedMismatch:967 return &static_cast<DFIArguments*>(Data)->FirstArg;968 969 // Unhandled970 case TemplateDeductionResult::MiscellaneousDeductionFailure:971 case TemplateDeductionResult::AlreadyDiagnosed:972 break;973 }974 975 return nullptr;976}977 978const TemplateArgument *DeductionFailureInfo::getSecondArg() {979 switch (static_cast<TemplateDeductionResult>(Result)) {980 case TemplateDeductionResult::Success:981 case TemplateDeductionResult::Invalid:982 case TemplateDeductionResult::InstantiationDepth:983 case TemplateDeductionResult::Incomplete:984 case TemplateDeductionResult::IncompletePack:985 case TemplateDeductionResult::TooManyArguments:986 case TemplateDeductionResult::TooFewArguments:987 case TemplateDeductionResult::InvalidExplicitArguments:988 case TemplateDeductionResult::SubstitutionFailure:989 case TemplateDeductionResult::CUDATargetMismatch:990 case TemplateDeductionResult::NonDependentConversionFailure:991 case TemplateDeductionResult::ConstraintsNotSatisfied:992 return nullptr;993 994 case TemplateDeductionResult::Inconsistent:995 case TemplateDeductionResult::Underqualified:996 case TemplateDeductionResult::DeducedMismatch:997 case TemplateDeductionResult::DeducedMismatchNested:998 case TemplateDeductionResult::NonDeducedMismatch:999 return &static_cast<DFIArguments*>(Data)->SecondArg;1000 1001 // Unhandled1002 case TemplateDeductionResult::MiscellaneousDeductionFailure:1003 case TemplateDeductionResult::AlreadyDiagnosed:1004 break;1005 }1006 1007 return nullptr;1008}1009 1010UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {1011 switch (static_cast<TemplateDeductionResult>(Result)) {1012 case TemplateDeductionResult::DeducedMismatch:1013 case TemplateDeductionResult::DeducedMismatchNested:1014 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;1015 1016 default:1017 return std::nullopt;1018 }1019}1020 1021static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,1022 const FunctionDecl *Y) {1023 if (!X || !Y)1024 return false;1025 if (X->getNumParams() != Y->getNumParams())1026 return false;1027 // FIXME: when do rewritten comparison operators1028 // with explicit object parameters correspond?1029 // https://cplusplus.github.io/CWG/issues/2797.html1030 for (unsigned I = 0; I < X->getNumParams(); ++I)1031 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),1032 Y->getParamDecl(I)->getType()))1033 return false;1034 if (auto *FTX = X->getDescribedFunctionTemplate()) {1035 auto *FTY = Y->getDescribedFunctionTemplate();1036 if (!FTY)1037 return false;1038 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),1039 FTY->getTemplateParameters()))1040 return false;1041 }1042 return true;1043}1044 1045static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,1046 Expr *FirstOperand, FunctionDecl *EqFD) {1047 assert(EqFD->getOverloadedOperator() ==1048 OverloadedOperatorKind::OO_EqualEqual);1049 // C++2a [over.match.oper]p4:1050 // A non-template function or function template F named operator== is a1051 // rewrite target with first operand o unless a search for the name operator!=1052 // in the scope S from the instantiation context of the operator expression1053 // finds a function or function template that would correspond1054 // ([basic.scope.scope]) to F if its name were operator==, where S is the1055 // scope of the class type of o if F is a class member, and the namespace1056 // scope of which F is a member otherwise. A function template specialization1057 // named operator== is a rewrite target if its function template is a rewrite1058 // target.1059 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(1060 OverloadedOperatorKind::OO_ExclaimEqual);1061 if (isa<CXXMethodDecl>(EqFD)) {1062 // If F is a class member, search scope is class type of first operand.1063 QualType RHS = FirstOperand->getType();1064 auto *RHSRec = RHS->getAsCXXRecordDecl();1065 if (!RHSRec)1066 return true;1067 LookupResult Members(S, NotEqOp, OpLoc,1068 Sema::LookupNameKind::LookupMemberName);1069 S.LookupQualifiedName(Members, RHSRec);1070 Members.suppressAccessDiagnostics();1071 for (NamedDecl *Op : Members)1072 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))1073 return false;1074 return true;1075 }1076 // Otherwise the search scope is the namespace scope of which F is a member.1077 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {1078 auto *NotEqFD = Op->getAsFunction();1079 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))1080 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();1081 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&1082 declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),1083 cast<Decl>(Op->getLexicalDeclContext())))1084 return false;1085 }1086 return true;1087}1088 1089bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(1090 OverloadedOperatorKind Op) const {1091 if (!AllowRewrittenCandidates)1092 return false;1093 return Op == OO_EqualEqual || Op == OO_Spaceship;1094}1095 1096bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(1097 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {1098 auto Op = FD->getOverloadedOperator();1099 if (!allowsReversed(Op))1100 return false;1101 if (Op == OverloadedOperatorKind::OO_EqualEqual) {1102 assert(OriginalArgs.size() == 2);1103 if (!shouldAddReversedEqEq(1104 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))1105 return false;1106 }1107 // Don't bother adding a reversed candidate that can never be a better1108 // match than the non-reversed version.1109 return FD->getNumNonObjectParams() != 2 ||1110 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),1111 FD->getParamDecl(1)->getType()) ||1112 FD->hasAttr<EnableIfAttr>();1113}1114 1115void OverloadCandidateSet::destroyCandidates() {1116 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {1117 for (auto &C : i->Conversions)1118 C.~ImplicitConversionSequence();1119 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)1120 i->DeductionFailure.Destroy();1121 }1122}1123 1124void OverloadCandidateSet::clear(CandidateSetKind CSK) {1125 destroyCandidates();1126 SlabAllocator.Reset();1127 NumInlineBytesUsed = 0;1128 Candidates.clear();1129 Functions.clear();1130 Kind = CSK;1131 FirstDeferredCandidate = nullptr;1132 DeferredCandidatesCount = 0;1133 HasDeferredTemplateConstructors = false;1134 ResolutionByPerfectCandidateIsDisabled = false;1135}1136 1137namespace {1138 class UnbridgedCastsSet {1139 struct Entry {1140 Expr **Addr;1141 Expr *Saved;1142 };1143 SmallVector<Entry, 2> Entries;1144 1145 public:1146 void save(Sema &S, Expr *&E) {1147 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));1148 Entry entry = { &E, E };1149 Entries.push_back(entry);1150 E = S.ObjC().stripARCUnbridgedCast(E);1151 }1152 1153 void restore() {1154 for (SmallVectorImpl<Entry>::iterator1155 i = Entries.begin(), e = Entries.end(); i != e; ++i)1156 *i->Addr = i->Saved;1157 }1158 };1159}1160 1161/// checkPlaceholderForOverload - Do any interesting placeholder-like1162/// preprocessing on the given expression.1163///1164/// \param unbridgedCasts a collection to which to add unbridged casts;1165/// without this, they will be immediately diagnosed as errors1166///1167/// Return true on unrecoverable error.1168static bool1169checkPlaceholderForOverload(Sema &S, Expr *&E,1170 UnbridgedCastsSet *unbridgedCasts = nullptr) {1171 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {1172 // We can't handle overloaded expressions here because overload1173 // resolution might reasonably tweak them.1174 if (placeholder->getKind() == BuiltinType::Overload) return false;1175 1176 // If the context potentially accepts unbridged ARC casts, strip1177 // the unbridged cast and add it to the collection for later restoration.1178 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&1179 unbridgedCasts) {1180 unbridgedCasts->save(S, E);1181 return false;1182 }1183 1184 // Go ahead and check everything else.1185 ExprResult result = S.CheckPlaceholderExpr(E);1186 if (result.isInvalid())1187 return true;1188 1189 E = result.get();1190 return false;1191 }1192 1193 // Nothing to do.1194 return false;1195}1196 1197/// checkArgPlaceholdersForOverload - Check a set of call operands for1198/// placeholders.1199static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,1200 UnbridgedCastsSet &unbridged) {1201 for (unsigned i = 0, e = Args.size(); i != e; ++i)1202 if (checkPlaceholderForOverload(S, Args[i], &unbridged))1203 return true;1204 1205 return false;1206}1207 1208OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,1209 const LookupResult &Old, NamedDecl *&Match,1210 bool NewIsUsingDecl) {1211 for (LookupResult::iterator I = Old.begin(), E = Old.end();1212 I != E; ++I) {1213 NamedDecl *OldD = *I;1214 1215 bool OldIsUsingDecl = false;1216 if (isa<UsingShadowDecl>(OldD)) {1217 OldIsUsingDecl = true;1218 1219 // We can always introduce two using declarations into the same1220 // context, even if they have identical signatures.1221 if (NewIsUsingDecl) continue;1222 1223 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();1224 }1225 1226 // A using-declaration does not conflict with another declaration1227 // if one of them is hidden.1228 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))1229 continue;1230 1231 // If either declaration was introduced by a using declaration,1232 // we'll need to use slightly different rules for matching.1233 // Essentially, these rules are the normal rules, except that1234 // function templates hide function templates with different1235 // return types or template parameter lists.1236 bool UseMemberUsingDeclRules =1237 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&1238 !New->getFriendObjectKind();1239 1240 if (FunctionDecl *OldF = OldD->getAsFunction()) {1241 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {1242 if (UseMemberUsingDeclRules && OldIsUsingDecl) {1243 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));1244 continue;1245 }1246 1247 if (!isa<FunctionTemplateDecl>(OldD) &&1248 !shouldLinkPossiblyHiddenDecl(*I, New))1249 continue;1250 1251 Match = *I;1252 return OverloadKind::Match;1253 }1254 1255 // Builtins that have custom typechecking or have a reference should1256 // not be overloadable or redeclarable.1257 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {1258 Match = *I;1259 return OverloadKind::NonFunction;1260 }1261 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {1262 // We can overload with these, which can show up when doing1263 // redeclaration checks for UsingDecls.1264 assert(Old.getLookupKind() == LookupUsingDeclName);1265 } else if (isa<TagDecl>(OldD)) {1266 // We can always overload with tags by hiding them.1267 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {1268 // Optimistically assume that an unresolved using decl will1269 // overload; if it doesn't, we'll have to diagnose during1270 // template instantiation.1271 //1272 // Exception: if the scope is dependent and this is not a class1273 // member, the using declaration can only introduce an enumerator.1274 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {1275 Match = *I;1276 return OverloadKind::NonFunction;1277 }1278 } else {1279 // (C++ 13p1):1280 // Only function declarations can be overloaded; object and type1281 // declarations cannot be overloaded.1282 Match = *I;1283 return OverloadKind::NonFunction;1284 }1285 }1286 1287 // C++ [temp.friend]p1:1288 // For a friend function declaration that is not a template declaration:1289 // -- if the name of the friend is a qualified or unqualified template-id,1290 // [...], otherwise1291 // -- if the name of the friend is a qualified-id and a matching1292 // non-template function is found in the specified class or namespace,1293 // the friend declaration refers to that function, otherwise,1294 // -- if the name of the friend is a qualified-id and a matching function1295 // template is found in the specified class or namespace, the friend1296 // declaration refers to the deduced specialization of that function1297 // template, otherwise1298 // -- the name shall be an unqualified-id [...]1299 // If we get here for a qualified friend declaration, we've just reached the1300 // third bullet. If the type of the friend is dependent, skip this lookup1301 // until instantiation.1302 if (New->getFriendObjectKind() && New->getQualifier() &&1303 !New->getDescribedFunctionTemplate() &&1304 !New->getDependentSpecializationInfo() &&1305 !New->getType()->isDependentType()) {1306 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);1307 TemplateSpecResult.addAllDecls(Old);1308 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,1309 /*QualifiedFriend*/true)) {1310 New->setInvalidDecl();1311 return OverloadKind::Overload;1312 }1313 1314 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();1315 return OverloadKind::Match;1316 }1317 1318 return OverloadKind::Overload;1319}1320 1321template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {1322 assert(D && "function decl should not be null");1323 if (auto *A = D->getAttr<AttrT>())1324 return !A->isImplicit();1325 return false;1326}1327 1328static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,1329 FunctionDecl *Old,1330 bool UseMemberUsingDeclRules,1331 bool ConsiderCudaAttrs,1332 bool UseOverrideRules = false) {1333 // C++ [basic.start.main]p2: This function shall not be overloaded.1334 if (New->isMain())1335 return false;1336 1337 // MSVCRT user defined entry points cannot be overloaded.1338 if (New->isMSVCRTEntryPoint())1339 return false;1340 1341 NamedDecl *OldDecl = Old;1342 NamedDecl *NewDecl = New;1343 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();1344 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();1345 1346 // C++ [temp.fct]p2:1347 // A function template can be overloaded with other function templates1348 // and with normal (non-template) functions.1349 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))1350 return true;1351 1352 // Is the function New an overload of the function Old?1353 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());1354 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());1355 1356 // Compare the signatures (C++ 1.3.10) of the two functions to1357 // determine whether they are overloads. If we find any mismatch1358 // in the signature, they are overloads.1359 1360 // If either of these functions is a K&R-style function (no1361 // prototype), then we consider them to have matching signatures.1362 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||1363 isa<FunctionNoProtoType>(NewQType.getTypePtr()))1364 return false;1365 1366 const auto *OldType = cast<FunctionProtoType>(OldQType);1367 const auto *NewType = cast<FunctionProtoType>(NewQType);1368 1369 // The signature of a function includes the types of its1370 // parameters (C++ 1.3.10), which includes the presence or absence1371 // of the ellipsis; see C++ DR 357).1372 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())1373 return true;1374 1375 // For member-like friends, the enclosing class is part of the signature.1376 if ((New->isMemberLikeConstrainedFriend() ||1377 Old->isMemberLikeConstrainedFriend()) &&1378 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))1379 return true;1380 1381 // Compare the parameter lists.1382 // This can only be done once we have establish that friend functions1383 // inhabit the same context, otherwise we might tried to instantiate1384 // references to non-instantiated entities during constraint substitution.1385 // GH78101.1386 if (NewTemplate) {1387 OldDecl = OldTemplate;1388 NewDecl = NewTemplate;1389 // C++ [temp.over.link]p4:1390 // The signature of a function template consists of its function1391 // signature, its return type and its template parameter list. The names1392 // of the template parameters are significant only for establishing the1393 // relationship between the template parameters and the rest of the1394 // signature.1395 //1396 // We check the return type and template parameter lists for function1397 // templates first; the remaining checks follow.1398 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(1399 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,1400 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);1401 bool SameReturnType = SemaRef.Context.hasSameType(1402 Old->getDeclaredReturnType(), New->getDeclaredReturnType());1403 // FIXME(GH58571): Match template parameter list even for non-constrained1404 // template heads. This currently ensures that the code prior to C++20 is1405 // not newly broken.1406 bool ConstraintsInTemplateHead =1407 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||1408 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();1409 // C++ [namespace.udecl]p11:1410 // The set of declarations named by a using-declarator that inhabits a1411 // class C does not include member functions and member function1412 // templates of a base class that "correspond" to (and thus would1413 // conflict with) a declaration of a function or function template in1414 // C.1415 // Comparing return types is not required for the "correspond" check to1416 // decide whether a member introduced by a shadow declaration is hidden.1417 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&1418 !SameTemplateParameterList)1419 return true;1420 if (!UseMemberUsingDeclRules &&1421 (!SameTemplateParameterList || !SameReturnType))1422 return true;1423 }1424 1425 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);1426 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);1427 1428 int OldParamsOffset = 0;1429 int NewParamsOffset = 0;1430 1431 // When determining if a method is an overload from a base class, act as if1432 // the implicit object parameter are of the same type.1433 1434 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {1435 if (M->isExplicitObjectMemberFunction()) {1436 auto ThisType = M->getFunctionObjectParameterReferenceType();1437 if (ThisType.isConstQualified())1438 Q.removeConst();1439 return Q;1440 }1441 1442 // We do not allow overloading based off of '__restrict'.1443 Q.removeRestrict();1444 1445 // We may not have applied the implicit const for a constexpr member1446 // function yet (because we haven't yet resolved whether this is a static1447 // or non-static member function). Add it now, on the assumption that this1448 // is a redeclaration of OldMethod.1449 if (!SemaRef.getLangOpts().CPlusPlus14 &&1450 (M->isConstexpr() || M->isConsteval()) &&1451 !isa<CXXConstructorDecl>(NewMethod))1452 Q.addConst();1453 return Q;1454 };1455 1456 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {1457 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);1458 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);1459 1460 if (OldMethod->isExplicitObjectMemberFunction()) {1461 BS.Quals.removeVolatile();1462 DS.Quals.removeVolatile();1463 }1464 1465 return BS.Quals == DS.Quals;1466 };1467 1468 auto CompareType = [&](QualType Base, QualType D) {1469 auto BS = Base.getNonReferenceType().getCanonicalType().split();1470 auto DS = D.getNonReferenceType().getCanonicalType().split();1471 1472 if (!AreQualifiersEqual(BS, DS))1473 return false;1474 1475 if (OldMethod->isImplicitObjectMemberFunction() &&1476 OldMethod->getParent() != NewMethod->getParent()) {1477 CanQualType ParentType =1478 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());1479 if (ParentType.getTypePtr() != BS.Ty)1480 return false;1481 BS.Ty = DS.Ty;1482 }1483 1484 // FIXME: should we ignore some type attributes here?1485 if (BS.Ty != DS.Ty)1486 return false;1487 1488 if (Base->isLValueReferenceType())1489 return D->isLValueReferenceType();1490 return Base->isRValueReferenceType() == D->isRValueReferenceType();1491 };1492 1493 // If the function is a class member, its signature includes the1494 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.1495 auto DiagnoseInconsistentRefQualifiers = [&]() {1496 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)1497 return false;1498 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())1499 return false;1500 if (OldMethod->isExplicitObjectMemberFunction() ||1501 NewMethod->isExplicitObjectMemberFunction())1502 return false;1503 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||1504 NewMethod->getRefQualifier() == RQ_None)) {1505 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)1506 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();1507 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);1508 return true;1509 }1510 return false;1511 };1512 1513 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())1514 OldParamsOffset++;1515 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())1516 NewParamsOffset++;1517 1518 if (OldType->getNumParams() - OldParamsOffset !=1519 NewType->getNumParams() - NewParamsOffset ||1520 !SemaRef.FunctionParamTypesAreEqual(1521 {OldType->param_type_begin() + OldParamsOffset,1522 OldType->param_type_end()},1523 {NewType->param_type_begin() + NewParamsOffset,1524 NewType->param_type_end()},1525 nullptr)) {1526 return true;1527 }1528 1529 if (OldMethod && NewMethod && !OldMethod->isStatic() &&1530 !NewMethod->isStatic()) {1531 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,1532 const CXXMethodDecl *New) {1533 auto NewObjectType = New->getFunctionObjectParameterReferenceType();1534 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();1535 1536 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {1537 return F->getRefQualifier() == RQ_None &&1538 !F->isExplicitObjectMemberFunction();1539 };1540 1541 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&1542 CompareType(OldObjectType.getNonReferenceType(),1543 NewObjectType.getNonReferenceType()))1544 return true;1545 return CompareType(OldObjectType, NewObjectType);1546 }(OldMethod, NewMethod);1547 1548 if (!HaveCorrespondingObjectParameters) {1549 if (DiagnoseInconsistentRefQualifiers())1550 return true;1551 // CWG25541552 // and, if at least one is an explicit object member function, ignoring1553 // object parameters1554 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&1555 !OldMethod->isExplicitObjectMemberFunction()))1556 return true;1557 }1558 }1559 1560 if (!UseOverrideRules &&1561 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {1562 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),1563 OldRC = Old->getTrailingRequiresClause();1564 if (!NewRC != !OldRC)1565 return true;1566 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)1567 return true;1568 if (NewRC &&1569 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,1570 NewDecl, NewRC.ConstraintExpr))1571 return true;1572 }1573 1574 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&1575 NewMethod->isImplicitObjectMemberFunction()) {1576 if (DiagnoseInconsistentRefQualifiers())1577 return true;1578 }1579 1580 // Though pass_object_size is placed on parameters and takes an argument, we1581 // consider it to be a function-level modifier for the sake of function1582 // identity. Either the function has one or more parameters with1583 // pass_object_size or it doesn't.1584 if (functionHasPassObjectSizeParams(New) !=1585 functionHasPassObjectSizeParams(Old))1586 return true;1587 1588 // enable_if attributes are an order-sensitive part of the signature.1589 for (specific_attr_iterator<EnableIfAttr>1590 NewI = New->specific_attr_begin<EnableIfAttr>(),1591 NewE = New->specific_attr_end<EnableIfAttr>(),1592 OldI = Old->specific_attr_begin<EnableIfAttr>(),1593 OldE = Old->specific_attr_end<EnableIfAttr>();1594 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {1595 if (NewI == NewE || OldI == OldE)1596 return true;1597 llvm::FoldingSetNodeID NewID, OldID;1598 NewI->getCond()->Profile(NewID, SemaRef.Context, true);1599 OldI->getCond()->Profile(OldID, SemaRef.Context, true);1600 if (NewID != OldID)1601 return true;1602 }1603 1604 // At this point, it is known that the two functions have the same signature.1605 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {1606 // Don't allow overloading of destructors. (In theory we could, but it1607 // would be a giant change to clang.)1608 if (!isa<CXXDestructorDecl>(New)) {1609 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),1610 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);1611 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {1612 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&1613 "Unexpected invalid target.");1614 1615 // Allow overloading of functions with same signature and different CUDA1616 // target attributes.1617 if (NewTarget != OldTarget) {1618 // Special case: non-constexpr function is allowed to override1619 // constexpr virtual function1620 if (OldMethod && NewMethod && OldMethod->isVirtual() &&1621 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&1622 !hasExplicitAttr<CUDAHostAttr>(Old) &&1623 !hasExplicitAttr<CUDADeviceAttr>(Old) &&1624 !hasExplicitAttr<CUDAHostAttr>(New) &&1625 !hasExplicitAttr<CUDADeviceAttr>(New)) {1626 return false;1627 }1628 return true;1629 }1630 }1631 }1632 }1633 1634 // The signatures match; this is not an overload.1635 return false;1636}1637 1638bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,1639 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {1640 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,1641 ConsiderCudaAttrs);1642}1643 1644bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,1645 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {1646 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,1647 /*UseMemberUsingDeclRules=*/false,1648 /*ConsiderCudaAttrs=*/true,1649 /*UseOverrideRules=*/true);1650}1651 1652/// Tries a user-defined conversion from From to ToType.1653///1654/// Produces an implicit conversion sequence for when a standard conversion1655/// is not an option. See TryImplicitConversion for more information.1656static ImplicitConversionSequence1657TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,1658 bool SuppressUserConversions,1659 AllowedExplicit AllowExplicit,1660 bool InOverloadResolution,1661 bool CStyle,1662 bool AllowObjCWritebackConversion,1663 bool AllowObjCConversionOnExplicit) {1664 ImplicitConversionSequence ICS;1665 1666 if (SuppressUserConversions) {1667 // We're not in the case above, so there is no conversion that1668 // we can perform.1669 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);1670 return ICS;1671 }1672 1673 // Attempt user-defined conversion.1674 OverloadCandidateSet Conversions(From->getExprLoc(),1675 OverloadCandidateSet::CSK_Normal);1676 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,1677 Conversions, AllowExplicit,1678 AllowObjCConversionOnExplicit)) {1679 case OR_Success:1680 case OR_Deleted:1681 ICS.setUserDefined();1682 // C++ [over.ics.user]p4:1683 // A conversion of an expression of class type to the same class1684 // type is given Exact Match rank, and a conversion of an1685 // expression of class type to a base class of that type is1686 // given Conversion rank, in spite of the fact that a copy1687 // constructor (i.e., a user-defined conversion function) is1688 // called for those cases.1689 if (CXXConstructorDecl *Constructor1690 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {1691 QualType FromType;1692 SourceLocation FromLoc;1693 // C++11 [over.ics.list]p6, per DR2137:1694 // C++17 [over.ics.list]p6:1695 // If C is not an initializer-list constructor and the initializer list1696 // has a single element of type cv U, where U is X or a class derived1697 // from X, the implicit conversion sequence has Exact Match rank if U is1698 // X, or Conversion rank if U is derived from X.1699 bool FromListInit = false;1700 if (const auto *InitList = dyn_cast<InitListExpr>(From);1701 InitList && InitList->getNumInits() == 1 &&1702 !S.isInitListConstructor(Constructor)) {1703 const Expr *SingleInit = InitList->getInit(0);1704 FromType = SingleInit->getType();1705 FromLoc = SingleInit->getBeginLoc();1706 FromListInit = true;1707 } else {1708 FromType = From->getType();1709 FromLoc = From->getBeginLoc();1710 }1711 QualType FromCanon =1712 S.Context.getCanonicalType(FromType.getUnqualifiedType());1713 QualType ToCanon1714 = S.Context.getCanonicalType(ToType).getUnqualifiedType();1715 if ((FromCanon == ToCanon ||1716 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {1717 // Turn this into a "standard" conversion sequence, so that it1718 // gets ranked with standard conversion sequences.1719 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;1720 ICS.setStandard();1721 ICS.Standard.setAsIdentityConversion();1722 ICS.Standard.setFromType(FromType);1723 ICS.Standard.setAllToTypes(ToType);1724 ICS.Standard.FromBracedInitList = FromListInit;1725 ICS.Standard.CopyConstructor = Constructor;1726 ICS.Standard.FoundCopyConstructor = Found;1727 if (ToCanon != FromCanon)1728 ICS.Standard.Second = ICK_Derived_To_Base;1729 }1730 }1731 break;1732 1733 case OR_Ambiguous:1734 ICS.setAmbiguous();1735 ICS.Ambiguous.setFromType(From->getType());1736 ICS.Ambiguous.setToType(ToType);1737 for (OverloadCandidateSet::iterator Cand = Conversions.begin();1738 Cand != Conversions.end(); ++Cand)1739 if (Cand->Best)1740 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);1741 break;1742 1743 // Fall through.1744 case OR_No_Viable_Function:1745 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);1746 break;1747 }1748 1749 return ICS;1750}1751 1752/// TryImplicitConversion - Attempt to perform an implicit conversion1753/// from the given expression (Expr) to the given type (ToType). This1754/// function returns an implicit conversion sequence that can be used1755/// to perform the initialization. Given1756///1757/// void f(float f);1758/// void g(int i) { f(i); }1759///1760/// this routine would produce an implicit conversion sequence to1761/// describe the initialization of f from i, which will be a standard1762/// conversion sequence containing an lvalue-to-rvalue conversion (C++1763/// 4.1) followed by a floating-integral conversion (C++ 4.9).1764//1765/// Note that this routine only determines how the conversion can be1766/// performed; it does not actually perform the conversion. As such,1767/// it will not produce any diagnostics if no conversion is available,1768/// but will instead return an implicit conversion sequence of kind1769/// "BadConversion".1770///1771/// If @p SuppressUserConversions, then user-defined conversions are1772/// not permitted.1773/// If @p AllowExplicit, then explicit user-defined conversions are1774/// permitted.1775///1776/// \param AllowObjCWritebackConversion Whether we allow the Objective-C1777/// writeback conversion, which allows __autoreleasing id* parameters to1778/// be initialized with __strong id* or __weak id* arguments.1779static ImplicitConversionSequence1780TryImplicitConversion(Sema &S, Expr *From, QualType ToType,1781 bool SuppressUserConversions,1782 AllowedExplicit AllowExplicit,1783 bool InOverloadResolution,1784 bool CStyle,1785 bool AllowObjCWritebackConversion,1786 bool AllowObjCConversionOnExplicit) {1787 ImplicitConversionSequence ICS;1788 if (IsStandardConversion(S, From, ToType, InOverloadResolution,1789 ICS.Standard, CStyle, AllowObjCWritebackConversion)){1790 ICS.setStandard();1791 return ICS;1792 }1793 1794 if (!S.getLangOpts().CPlusPlus) {1795 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);1796 return ICS;1797 }1798 1799 // C++ [over.ics.user]p4:1800 // A conversion of an expression of class type to the same class1801 // type is given Exact Match rank, and a conversion of an1802 // expression of class type to a base class of that type is1803 // given Conversion rank, in spite of the fact that a copy/move1804 // constructor (i.e., a user-defined conversion function) is1805 // called for those cases.1806 QualType FromType = From->getType();1807 if (ToType->isRecordType() &&1808 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||1809 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {1810 ICS.setStandard();1811 ICS.Standard.setAsIdentityConversion();1812 ICS.Standard.setFromType(FromType);1813 ICS.Standard.setAllToTypes(ToType);1814 1815 // We don't actually check at this point whether there is a valid1816 // copy/move constructor, since overloading just assumes that it1817 // exists. When we actually perform initialization, we'll find the1818 // appropriate constructor to copy the returned object, if needed.1819 ICS.Standard.CopyConstructor = nullptr;1820 1821 // Determine whether this is considered a derived-to-base conversion.1822 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))1823 ICS.Standard.Second = ICK_Derived_To_Base;1824 1825 return ICS;1826 }1827 1828 if (S.getLangOpts().HLSL) {1829 // Handle conversion of the HLSL resource types.1830 const Type *FromTy = FromType->getUnqualifiedDesugaredType();1831 if (FromTy->isHLSLAttributedResourceType()) {1832 // Attributed resource types can convert to other attributed1833 // resource types with the same attributes and contained types,1834 // or to __hlsl_resource_t without any attributes.1835 bool CanConvert = false;1836 const Type *ToTy = ToType->getUnqualifiedDesugaredType();1837 if (ToTy->isHLSLAttributedResourceType()) {1838 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);1839 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);1840 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),1841 FromResType->getWrappedType()) &&1842 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),1843 FromResType->getContainedType()) &&1844 ToResType->getAttrs() == FromResType->getAttrs())1845 CanConvert = true;1846 } else if (ToTy->isHLSLResourceType()) {1847 CanConvert = true;1848 }1849 if (CanConvert) {1850 ICS.setStandard();1851 ICS.Standard.setAsIdentityConversion();1852 ICS.Standard.setFromType(FromType);1853 ICS.Standard.setAllToTypes(ToType);1854 return ICS;1855 }1856 }1857 }1858 1859 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,1860 AllowExplicit, InOverloadResolution, CStyle,1861 AllowObjCWritebackConversion,1862 AllowObjCConversionOnExplicit);1863}1864 1865ImplicitConversionSequence1866Sema::TryImplicitConversion(Expr *From, QualType ToType,1867 bool SuppressUserConversions,1868 AllowedExplicit AllowExplicit,1869 bool InOverloadResolution,1870 bool CStyle,1871 bool AllowObjCWritebackConversion) {1872 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,1873 AllowExplicit, InOverloadResolution, CStyle,1874 AllowObjCWritebackConversion,1875 /*AllowObjCConversionOnExplicit=*/false);1876}1877 1878ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,1879 AssignmentAction Action,1880 bool AllowExplicit) {1881 if (checkPlaceholderForOverload(*this, From))1882 return ExprError();1883 1884 // Objective-C ARC: Determine whether we will allow the writeback conversion.1885 bool AllowObjCWritebackConversion =1886 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||1887 Action == AssignmentAction::Sending);1888 if (getLangOpts().ObjC)1889 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,1890 From->getType(), From);1891 ImplicitConversionSequence ICS = ::TryImplicitConversion(1892 *this, From, ToType,1893 /*SuppressUserConversions=*/false,1894 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,1895 /*InOverloadResolution=*/false,1896 /*CStyle=*/false, AllowObjCWritebackConversion,1897 /*AllowObjCConversionOnExplicit=*/false);1898 return PerformImplicitConversion(From, ToType, ICS, Action);1899}1900 1901bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,1902 QualType &ResultTy) const {1903 bool Changed = IsFunctionConversion(FromType, ToType);1904 if (Changed)1905 ResultTy = ToType;1906 return Changed;1907}1908 1909bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {1910 if (Context.hasSameUnqualifiedType(FromType, ToType))1911 return false;1912 1913 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)1914 // or F(t noexcept) -> F(t)1915 // where F adds one of the following at most once:1916 // - a pointer1917 // - a member pointer1918 // - a block pointer1919 // Changes here need matching changes in FindCompositePointerType.1920 CanQualType CanTo = Context.getCanonicalType(ToType);1921 CanQualType CanFrom = Context.getCanonicalType(FromType);1922 Type::TypeClass TyClass = CanTo->getTypeClass();1923 if (TyClass != CanFrom->getTypeClass()) return false;1924 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {1925 if (TyClass == Type::Pointer) {1926 CanTo = CanTo.castAs<PointerType>()->getPointeeType();1927 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();1928 } else if (TyClass == Type::BlockPointer) {1929 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();1930 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();1931 } else if (TyClass == Type::MemberPointer) {1932 auto ToMPT = CanTo.castAs<MemberPointerType>();1933 auto FromMPT = CanFrom.castAs<MemberPointerType>();1934 // A function pointer conversion cannot change the class of the function.1935 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),1936 FromMPT->getMostRecentCXXRecordDecl()))1937 return false;1938 CanTo = ToMPT->getPointeeType();1939 CanFrom = FromMPT->getPointeeType();1940 } else {1941 return false;1942 }1943 1944 TyClass = CanTo->getTypeClass();1945 if (TyClass != CanFrom->getTypeClass()) return false;1946 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)1947 return false;1948 }1949 1950 const auto *FromFn = cast<FunctionType>(CanFrom);1951 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();1952 1953 const auto *ToFn = cast<FunctionType>(CanTo);1954 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();1955 1956 bool Changed = false;1957 1958 // Drop 'noreturn' if not present in target type.1959 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {1960 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));1961 Changed = true;1962 }1963 1964 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);1965 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);1966 1967 if (FromFPT && ToFPT) {1968 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {1969 QualType NewTy = Context.getFunctionType(1970 FromFPT->getReturnType(), FromFPT->getParamTypes(),1971 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(1972 ToFPT->hasCFIUncheckedCallee()));1973 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());1974 FromFn = FromFPT;1975 Changed = true;1976 }1977 }1978 1979 // Drop 'noexcept' if not present in target type.1980 if (FromFPT && ToFPT) {1981 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {1982 FromFn = cast<FunctionType>(1983 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),1984 EST_None)1985 .getTypePtr());1986 Changed = true;1987 }1988 1989 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid1990 // only if the ExtParameterInfo lists of the two function prototypes can be1991 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.1992 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;1993 bool CanUseToFPT, CanUseFromFPT;1994 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,1995 CanUseFromFPT, NewParamInfos) &&1996 CanUseToFPT && !CanUseFromFPT) {1997 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();1998 ExtInfo.ExtParameterInfos =1999 NewParamInfos.empty() ? nullptr : NewParamInfos.data();2000 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),2001 FromFPT->getParamTypes(), ExtInfo);2002 FromFn = QT->getAs<FunctionType>();2003 Changed = true;2004 }2005 2006 if (Context.hasAnyFunctionEffects()) {2007 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above2008 2009 // Transparently add/drop effects; here we are concerned with2010 // language rules/canonicalization. Adding/dropping effects is a warning.2011 const auto FromFX = FromFPT->getFunctionEffects();2012 const auto ToFX = ToFPT->getFunctionEffects();2013 if (FromFX != ToFX) {2014 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();2015 ExtInfo.FunctionEffects = ToFX;2016 QualType QT = Context.getFunctionType(2017 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);2018 FromFn = QT->getAs<FunctionType>();2019 Changed = true;2020 }2021 }2022 }2023 2024 if (!Changed)2025 return false;2026 2027 assert(QualType(FromFn, 0).isCanonical());2028 if (QualType(FromFn, 0) != CanTo) return false;2029 2030 return true;2031}2032 2033/// Determine whether the conversion from FromType to ToType is a valid2034/// floating point conversion.2035///2036static bool IsFloatingPointConversion(Sema &S, QualType FromType,2037 QualType ToType) {2038 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())2039 return false;2040 // FIXME: disable conversions between long double, __ibm128 and __float1282041 // if their representation is different until there is back end support2042 // We of course allow this conversion if long double is really double.2043 2044 // Conversions between bfloat16 and float16 are currently not supported.2045 if ((FromType->isBFloat16Type() &&2046 (ToType->isFloat16Type() || ToType->isHalfType())) ||2047 (ToType->isBFloat16Type() &&2048 (FromType->isFloat16Type() || FromType->isHalfType())))2049 return false;2050 2051 // Conversions between IEEE-quad and IBM-extended semantics are not2052 // permitted.2053 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);2054 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);2055 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&2056 &ToSem == &llvm::APFloat::IEEEquad()) ||2057 (&FromSem == &llvm::APFloat::IEEEquad() &&2058 &ToSem == &llvm::APFloat::PPCDoubleDouble()))2059 return false;2060 return true;2061}2062 2063static bool IsVectorElementConversion(Sema &S, QualType FromType,2064 QualType ToType,2065 ImplicitConversionKind &ICK, Expr *From) {2066 if (S.Context.hasSameUnqualifiedType(FromType, ToType))2067 return true;2068 2069 if (S.IsFloatingPointPromotion(FromType, ToType)) {2070 ICK = ICK_Floating_Promotion;2071 return true;2072 }2073 2074 if (IsFloatingPointConversion(S, FromType, ToType)) {2075 ICK = ICK_Floating_Conversion;2076 return true;2077 }2078 2079 if (ToType->isBooleanType() && FromType->isArithmeticType()) {2080 ICK = ICK_Boolean_Conversion;2081 return true;2082 }2083 2084 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||2085 (FromType->isIntegralOrUnscopedEnumerationType() &&2086 ToType->isRealFloatingType())) {2087 ICK = ICK_Floating_Integral;2088 return true;2089 }2090 2091 if (S.IsIntegralPromotion(From, FromType, ToType)) {2092 ICK = ICK_Integral_Promotion;2093 return true;2094 }2095 2096 if (FromType->isIntegralOrUnscopedEnumerationType() &&2097 ToType->isIntegralType(S.Context)) {2098 ICK = ICK_Integral_Conversion;2099 return true;2100 }2101 2102 return false;2103}2104 2105/// Determine whether the conversion from FromType to ToType is a valid2106/// vector conversion.2107///2108/// \param ICK Will be set to the vector conversion kind, if this is a vector2109/// conversion.2110static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,2111 ImplicitConversionKind &ICK,2112 ImplicitConversionKind &ElConv, Expr *From,2113 bool InOverloadResolution, bool CStyle) {2114 // We need at least one of these types to be a vector type to have a vector2115 // conversion.2116 if (!ToType->isVectorType() && !FromType->isVectorType())2117 return false;2118 2119 // Identical types require no conversions.2120 if (S.Context.hasSameUnqualifiedType(FromType, ToType))2121 return false;2122 2123 // HLSL allows implicit truncation of vector types.2124 if (S.getLangOpts().HLSL) {2125 auto *ToExtType = ToType->getAs<ExtVectorType>();2126 auto *FromExtType = FromType->getAs<ExtVectorType>();2127 2128 // If both arguments are vectors, handle possible vector truncation and2129 // element conversion.2130 if (ToExtType && FromExtType) {2131 unsigned FromElts = FromExtType->getNumElements();2132 unsigned ToElts = ToExtType->getNumElements();2133 if (FromElts < ToElts)2134 return false;2135 if (FromElts == ToElts)2136 ElConv = ICK_Identity;2137 else2138 ElConv = ICK_HLSL_Vector_Truncation;2139 2140 QualType FromElTy = FromExtType->getElementType();2141 QualType ToElTy = ToExtType->getElementType();2142 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))2143 return true;2144 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);2145 }2146 if (FromExtType && !ToExtType) {2147 ElConv = ICK_HLSL_Vector_Truncation;2148 QualType FromElTy = FromExtType->getElementType();2149 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))2150 return true;2151 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);2152 }2153 // Fallthrough for the case where ToType is a vector and FromType is not.2154 }2155 2156 // There are no conversions between extended vector types, only identity.2157 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {2158 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {2159 // Implicit conversions require the same number of elements.2160 if (ToExtType->getNumElements() != FromExtType->getNumElements())2161 return false;2162 2163 // Permit implicit conversions from integral values to boolean vectors.2164 if (ToType->isExtVectorBoolType() &&2165 FromExtType->getElementType()->isIntegerType()) {2166 ICK = ICK_Boolean_Conversion;2167 return true;2168 }2169 // There are no other conversions between extended vector types.2170 return false;2171 }2172 2173 // Vector splat from any arithmetic type to a vector.2174 if (FromType->isArithmeticType()) {2175 if (S.getLangOpts().HLSL) {2176 ElConv = ICK_HLSL_Vector_Splat;2177 QualType ToElTy = ToExtType->getElementType();2178 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);2179 }2180 ICK = ICK_Vector_Splat;2181 return true;2182 }2183 }2184 2185 if (ToType->isSVESizelessBuiltinType() ||2186 FromType->isSVESizelessBuiltinType())2187 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||2188 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {2189 ICK = ICK_SVE_Vector_Conversion;2190 return true;2191 }2192 2193 if (ToType->isRVVSizelessBuiltinType() ||2194 FromType->isRVVSizelessBuiltinType())2195 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||2196 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {2197 ICK = ICK_RVV_Vector_Conversion;2198 return true;2199 }2200 2201 // We can perform the conversion between vector types in the following cases:2202 // 1)vector types are equivalent AltiVec and GCC vector types2203 // 2)lax vector conversions are permitted and the vector types are of the2204 // same size2205 // 3)the destination type does not have the ARM MVE strict-polymorphism2206 // attribute, which inhibits lax vector conversion for overload resolution2207 // only2208 if (ToType->isVectorType() && FromType->isVectorType()) {2209 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||2210 (S.isLaxVectorConversion(FromType, ToType) &&2211 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {2212 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&2213 S.isLaxVectorConversion(FromType, ToType) &&2214 S.anyAltivecTypes(FromType, ToType) &&2215 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&2216 !InOverloadResolution && !CStyle) {2217 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)2218 << FromType << ToType;2219 }2220 ICK = ICK_Vector_Conversion;2221 return true;2222 }2223 }2224 2225 return false;2226}2227 2228static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,2229 bool InOverloadResolution,2230 StandardConversionSequence &SCS,2231 bool CStyle);2232 2233/// IsStandardConversion - Determines whether there is a standard2234/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the2235/// expression From to the type ToType. Standard conversion sequences2236/// only consider non-class types; for conversions that involve class2237/// types, use TryImplicitConversion. If a conversion exists, SCS will2238/// contain the standard conversion sequence required to perform this2239/// conversion and this routine will return true. Otherwise, this2240/// routine will return false and the value of SCS is unspecified.2241static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,2242 bool InOverloadResolution,2243 StandardConversionSequence &SCS,2244 bool CStyle,2245 bool AllowObjCWritebackConversion) {2246 QualType FromType = From->getType();2247 2248 // Standard conversions (C++ [conv])2249 SCS.setAsIdentityConversion();2250 SCS.IncompatibleObjC = false;2251 SCS.setFromType(FromType);2252 SCS.CopyConstructor = nullptr;2253 2254 // There are no standard conversions for class types in C++, so2255 // abort early. When overloading in C, however, we do permit them.2256 if (S.getLangOpts().CPlusPlus &&2257 (FromType->isRecordType() || ToType->isRecordType()))2258 return false;2259 2260 // The first conversion can be an lvalue-to-rvalue conversion,2261 // array-to-pointer conversion, or function-to-pointer conversion2262 // (C++ 4p1).2263 2264 if (FromType == S.Context.OverloadTy) {2265 DeclAccessPair AccessPair;2266 if (FunctionDecl *Fn2267 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,2268 AccessPair)) {2269 // We were able to resolve the address of the overloaded function,2270 // so we can convert to the type of that function.2271 FromType = Fn->getType();2272 SCS.setFromType(FromType);2273 2274 // we can sometimes resolve &foo<int> regardless of ToType, so check2275 // if the type matches (identity) or we are converting to bool2276 if (!S.Context.hasSameUnqualifiedType(2277 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {2278 // if the function type matches except for [[noreturn]], it's ok2279 if (!S.IsFunctionConversion(FromType,2280 S.ExtractUnqualifiedFunctionType(ToType)))2281 // otherwise, only a boolean conversion is standard2282 if (!ToType->isBooleanType())2283 return false;2284 }2285 2286 // Check if the "from" expression is taking the address of an overloaded2287 // function and recompute the FromType accordingly. Take advantage of the2288 // fact that non-static member functions *must* have such an address-of2289 // expression.2290 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);2291 if (Method && !Method->isStatic() &&2292 !Method->isExplicitObjectMemberFunction()) {2293 assert(isa<UnaryOperator>(From->IgnoreParens()) &&2294 "Non-unary operator on non-static member address");2295 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()2296 == UO_AddrOf &&2297 "Non-address-of operator on non-static member address");2298 FromType = S.Context.getMemberPointerType(2299 FromType, /*Qualifier=*/std::nullopt, Method->getParent());2300 } else if (isa<UnaryOperator>(From->IgnoreParens())) {2301 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==2302 UO_AddrOf &&2303 "Non-address-of operator for overloaded function expression");2304 FromType = S.Context.getPointerType(FromType);2305 }2306 } else {2307 return false;2308 }2309 }2310 2311 bool argIsLValue = From->isGLValue();2312 // To handle conversion from ArrayParameterType to ConstantArrayType2313 // this block must be above the one below because Array parameters2314 // do not decay and when handling HLSLOutArgExprs and2315 // the From expression is an LValue.2316 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&2317 ToType->isConstantArrayType()) {2318 // HLSL constant array parameters do not decay, so if the argument is a2319 // constant array and the parameter is an ArrayParameterType we have special2320 // handling here.2321 if (ToType->isArrayParameterType()) {2322 FromType = S.Context.getArrayParameterType(FromType);2323 } else if (FromType->isArrayParameterType()) {2324 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);2325 FromType = APT->getConstantArrayType(S.Context);2326 }2327 2328 SCS.First = ICK_HLSL_Array_RValue;2329 2330 // Don't consider qualifiers, which include things like address spaces2331 if (FromType.getCanonicalType().getUnqualifiedType() !=2332 ToType.getCanonicalType().getUnqualifiedType())2333 return false;2334 2335 SCS.setAllToTypes(ToType);2336 return true;2337 } else if (argIsLValue && !FromType->canDecayToPointerType() &&2338 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {2339 // Lvalue-to-rvalue conversion (C++11 4.1):2340 // A glvalue (3.10) of a non-function, non-array type T can2341 // be converted to a prvalue.2342 2343 SCS.First = ICK_Lvalue_To_Rvalue;2344 2345 // C11 6.3.2.1p2:2346 // ... if the lvalue has atomic type, the value has the non-atomic version2347 // of the type of the lvalue ...2348 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())2349 FromType = Atomic->getValueType();2350 2351 // If T is a non-class type, the type of the rvalue is the2352 // cv-unqualified version of T. Otherwise, the type of the rvalue2353 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we2354 // just strip the qualifiers because they don't matter.2355 FromType = FromType.getUnqualifiedType();2356 } else if (FromType->isArrayType()) {2357 // Array-to-pointer conversion (C++ 4.2)2358 SCS.First = ICK_Array_To_Pointer;2359 2360 // An lvalue or rvalue of type "array of N T" or "array of unknown2361 // bound of T" can be converted to an rvalue of type "pointer to2362 // T" (C++ 4.2p1).2363 FromType = S.Context.getArrayDecayedType(FromType);2364 2365 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {2366 // This conversion is deprecated in C++03 (D.4)2367 SCS.DeprecatedStringLiteralToCharPtr = true;2368 2369 // For the purpose of ranking in overload resolution2370 // (13.3.3.1.1), this conversion is considered an2371 // array-to-pointer conversion followed by a qualification2372 // conversion (4.4). (C++ 4.2p2)2373 SCS.Second = ICK_Identity;2374 SCS.Third = ICK_Qualification;2375 SCS.QualificationIncludesObjCLifetime = false;2376 SCS.setAllToTypes(FromType);2377 return true;2378 }2379 } else if (FromType->isFunctionType() && argIsLValue) {2380 // Function-to-pointer conversion (C++ 4.3).2381 SCS.First = ICK_Function_To_Pointer;2382 2383 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))2384 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))2385 if (!S.checkAddressOfFunctionIsAvailable(FD))2386 return false;2387 2388 // An lvalue of function type T can be converted to an rvalue of2389 // type "pointer to T." The result is a pointer to the2390 // function. (C++ 4.3p1).2391 FromType = S.Context.getPointerType(FromType);2392 } else {2393 // We don't require any conversions for the first step.2394 SCS.First = ICK_Identity;2395 }2396 SCS.setToType(0, FromType);2397 2398 // The second conversion can be an integral promotion, floating2399 // point promotion, integral conversion, floating point conversion,2400 // floating-integral conversion, pointer conversion,2401 // pointer-to-member conversion, or boolean conversion (C++ 4p1).2402 // For overloading in C, this can also be a "compatible-type"2403 // conversion.2404 bool IncompatibleObjC = false;2405 ImplicitConversionKind SecondICK = ICK_Identity;2406 ImplicitConversionKind DimensionICK = ICK_Identity;2407 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {2408 // The unqualified versions of the types are the same: there's no2409 // conversion to do.2410 SCS.Second = ICK_Identity;2411 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {2412 // Integral promotion (C++ 4.5).2413 SCS.Second = ICK_Integral_Promotion;2414 FromType = ToType.getUnqualifiedType();2415 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {2416 // Floating point promotion (C++ 4.6).2417 SCS.Second = ICK_Floating_Promotion;2418 FromType = ToType.getUnqualifiedType();2419 } else if (S.IsComplexPromotion(FromType, ToType)) {2420 // Complex promotion (Clang extension)2421 SCS.Second = ICK_Complex_Promotion;2422 FromType = ToType.getUnqualifiedType();2423 } else if (ToType->isBooleanType() &&2424 (FromType->isArithmeticType() ||2425 FromType->isAnyPointerType() ||2426 FromType->isBlockPointerType() ||2427 FromType->isMemberPointerType())) {2428 // Boolean conversions (C++ 4.12).2429 SCS.Second = ICK_Boolean_Conversion;2430 FromType = S.Context.BoolTy;2431 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&2432 ToType->isIntegralType(S.Context)) {2433 // Integral conversions (C++ 4.7).2434 SCS.Second = ICK_Integral_Conversion;2435 FromType = ToType.getUnqualifiedType();2436 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {2437 // Complex conversions (C99 6.3.1.6)2438 SCS.Second = ICK_Complex_Conversion;2439 FromType = ToType.getUnqualifiedType();2440 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||2441 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {2442 // Complex-real conversions (C99 6.3.1.7)2443 SCS.Second = ICK_Complex_Real;2444 FromType = ToType.getUnqualifiedType();2445 } else if (IsFloatingPointConversion(S, FromType, ToType)) {2446 // Floating point conversions (C++ 4.8).2447 SCS.Second = ICK_Floating_Conversion;2448 FromType = ToType.getUnqualifiedType();2449 } else if ((FromType->isRealFloatingType() &&2450 ToType->isIntegralType(S.Context)) ||2451 (FromType->isIntegralOrUnscopedEnumerationType() &&2452 ToType->isRealFloatingType())) {2453 2454 // Floating-integral conversions (C++ 4.9).2455 SCS.Second = ICK_Floating_Integral;2456 FromType = ToType.getUnqualifiedType();2457 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {2458 SCS.Second = ICK_Block_Pointer_Conversion;2459 } else if (AllowObjCWritebackConversion &&2460 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {2461 SCS.Second = ICK_Writeback_Conversion;2462 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,2463 FromType, IncompatibleObjC)) {2464 // Pointer conversions (C++ 4.10).2465 SCS.Second = ICK_Pointer_Conversion;2466 SCS.IncompatibleObjC = IncompatibleObjC;2467 FromType = FromType.getUnqualifiedType();2468 } else if (S.IsMemberPointerConversion(From, FromType, ToType,2469 InOverloadResolution, FromType)) {2470 // Pointer to member conversions (4.11).2471 SCS.Second = ICK_Pointer_Member;2472 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,2473 From, InOverloadResolution, CStyle)) {2474 SCS.Second = SecondICK;2475 SCS.Dimension = DimensionICK;2476 FromType = ToType.getUnqualifiedType();2477 } else if (!S.getLangOpts().CPlusPlus &&2478 S.Context.typesAreCompatible(ToType, FromType)) {2479 // Compatible conversions (Clang extension for C function overloading)2480 SCS.Second = ICK_Compatible_Conversion;2481 FromType = ToType.getUnqualifiedType();2482 } else if (IsTransparentUnionStandardConversion(2483 S, From, ToType, InOverloadResolution, SCS, CStyle)) {2484 SCS.Second = ICK_TransparentUnionConversion;2485 FromType = ToType;2486 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,2487 CStyle)) {2488 // tryAtomicConversion has updated the standard conversion sequence2489 // appropriately.2490 return true;2491 } else if (ToType->isEventT() &&2492 From->isIntegerConstantExpr(S.getASTContext()) &&2493 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {2494 SCS.Second = ICK_Zero_Event_Conversion;2495 FromType = ToType;2496 } else if (ToType->isQueueT() &&2497 From->isIntegerConstantExpr(S.getASTContext()) &&2498 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {2499 SCS.Second = ICK_Zero_Queue_Conversion;2500 FromType = ToType;2501 } else if (ToType->isSamplerT() &&2502 From->isIntegerConstantExpr(S.getASTContext())) {2503 SCS.Second = ICK_Compatible_Conversion;2504 FromType = ToType;2505 } else if ((ToType->isFixedPointType() &&2506 FromType->isConvertibleToFixedPointType()) ||2507 (FromType->isFixedPointType() &&2508 ToType->isConvertibleToFixedPointType())) {2509 SCS.Second = ICK_Fixed_Point_Conversion;2510 FromType = ToType;2511 } else {2512 // No second conversion required.2513 SCS.Second = ICK_Identity;2514 }2515 SCS.setToType(1, FromType);2516 2517 // The third conversion can be a function pointer conversion or a2518 // qualification conversion (C++ [conv.fctptr], [conv.qual]).2519 bool ObjCLifetimeConversion;2520 if (S.TryFunctionConversion(FromType, ToType, FromType)) {2521 // Function pointer conversions (removing 'noexcept') including removal of2522 // 'noreturn' (Clang extension).2523 SCS.Third = ICK_Function_Conversion;2524 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,2525 ObjCLifetimeConversion)) {2526 SCS.Third = ICK_Qualification;2527 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;2528 FromType = ToType;2529 } else {2530 // No conversion required2531 SCS.Third = ICK_Identity;2532 }2533 2534 // C++ [over.best.ics]p6:2535 // [...] Any difference in top-level cv-qualification is2536 // subsumed by the initialization itself and does not constitute2537 // a conversion. [...]2538 QualType CanonFrom = S.Context.getCanonicalType(FromType);2539 QualType CanonTo = S.Context.getCanonicalType(ToType);2540 if (CanonFrom.getLocalUnqualifiedType()2541 == CanonTo.getLocalUnqualifiedType() &&2542 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {2543 FromType = ToType;2544 CanonFrom = CanonTo;2545 }2546 2547 SCS.setToType(2, FromType);2548 2549 if (CanonFrom == CanonTo)2550 return true;2551 2552 // If we have not converted the argument type to the parameter type,2553 // this is a bad conversion sequence, unless we're resolving an overload in C.2554 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)2555 return false;2556 2557 ExprResult ER = ExprResult{From};2558 AssignConvertType Conv =2559 S.CheckSingleAssignmentConstraints(ToType, ER,2560 /*Diagnose=*/false,2561 /*DiagnoseCFAudited=*/false,2562 /*ConvertRHS=*/false);2563 ImplicitConversionKind SecondConv;2564 switch (Conv) {2565 case AssignConvertType::Compatible:2566 case AssignConvertType::2567 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))2568 SecondConv = ICK_C_Only_Conversion;2569 break;2570 // For our purposes, discarding qualifiers is just as bad as using an2571 // incompatible pointer. Note that an IncompatiblePointer conversion can drop2572 // qualifiers, as well.2573 case AssignConvertType::CompatiblePointerDiscardsQualifiers:2574 case AssignConvertType::IncompatiblePointer:2575 case AssignConvertType::IncompatiblePointerSign:2576 SecondConv = ICK_Incompatible_Pointer_Conversion;2577 break;2578 default:2579 return false;2580 }2581 2582 // First can only be an lvalue conversion, so we pretend that this was the2583 // second conversion. First should already be valid from earlier in the2584 // function.2585 SCS.Second = SecondConv;2586 SCS.setToType(1, ToType);2587 2588 // Third is Identity, because Second should rank us worse than any other2589 // conversion. This could also be ICK_Qualification, but it's simpler to just2590 // lump everything in with the second conversion, and we don't gain anything2591 // from making this ICK_Qualification.2592 SCS.Third = ICK_Identity;2593 SCS.setToType(2, ToType);2594 return true;2595}2596 2597static bool2598IsTransparentUnionStandardConversion(Sema &S, Expr* From,2599 QualType &ToType,2600 bool InOverloadResolution,2601 StandardConversionSequence &SCS,2602 bool CStyle) {2603 2604 const RecordType *UT = ToType->getAsUnionType();2605 if (!UT)2606 return false;2607 // The field to initialize within the transparent union.2608 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();2609 if (!UD->hasAttr<TransparentUnionAttr>())2610 return false;2611 // It's compatible if the expression matches any of the fields.2612 for (const auto *it : UD->fields()) {2613 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,2614 CStyle, /*AllowObjCWritebackConversion=*/false)) {2615 ToType = it->getType();2616 return true;2617 }2618 }2619 return false;2620}2621 2622bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {2623 const BuiltinType *To = ToType->getAs<BuiltinType>();2624 // All integers are built-in.2625 if (!To) {2626 return false;2627 }2628 2629 // An rvalue of type char, signed char, unsigned char, short int, or2630 // unsigned short int can be converted to an rvalue of type int if2631 // int can represent all the values of the source type; otherwise,2632 // the source rvalue can be converted to an rvalue of type unsigned2633 // int (C++ 4.5p1).2634 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&2635 !FromType->isEnumeralType()) {2636 if ( // We can promote any signed, promotable integer type to an int2637 (FromType->isSignedIntegerType() ||2638 // We can promote any unsigned integer type whose size is2639 // less than int to an int.2640 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {2641 return To->getKind() == BuiltinType::Int;2642 }2643 2644 return To->getKind() == BuiltinType::UInt;2645 }2646 2647 // C++11 [conv.prom]p3:2648 // A prvalue of an unscoped enumeration type whose underlying type is not2649 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the2650 // following types that can represent all the values of the enumeration2651 // (i.e., the values in the range bmin to bmax as described in 7.2): int,2652 // unsigned int, long int, unsigned long int, long long int, or unsigned2653 // long long int. If none of the types in that list can represent all the2654 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration2655 // type can be converted to an rvalue a prvalue of the extended integer type2656 // with lowest integer conversion rank (4.13) greater than the rank of long2657 // long in which all the values of the enumeration can be represented. If2658 // there are two such extended types, the signed one is chosen.2659 // C++11 [conv.prom]p4:2660 // A prvalue of an unscoped enumeration type whose underlying type is fixed2661 // can be converted to a prvalue of its underlying type. Moreover, if2662 // integral promotion can be applied to its underlying type, a prvalue of an2663 // unscoped enumeration type whose underlying type is fixed can also be2664 // converted to a prvalue of the promoted underlying type.2665 if (const auto *FromED = FromType->getAsEnumDecl()) {2666 // C++0x 7.2p9: Note that this implicit enum to int conversion is not2667 // provided for a scoped enumeration.2668 if (FromED->isScoped())2669 return false;2670 2671 // We can perform an integral promotion to the underlying type of the enum,2672 // even if that's not the promoted type. Note that the check for promoting2673 // the underlying type is based on the type alone, and does not consider2674 // the bitfield-ness of the actual source expression.2675 if (FromED->isFixed()) {2676 QualType Underlying = FromED->getIntegerType();2677 return Context.hasSameUnqualifiedType(Underlying, ToType) ||2678 IsIntegralPromotion(nullptr, Underlying, ToType);2679 }2680 2681 // We have already pre-calculated the promotion type, so this is trivial.2682 if (ToType->isIntegerType() &&2683 isCompleteType(From->getBeginLoc(), FromType))2684 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());2685 2686 // C++ [conv.prom]p5:2687 // If the bit-field has an enumerated type, it is treated as any other2688 // value of that type for promotion purposes.2689 //2690 // ... so do not fall through into the bit-field checks below in C++.2691 if (getLangOpts().CPlusPlus)2692 return false;2693 }2694 2695 // C++0x [conv.prom]p2:2696 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted2697 // to an rvalue a prvalue of the first of the following types that can2698 // represent all the values of its underlying type: int, unsigned int,2699 // long int, unsigned long int, long long int, or unsigned long long int.2700 // If none of the types in that list can represent all the values of its2701 // underlying type, an rvalue a prvalue of type char16_t, char32_t,2702 // or wchar_t can be converted to an rvalue a prvalue of its underlying2703 // type.2704 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&2705 ToType->isIntegerType()) {2706 // Determine whether the type we're converting from is signed or2707 // unsigned.2708 bool FromIsSigned = FromType->isSignedIntegerType();2709 uint64_t FromSize = Context.getTypeSize(FromType);2710 2711 // The types we'll try to promote to, in the appropriate2712 // order. Try each of these types.2713 QualType PromoteTypes[6] = {2714 Context.IntTy, Context.UnsignedIntTy,2715 Context.LongTy, Context.UnsignedLongTy ,2716 Context.LongLongTy, Context.UnsignedLongLongTy2717 };2718 for (int Idx = 0; Idx < 6; ++Idx) {2719 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);2720 if (FromSize < ToSize ||2721 (FromSize == ToSize &&2722 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {2723 // We found the type that we can promote to. If this is the2724 // type we wanted, we have a promotion. Otherwise, no2725 // promotion.2726 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);2727 }2728 }2729 }2730 2731 // An rvalue for an integral bit-field (9.6) can be converted to an2732 // rvalue of type int if int can represent all the values of the2733 // bit-field; otherwise, it can be converted to unsigned int if2734 // unsigned int can represent all the values of the bit-field. If2735 // the bit-field is larger yet, no integral promotion applies to2736 // it. If the bit-field has an enumerated type, it is treated as any2737 // other value of that type for promotion purposes (C++ 4.5p3).2738 // FIXME: We should delay checking of bit-fields until we actually perform the2739 // conversion.2740 //2741 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be2742 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum2743 // bit-fields and those whose underlying type is larger than int) for GCC2744 // compatibility.2745 if (From) {2746 if (FieldDecl *MemberDecl = From->getSourceBitField()) {2747 std::optional<llvm::APSInt> BitWidth;2748 if (FromType->isIntegralType(Context) &&2749 (BitWidth =2750 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {2751 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());2752 ToSize = Context.getTypeSize(ToType);2753 2754 // Are we promoting to an int from a bitfield that fits in an int?2755 if (*BitWidth < ToSize ||2756 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {2757 return To->getKind() == BuiltinType::Int;2758 }2759 2760 // Are we promoting to an unsigned int from an unsigned bitfield2761 // that fits into an unsigned int?2762 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {2763 return To->getKind() == BuiltinType::UInt;2764 }2765 2766 return false;2767 }2768 }2769 }2770 2771 // An rvalue of type bool can be converted to an rvalue of type int,2772 // with false becoming zero and true becoming one (C++ 4.5p4).2773 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {2774 return true;2775 }2776 2777 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger2778 // integral type.2779 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&2780 ToType->isIntegerType())2781 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);2782 2783 return false;2784}2785 2786bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {2787 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())2788 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {2789 /// An rvalue of type float can be converted to an rvalue of type2790 /// double. (C++ 4.6p1).2791 if (FromBuiltin->getKind() == BuiltinType::Float &&2792 ToBuiltin->getKind() == BuiltinType::Double)2793 return true;2794 2795 // C99 6.3.1.5p1:2796 // When a float is promoted to double or long double, or a2797 // double is promoted to long double [...].2798 if (!getLangOpts().CPlusPlus &&2799 (FromBuiltin->getKind() == BuiltinType::Float ||2800 FromBuiltin->getKind() == BuiltinType::Double) &&2801 (ToBuiltin->getKind() == BuiltinType::LongDouble ||2802 ToBuiltin->getKind() == BuiltinType::Float128 ||2803 ToBuiltin->getKind() == BuiltinType::Ibm128))2804 return true;2805 2806 // In HLSL, `half` promotes to `float` or `double`, regardless of whether2807 // or not native half types are enabled.2808 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&2809 (ToBuiltin->getKind() == BuiltinType::Float ||2810 ToBuiltin->getKind() == BuiltinType::Double))2811 return true;2812 2813 // Half can be promoted to float.2814 if (!getLangOpts().NativeHalfType &&2815 FromBuiltin->getKind() == BuiltinType::Half &&2816 ToBuiltin->getKind() == BuiltinType::Float)2817 return true;2818 }2819 2820 return false;2821}2822 2823bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {2824 const ComplexType *FromComplex = FromType->getAs<ComplexType>();2825 if (!FromComplex)2826 return false;2827 2828 const ComplexType *ToComplex = ToType->getAs<ComplexType>();2829 if (!ToComplex)2830 return false;2831 2832 return IsFloatingPointPromotion(FromComplex->getElementType(),2833 ToComplex->getElementType()) ||2834 IsIntegralPromotion(nullptr, FromComplex->getElementType(),2835 ToComplex->getElementType());2836}2837 2838/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from2839/// the pointer type FromPtr to a pointer to type ToPointee, with the2840/// same type qualifiers as FromPtr has on its pointee type. ToType,2841/// if non-empty, will be a pointer to ToType that may or may not have2842/// the right set of qualifiers on its pointee.2843///2844static QualType2845BuildSimilarlyQualifiedPointerType(const Type *FromPtr,2846 QualType ToPointee, QualType ToType,2847 ASTContext &Context,2848 bool StripObjCLifetime = false) {2849 assert((FromPtr->getTypeClass() == Type::Pointer ||2850 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&2851 "Invalid similarly-qualified pointer type");2852 2853 /// Conversions to 'id' subsume cv-qualifier conversions.2854 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())2855 return ToType.getUnqualifiedType();2856 2857 QualType CanonFromPointee2858 = Context.getCanonicalType(FromPtr->getPointeeType());2859 QualType CanonToPointee = Context.getCanonicalType(ToPointee);2860 Qualifiers Quals = CanonFromPointee.getQualifiers();2861 2862 if (StripObjCLifetime)2863 Quals.removeObjCLifetime();2864 2865 // Exact qualifier match -> return the pointer type we're converting to.2866 if (CanonToPointee.getLocalQualifiers() == Quals) {2867 // ToType is exactly what we need. Return it.2868 if (!ToType.isNull())2869 return ToType.getUnqualifiedType();2870 2871 // Build a pointer to ToPointee. It has the right qualifiers2872 // already.2873 if (isa<ObjCObjectPointerType>(ToType))2874 return Context.getObjCObjectPointerType(ToPointee);2875 return Context.getPointerType(ToPointee);2876 }2877 2878 // Just build a canonical type that has the right qualifiers.2879 QualType QualifiedCanonToPointee2880 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);2881 2882 if (isa<ObjCObjectPointerType>(ToType))2883 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);2884 return Context.getPointerType(QualifiedCanonToPointee);2885}2886 2887static bool isNullPointerConstantForConversion(Expr *Expr,2888 bool InOverloadResolution,2889 ASTContext &Context) {2890 // Handle value-dependent integral null pointer constants correctly.2891 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#9032892 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&2893 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())2894 return !InOverloadResolution;2895 2896 return Expr->isNullPointerConstant(Context,2897 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull2898 : Expr::NPC_ValueDependentIsNull);2899}2900 2901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,2902 bool InOverloadResolution,2903 QualType& ConvertedType,2904 bool &IncompatibleObjC) {2905 IncompatibleObjC = false;2906 if (isObjCPointerConversion(FromType, ToType, ConvertedType,2907 IncompatibleObjC))2908 return true;2909 2910 // Conversion from a null pointer constant to any Objective-C pointer type.2911 if (ToType->isObjCObjectPointerType() &&2912 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {2913 ConvertedType = ToType;2914 return true;2915 }2916 2917 // Blocks: Block pointers can be converted to void*.2918 if (FromType->isBlockPointerType() && ToType->isPointerType() &&2919 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {2920 ConvertedType = ToType;2921 return true;2922 }2923 // Blocks: A null pointer constant can be converted to a block2924 // pointer type.2925 if (ToType->isBlockPointerType() &&2926 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {2927 ConvertedType = ToType;2928 return true;2929 }2930 2931 // If the left-hand-side is nullptr_t, the right side can be a null2932 // pointer constant.2933 if (ToType->isNullPtrType() &&2934 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {2935 ConvertedType = ToType;2936 return true;2937 }2938 2939 const PointerType* ToTypePtr = ToType->getAs<PointerType>();2940 if (!ToTypePtr)2941 return false;2942 2943 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).2944 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {2945 ConvertedType = ToType;2946 return true;2947 }2948 2949 // Beyond this point, both types need to be pointers2950 // , including objective-c pointers.2951 QualType ToPointeeType = ToTypePtr->getPointeeType();2952 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&2953 !getLangOpts().ObjCAutoRefCount) {2954 ConvertedType = BuildSimilarlyQualifiedPointerType(2955 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,2956 Context);2957 return true;2958 }2959 const PointerType *FromTypePtr = FromType->getAs<PointerType>();2960 if (!FromTypePtr)2961 return false;2962 2963 QualType FromPointeeType = FromTypePtr->getPointeeType();2964 2965 // If the unqualified pointee types are the same, this can't be a2966 // pointer conversion, so don't do all of the work below.2967 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))2968 return false;2969 2970 // An rvalue of type "pointer to cv T," where T is an object type,2971 // can be converted to an rvalue of type "pointer to cv void" (C++2972 // 4.10p2).2973 if (FromPointeeType->isIncompleteOrObjectType() &&2974 ToPointeeType->isVoidType()) {2975 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,2976 ToPointeeType,2977 ToType, Context,2978 /*StripObjCLifetime=*/true);2979 return true;2980 }2981 2982 // MSVC allows implicit function to void* type conversion.2983 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&2984 ToPointeeType->isVoidType()) {2985 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,2986 ToPointeeType,2987 ToType, Context);2988 return true;2989 }2990 2991 // When we're overloading in C, we allow a special kind of pointer2992 // conversion for compatible-but-not-identical pointee types.2993 if (!getLangOpts().CPlusPlus &&2994 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {2995 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,2996 ToPointeeType,2997 ToType, Context);2998 return true;2999 }3000 3001 // C++ [conv.ptr]p3:3002 //3003 // An rvalue of type "pointer to cv D," where D is a class type,3004 // can be converted to an rvalue of type "pointer to cv B," where3005 // B is a base class (clause 10) of D. If B is an inaccessible3006 // (clause 11) or ambiguous (10.2) base class of D, a program that3007 // necessitates this conversion is ill-formed. The result of the3008 // conversion is a pointer to the base class sub-object of the3009 // derived class object. The null pointer value is converted to3010 // the null pointer value of the destination type.3011 //3012 // Note that we do not check for ambiguity or inaccessibility3013 // here. That is handled by CheckPointerConversion.3014 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&3015 ToPointeeType->isRecordType() &&3016 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&3017 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {3018 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,3019 ToPointeeType,3020 ToType, Context);3021 return true;3022 }3023 3024 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&3025 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {3026 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,3027 ToPointeeType,3028 ToType, Context);3029 return true;3030 }3031 3032 return false;3033}3034 3035/// Adopt the given qualifiers for the given type.3036static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){3037 Qualifiers TQs = T.getQualifiers();3038 3039 // Check whether qualifiers already match.3040 if (TQs == Qs)3041 return T;3042 3043 if (Qs.compatiblyIncludes(TQs, Context))3044 return Context.getQualifiedType(T, Qs);3045 3046 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);3047}3048 3049bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,3050 QualType& ConvertedType,3051 bool &IncompatibleObjC) {3052 if (!getLangOpts().ObjC)3053 return false;3054 3055 // The set of qualifiers on the type we're converting from.3056 Qualifiers FromQualifiers = FromType.getQualifiers();3057 3058 // First, we handle all conversions on ObjC object pointer types.3059 const ObjCObjectPointerType* ToObjCPtr =3060 ToType->getAs<ObjCObjectPointerType>();3061 const ObjCObjectPointerType *FromObjCPtr =3062 FromType->getAs<ObjCObjectPointerType>();3063 3064 if (ToObjCPtr && FromObjCPtr) {3065 // If the pointee types are the same (ignoring qualifications),3066 // then this is not a pointer conversion.3067 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),3068 FromObjCPtr->getPointeeType()))3069 return false;3070 3071 // Conversion between Objective-C pointers.3072 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {3073 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();3074 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();3075 if (getLangOpts().CPlusPlus && LHS && RHS &&3076 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(3077 FromObjCPtr->getPointeeType(), getASTContext()))3078 return false;3079 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,3080 ToObjCPtr->getPointeeType(),3081 ToType, Context);3082 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);3083 return true;3084 }3085 3086 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {3087 // Okay: this is some kind of implicit downcast of Objective-C3088 // interfaces, which is permitted. However, we're going to3089 // complain about it.3090 IncompatibleObjC = true;3091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,3092 ToObjCPtr->getPointeeType(),3093 ToType, Context);3094 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);3095 return true;3096 }3097 }3098 // Beyond this point, both types need to be C pointers or block pointers.3099 QualType ToPointeeType;3100 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())3101 ToPointeeType = ToCPtr->getPointeeType();3102 else if (const BlockPointerType *ToBlockPtr =3103 ToType->getAs<BlockPointerType>()) {3104 // Objective C++: We're able to convert from a pointer to any object3105 // to a block pointer type.3106 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {3107 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);3108 return true;3109 }3110 ToPointeeType = ToBlockPtr->getPointeeType();3111 }3112 else if (FromType->getAs<BlockPointerType>() &&3113 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {3114 // Objective C++: We're able to convert from a block pointer type to a3115 // pointer to any object.3116 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);3117 return true;3118 }3119 else3120 return false;3121 3122 QualType FromPointeeType;3123 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())3124 FromPointeeType = FromCPtr->getPointeeType();3125 else if (const BlockPointerType *FromBlockPtr =3126 FromType->getAs<BlockPointerType>())3127 FromPointeeType = FromBlockPtr->getPointeeType();3128 else3129 return false;3130 3131 // If we have pointers to pointers, recursively check whether this3132 // is an Objective-C conversion.3133 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&3134 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,3135 IncompatibleObjC)) {3136 // We always complain about this conversion.3137 IncompatibleObjC = true;3138 ConvertedType = Context.getPointerType(ConvertedType);3139 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);3140 return true;3141 }3142 // Allow conversion of pointee being objective-c pointer to another one;3143 // as in I* to id.3144 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&3145 ToPointeeType->getAs<ObjCObjectPointerType>() &&3146 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,3147 IncompatibleObjC)) {3148 3149 ConvertedType = Context.getPointerType(ConvertedType);3150 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);3151 return true;3152 }3153 3154 // If we have pointers to functions or blocks, check whether the only3155 // differences in the argument and result types are in Objective-C3156 // pointer conversions. If so, we permit the conversion (but3157 // complain about it).3158 const FunctionProtoType *FromFunctionType3159 = FromPointeeType->getAs<FunctionProtoType>();3160 const FunctionProtoType *ToFunctionType3161 = ToPointeeType->getAs<FunctionProtoType>();3162 if (FromFunctionType && ToFunctionType) {3163 // If the function types are exactly the same, this isn't an3164 // Objective-C pointer conversion.3165 if (Context.getCanonicalType(FromPointeeType)3166 == Context.getCanonicalType(ToPointeeType))3167 return false;3168 3169 // Perform the quick checks that will tell us whether these3170 // function types are obviously different.3171 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||3172 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||3173 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())3174 return false;3175 3176 bool HasObjCConversion = false;3177 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==3178 Context.getCanonicalType(ToFunctionType->getReturnType())) {3179 // Okay, the types match exactly. Nothing to do.3180 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),3181 ToFunctionType->getReturnType(),3182 ConvertedType, IncompatibleObjC)) {3183 // Okay, we have an Objective-C pointer conversion.3184 HasObjCConversion = true;3185 } else {3186 // Function types are too different. Abort.3187 return false;3188 }3189 3190 // Check argument types.3191 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();3192 ArgIdx != NumArgs; ++ArgIdx) {3193 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);3194 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);3195 if (Context.getCanonicalType(FromArgType)3196 == Context.getCanonicalType(ToArgType)) {3197 // Okay, the types match exactly. Nothing to do.3198 } else if (isObjCPointerConversion(FromArgType, ToArgType,3199 ConvertedType, IncompatibleObjC)) {3200 // Okay, we have an Objective-C pointer conversion.3201 HasObjCConversion = true;3202 } else {3203 // Argument types are too different. Abort.3204 return false;3205 }3206 }3207 3208 if (HasObjCConversion) {3209 // We had an Objective-C conversion. Allow this pointer3210 // conversion, but complain about it.3211 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);3212 IncompatibleObjC = true;3213 return true;3214 }3215 }3216 3217 return false;3218}3219 3220bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,3221 QualType& ConvertedType) {3222 QualType ToPointeeType;3223 if (const BlockPointerType *ToBlockPtr =3224 ToType->getAs<BlockPointerType>())3225 ToPointeeType = ToBlockPtr->getPointeeType();3226 else3227 return false;3228 3229 QualType FromPointeeType;3230 if (const BlockPointerType *FromBlockPtr =3231 FromType->getAs<BlockPointerType>())3232 FromPointeeType = FromBlockPtr->getPointeeType();3233 else3234 return false;3235 // We have pointer to blocks, check whether the only3236 // differences in the argument and result types are in Objective-C3237 // pointer conversions. If so, we permit the conversion.3238 3239 const FunctionProtoType *FromFunctionType3240 = FromPointeeType->getAs<FunctionProtoType>();3241 const FunctionProtoType *ToFunctionType3242 = ToPointeeType->getAs<FunctionProtoType>();3243 3244 if (!FromFunctionType || !ToFunctionType)3245 return false;3246 3247 if (Context.hasSameType(FromPointeeType, ToPointeeType))3248 return true;3249 3250 // Perform the quick checks that will tell us whether these3251 // function types are obviously different.3252 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||3253 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())3254 return false;3255 3256 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();3257 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();3258 if (FromEInfo != ToEInfo)3259 return false;3260 3261 bool IncompatibleObjC = false;3262 if (Context.hasSameType(FromFunctionType->getReturnType(),3263 ToFunctionType->getReturnType())) {3264 // Okay, the types match exactly. Nothing to do.3265 } else {3266 QualType RHS = FromFunctionType->getReturnType();3267 QualType LHS = ToFunctionType->getReturnType();3268 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&3269 !RHS.hasQualifiers() && LHS.hasQualifiers())3270 LHS = LHS.getUnqualifiedType();3271 3272 if (Context.hasSameType(RHS,LHS)) {3273 // OK exact match.3274 } else if (isObjCPointerConversion(RHS, LHS,3275 ConvertedType, IncompatibleObjC)) {3276 if (IncompatibleObjC)3277 return false;3278 // Okay, we have an Objective-C pointer conversion.3279 }3280 else3281 return false;3282 }3283 3284 // Check argument types.3285 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();3286 ArgIdx != NumArgs; ++ArgIdx) {3287 IncompatibleObjC = false;3288 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);3289 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);3290 if (Context.hasSameType(FromArgType, ToArgType)) {3291 // Okay, the types match exactly. Nothing to do.3292 } else if (isObjCPointerConversion(ToArgType, FromArgType,3293 ConvertedType, IncompatibleObjC)) {3294 if (IncompatibleObjC)3295 return false;3296 // Okay, we have an Objective-C pointer conversion.3297 } else3298 // Argument types are too different. Abort.3299 return false;3300 }3301 3302 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;3303 bool CanUseToFPT, CanUseFromFPT;3304 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,3305 CanUseToFPT, CanUseFromFPT,3306 NewParamInfos))3307 return false;3308 3309 ConvertedType = ToType;3310 return true;3311}3312 3313enum {3314 ft_default,3315 ft_different_class,3316 ft_parameter_arity,3317 ft_parameter_mismatch,3318 ft_return_type,3319 ft_qualifer_mismatch,3320 ft_noexcept3321};3322 3323/// Attempts to get the FunctionProtoType from a Type. Handles3324/// MemberFunctionPointers properly.3325static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {3326 if (auto *FPT = FromType->getAs<FunctionProtoType>())3327 return FPT;3328 3329 if (auto *MPT = FromType->getAs<MemberPointerType>())3330 return MPT->getPointeeType()->getAs<FunctionProtoType>();3331 3332 return nullptr;3333}3334 3335void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,3336 QualType FromType, QualType ToType) {3337 // If either type is not valid, include no extra info.3338 if (FromType.isNull() || ToType.isNull()) {3339 PDiag << ft_default;3340 return;3341 }3342 3343 // Get the function type from the pointers.3344 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {3345 const auto *FromMember = FromType->castAs<MemberPointerType>(),3346 *ToMember = ToType->castAs<MemberPointerType>();3347 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),3348 ToMember->getMostRecentCXXRecordDecl())) {3349 PDiag << ft_different_class;3350 if (ToMember->isSugared())3351 PDiag << Context.getCanonicalTagType(3352 ToMember->getMostRecentCXXRecordDecl());3353 else3354 PDiag << ToMember->getQualifier();3355 if (FromMember->isSugared())3356 PDiag << Context.getCanonicalTagType(3357 FromMember->getMostRecentCXXRecordDecl());3358 else3359 PDiag << FromMember->getQualifier();3360 return;3361 }3362 FromType = FromMember->getPointeeType();3363 ToType = ToMember->getPointeeType();3364 }3365 3366 if (FromType->isPointerType())3367 FromType = FromType->getPointeeType();3368 if (ToType->isPointerType())3369 ToType = ToType->getPointeeType();3370 3371 // Remove references.3372 FromType = FromType.getNonReferenceType();3373 ToType = ToType.getNonReferenceType();3374 3375 // Don't print extra info for non-specialized template functions.3376 if (FromType->isInstantiationDependentType() &&3377 !FromType->getAs<TemplateSpecializationType>()) {3378 PDiag << ft_default;3379 return;3380 }3381 3382 // No extra info for same types.3383 if (Context.hasSameType(FromType, ToType)) {3384 PDiag << ft_default;3385 return;3386 }3387 3388 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),3389 *ToFunction = tryGetFunctionProtoType(ToType);3390 3391 // Both types need to be function types.3392 if (!FromFunction || !ToFunction) {3393 PDiag << ft_default;3394 return;3395 }3396 3397 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {3398 PDiag << ft_parameter_arity << ToFunction->getNumParams()3399 << FromFunction->getNumParams();3400 return;3401 }3402 3403 // Handle different parameter types.3404 unsigned ArgPos;3405 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {3406 PDiag << ft_parameter_mismatch << ArgPos + 13407 << ToFunction->getParamType(ArgPos)3408 << FromFunction->getParamType(ArgPos);3409 return;3410 }3411 3412 // Handle different return type.3413 if (!Context.hasSameType(FromFunction->getReturnType(),3414 ToFunction->getReturnType())) {3415 PDiag << ft_return_type << ToFunction->getReturnType()3416 << FromFunction->getReturnType();3417 return;3418 }3419 3420 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {3421 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()3422 << FromFunction->getMethodQuals();3423 return;3424 }3425 3426 // Handle exception specification differences on canonical type (in C++173427 // onwards).3428 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())3429 ->isNothrow() !=3430 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())3431 ->isNothrow()) {3432 PDiag << ft_noexcept;3433 return;3434 }3435 3436 // Unable to find a difference, so add no extra info.3437 PDiag << ft_default;3438}3439 3440bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,3441 ArrayRef<QualType> New, unsigned *ArgPos,3442 bool Reversed) {3443 assert(llvm::size(Old) == llvm::size(New) &&3444 "Can't compare parameters of functions with different number of "3445 "parameters!");3446 3447 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {3448 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.3449 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;3450 3451 // Ignore address spaces in pointee type. This is to disallow overloading3452 // on __ptr32/__ptr64 address spaces.3453 QualType OldType =3454 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());3455 QualType NewType =3456 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());3457 3458 if (!Context.hasSameType(OldType, NewType)) {3459 if (ArgPos)3460 *ArgPos = Idx;3461 return false;3462 }3463 }3464 return true;3465}3466 3467bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,3468 const FunctionProtoType *NewType,3469 unsigned *ArgPos, bool Reversed) {3470 return FunctionParamTypesAreEqual(OldType->param_types(),3471 NewType->param_types(), ArgPos, Reversed);3472}3473 3474bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,3475 const FunctionDecl *NewFunction,3476 unsigned *ArgPos,3477 bool Reversed) {3478 3479 if (OldFunction->getNumNonObjectParams() !=3480 NewFunction->getNumNonObjectParams())3481 return false;3482 3483 unsigned OldIgnore =3484 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());3485 unsigned NewIgnore =3486 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());3487 3488 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());3489 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());3490 3491 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),3492 NewPT->param_types().slice(NewIgnore),3493 ArgPos, Reversed);3494}3495 3496bool Sema::CheckPointerConversion(Expr *From, QualType ToType,3497 CastKind &Kind,3498 CXXCastPath& BasePath,3499 bool IgnoreBaseAccess,3500 bool Diagnose) {3501 QualType FromType = From->getType();3502 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;3503 3504 Kind = CK_BitCast;3505 3506 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&3507 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==3508 Expr::NPCK_ZeroExpression) {3509 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))3510 DiagRuntimeBehavior(From->getExprLoc(), From,3511 PDiag(diag::warn_impcast_bool_to_null_pointer)3512 << ToType << From->getSourceRange());3513 else if (!isUnevaluatedContext())3514 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)3515 << ToType << From->getSourceRange();3516 }3517 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {3518 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {3519 QualType FromPointeeType = FromPtrType->getPointeeType(),3520 ToPointeeType = ToPtrType->getPointeeType();3521 3522 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&3523 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {3524 // We must have a derived-to-base conversion. Check an3525 // ambiguous or inaccessible conversion.3526 unsigned InaccessibleID = 0;3527 unsigned AmbiguousID = 0;3528 if (Diagnose) {3529 InaccessibleID = diag::err_upcast_to_inaccessible_base;3530 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;3531 }3532 if (CheckDerivedToBaseConversion(3533 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,3534 From->getExprLoc(), From->getSourceRange(), DeclarationName(),3535 &BasePath, IgnoreBaseAccess))3536 return true;3537 3538 // The conversion was successful.3539 Kind = CK_DerivedToBase;3540 }3541 3542 if (Diagnose && !IsCStyleOrFunctionalCast &&3543 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {3544 assert(getLangOpts().MSVCCompat &&3545 "this should only be possible with MSVCCompat!");3546 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)3547 << From->getSourceRange();3548 }3549 }3550 } else if (const ObjCObjectPointerType *ToPtrType =3551 ToType->getAs<ObjCObjectPointerType>()) {3552 if (const ObjCObjectPointerType *FromPtrType =3553 FromType->getAs<ObjCObjectPointerType>()) {3554 // Objective-C++ conversions are always okay.3555 // FIXME: We should have a different class of conversions for the3556 // Objective-C++ implicit conversions.3557 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())3558 return false;3559 } else if (FromType->isBlockPointerType()) {3560 Kind = CK_BlockPointerToObjCPointerCast;3561 } else {3562 Kind = CK_CPointerToObjCPointerCast;3563 }3564 } else if (ToType->isBlockPointerType()) {3565 if (!FromType->isBlockPointerType())3566 Kind = CK_AnyPointerToBlockPointerCast;3567 }3568 3569 // We shouldn't fall into this case unless it's valid for other3570 // reasons.3571 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))3572 Kind = CK_NullToPointer;3573 3574 return false;3575}3576 3577bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,3578 QualType ToType,3579 bool InOverloadResolution,3580 QualType &ConvertedType) {3581 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();3582 if (!ToTypePtr)3583 return false;3584 3585 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)3586 if (From->isNullPointerConstant(Context,3587 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull3588 : Expr::NPC_ValueDependentIsNull)) {3589 ConvertedType = ToType;3590 return true;3591 }3592 3593 // Otherwise, both types have to be member pointers.3594 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();3595 if (!FromTypePtr)3596 return false;3597 3598 // A pointer to member of B can be converted to a pointer to member of D,3599 // where D is derived from B (C++ 4.11p2).3600 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();3601 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();3602 3603 if (!declaresSameEntity(FromClass, ToClass) &&3604 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {3605 ConvertedType = Context.getMemberPointerType(3606 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);3607 return true;3608 }3609 3610 return false;3611}3612 3613Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(3614 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,3615 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,3616 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {3617 // Lock down the inheritance model right now in MS ABI, whether or not the3618 // pointee types are the same.3619 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {3620 (void)isCompleteType(CheckLoc, FromType);3621 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));3622 }3623 3624 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();3625 if (!FromPtrType) {3626 // This must be a null pointer to member pointer conversion3627 Kind = CK_NullToMemberPointer;3628 return MemberPointerConversionResult::Success;3629 }3630 3631 // T == T, modulo cv3632 if (Direction == MemberPointerConversionDirection::Upcast &&3633 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),3634 ToPtrType->getPointeeType()))3635 return MemberPointerConversionResult::DifferentPointee;3636 3637 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),3638 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();3639 3640 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,3641 const CXXRecordDecl *Cls) {3642 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))3643 PD << Qual;3644 else3645 PD << Context.getCanonicalTagType(Cls);3646 };3647 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {3648 DiagCls(PD, FromPtrType->getQualifier(), FromClass);3649 DiagCls(PD, ToPtrType->getQualifier(), ToClass);3650 return PD;3651 };3652 3653 CXXRecordDecl *Base = FromClass, *Derived = ToClass;3654 if (Direction == MemberPointerConversionDirection::Upcast)3655 std::swap(Base, Derived);3656 3657 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,3658 /*DetectVirtual=*/true);3659 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))3660 return MemberPointerConversionResult::NotDerived;3661 3662 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {3663 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);3664 PD << int(Direction);3665 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;3666 Diag(CheckLoc, PD);3667 return MemberPointerConversionResult::Ambiguous;3668 }3669 3670 if (const RecordType *VBase = Paths.getDetectedVirtual()) {3671 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);3672 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;3673 Diag(CheckLoc, PD);3674 return MemberPointerConversionResult::Virtual;3675 }3676 3677 // Must be a base to derived member conversion.3678 BuildBasePathArray(Paths, BasePath);3679 Kind = Direction == MemberPointerConversionDirection::Upcast3680 ? CK_DerivedToBaseMemberPointer3681 : CK_BaseToDerivedMemberPointer;3682 3683 if (!IgnoreBaseAccess)3684 switch (CheckBaseClassAccess(3685 CheckLoc, Base, Derived, Paths.front(),3686 Direction == MemberPointerConversionDirection::Upcast3687 ? diag::err_upcast_to_inaccessible_base3688 : diag::err_downcast_from_inaccessible_base,3689 [&](PartialDiagnostic &PD) {3690 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),3691 DerivedQual = ToPtrType->getQualifier();3692 if (Direction == MemberPointerConversionDirection::Upcast)3693 std::swap(BaseQual, DerivedQual);3694 DiagCls(PD, DerivedQual, Derived);3695 DiagCls(PD, BaseQual, Base);3696 })) {3697 case Sema::AR_accessible:3698 case Sema::AR_delayed:3699 case Sema::AR_dependent:3700 // Optimistically assume that the delayed and dependent cases3701 // will work out.3702 break;3703 3704 case Sema::AR_inaccessible:3705 return MemberPointerConversionResult::Inaccessible;3706 }3707 3708 return MemberPointerConversionResult::Success;3709}3710 3711/// Determine whether the lifetime conversion between the two given3712/// qualifiers sets is nontrivial.3713static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,3714 Qualifiers ToQuals) {3715 // Converting anything to const __unsafe_unretained is trivial.3716 if (ToQuals.hasConst() &&3717 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)3718 return false;3719 3720 return true;3721}3722 3723/// Perform a single iteration of the loop for checking if a qualification3724/// conversion is valid.3725///3726/// Specifically, check whether any change between the qualifiers of \p3727/// FromType and \p ToType is permissible, given knowledge about whether every3728/// outer layer is const-qualified.3729static bool isQualificationConversionStep(QualType FromType, QualType ToType,3730 bool CStyle, bool IsTopLevel,3731 bool &PreviousToQualsIncludeConst,3732 bool &ObjCLifetimeConversion,3733 const ASTContext &Ctx) {3734 Qualifiers FromQuals = FromType.getQualifiers();3735 Qualifiers ToQuals = ToType.getQualifiers();3736 3737 // Ignore __unaligned qualifier.3738 FromQuals.removeUnaligned();3739 3740 // Objective-C ARC:3741 // Check Objective-C lifetime conversions.3742 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {3743 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {3744 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))3745 ObjCLifetimeConversion = true;3746 FromQuals.removeObjCLifetime();3747 ToQuals.removeObjCLifetime();3748 } else {3749 // Qualification conversions cannot cast between different3750 // Objective-C lifetime qualifiers.3751 return false;3752 }3753 }3754 3755 // Allow addition/removal of GC attributes but not changing GC attributes.3756 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&3757 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {3758 FromQuals.removeObjCGCAttr();3759 ToQuals.removeObjCGCAttr();3760 }3761 3762 // __ptrauth qualifiers must match exactly.3763 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())3764 return false;3765 3766 // -- for every j > 0, if const is in cv 1,j then const is in cv3767 // 2,j, and similarly for volatile.3768 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))3769 return false;3770 3771 // If address spaces mismatch:3772 // - in top level it is only valid to convert to addr space that is a3773 // superset in all cases apart from C-style casts where we allow3774 // conversions between overlapping address spaces.3775 // - in non-top levels it is not a valid conversion.3776 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&3777 (!IsTopLevel ||3778 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||3779 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))3780 return false;3781 3782 // -- if the cv 1,j and cv 2,j are different, then const is in3783 // every cv for 0 < k < j.3784 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&3785 !PreviousToQualsIncludeConst)3786 return false;3787 3788 // The following wording is from C++20, where the result of the conversion3789 // is T3, not T2.3790 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is3791 // "array of unknown bound of"3792 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())3793 return false;3794 3795 // -- if the resulting P3,i is different from P1,i [...], then const is3796 // added to every cv 3_k for 0 < k < i.3797 if (!CStyle && FromType->isConstantArrayType() &&3798 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)3799 return false;3800 3801 // Keep track of whether all prior cv-qualifiers in the "to" type3802 // include const.3803 PreviousToQualsIncludeConst =3804 PreviousToQualsIncludeConst && ToQuals.hasConst();3805 return true;3806}3807 3808bool3809Sema::IsQualificationConversion(QualType FromType, QualType ToType,3810 bool CStyle, bool &ObjCLifetimeConversion) {3811 FromType = Context.getCanonicalType(FromType);3812 ToType = Context.getCanonicalType(ToType);3813 ObjCLifetimeConversion = false;3814 3815 // If FromType and ToType are the same type, this is not a3816 // qualification conversion.3817 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())3818 return false;3819 3820 // (C++ 4.4p4):3821 // A conversion can add cv-qualifiers at levels other than the first3822 // in multi-level pointers, subject to the following rules: [...]3823 bool PreviousToQualsIncludeConst = true;3824 bool UnwrappedAnyPointer = false;3825 while (Context.UnwrapSimilarTypes(FromType, ToType)) {3826 if (!isQualificationConversionStep(FromType, ToType, CStyle,3827 !UnwrappedAnyPointer,3828 PreviousToQualsIncludeConst,3829 ObjCLifetimeConversion, getASTContext()))3830 return false;3831 UnwrappedAnyPointer = true;3832 }3833 3834 // We are left with FromType and ToType being the pointee types3835 // after unwrapping the original FromType and ToType the same number3836 // of times. If we unwrapped any pointers, and if FromType and3837 // ToType have the same unqualified type (since we checked3838 // qualifiers above), then this is a qualification conversion.3839 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);3840}3841 3842/// - Determine whether this is a conversion from a scalar type to an3843/// atomic type.3844///3845/// If successful, updates \c SCS's second and third steps in the conversion3846/// sequence to finish the conversion.3847static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,3848 bool InOverloadResolution,3849 StandardConversionSequence &SCS,3850 bool CStyle) {3851 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();3852 if (!ToAtomic)3853 return false;3854 3855 StandardConversionSequence InnerSCS;3856 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),3857 InOverloadResolution, InnerSCS,3858 CStyle, /*AllowObjCWritebackConversion=*/false))3859 return false;3860 3861 SCS.Second = InnerSCS.Second;3862 SCS.setToType(1, InnerSCS.getToType(1));3863 SCS.Third = InnerSCS.Third;3864 SCS.QualificationIncludesObjCLifetime3865 = InnerSCS.QualificationIncludesObjCLifetime;3866 SCS.setToType(2, InnerSCS.getToType(2));3867 return true;3868}3869 3870static bool isFirstArgumentCompatibleWithType(ASTContext &Context,3871 CXXConstructorDecl *Constructor,3872 QualType Type) {3873 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();3874 if (CtorType->getNumParams() > 0) {3875 QualType FirstArg = CtorType->getParamType(0);3876 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))3877 return true;3878 }3879 return false;3880}3881 3882static OverloadingResult3883IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,3884 CXXRecordDecl *To,3885 UserDefinedConversionSequence &User,3886 OverloadCandidateSet &CandidateSet,3887 bool AllowExplicit) {3888 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);3889 for (auto *D : S.LookupConstructors(To)) {3890 auto Info = getConstructorInfo(D);3891 if (!Info)3892 continue;3893 3894 bool Usable = !Info.Constructor->isInvalidDecl() &&3895 S.isInitListConstructor(Info.Constructor);3896 if (Usable) {3897 bool SuppressUserConversions = false;3898 if (Info.ConstructorTmpl)3899 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,3900 /*ExplicitArgs*/ nullptr, From,3901 CandidateSet, SuppressUserConversions,3902 /*PartialOverloading*/ false,3903 AllowExplicit);3904 else3905 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,3906 CandidateSet, SuppressUserConversions,3907 /*PartialOverloading*/ false, AllowExplicit);3908 }3909 }3910 3911 bool HadMultipleCandidates = (CandidateSet.size() > 1);3912 3913 OverloadCandidateSet::iterator Best;3914 switch (auto Result =3915 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {3916 case OR_Deleted:3917 case OR_Success: {3918 // Record the standard conversion we used and the conversion function.3919 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);3920 QualType ThisType = Constructor->getFunctionObjectParameterType();3921 // Initializer lists don't have conversions as such.3922 User.Before.setAsIdentityConversion();3923 User.HadMultipleCandidates = HadMultipleCandidates;3924 User.ConversionFunction = Constructor;3925 User.FoundConversionFunction = Best->FoundDecl;3926 User.After.setAsIdentityConversion();3927 User.After.setFromType(ThisType);3928 User.After.setAllToTypes(ToType);3929 return Result;3930 }3931 3932 case OR_No_Viable_Function:3933 return OR_No_Viable_Function;3934 case OR_Ambiguous:3935 return OR_Ambiguous;3936 }3937 3938 llvm_unreachable("Invalid OverloadResult!");3939}3940 3941/// Determines whether there is a user-defined conversion sequence3942/// (C++ [over.ics.user]) that converts expression From to the type3943/// ToType. If such a conversion exists, User will contain the3944/// user-defined conversion sequence that performs such a conversion3945/// and this routine will return true. Otherwise, this routine returns3946/// false and User is unspecified.3947///3948/// \param AllowExplicit true if the conversion should consider C++0x3949/// "explicit" conversion functions as well as non-explicit conversion3950/// functions (C++0x [class.conv.fct]p2).3951///3952/// \param AllowObjCConversionOnExplicit true if the conversion should3953/// allow an extra Objective-C pointer conversion on uses of explicit3954/// constructors. Requires \c AllowExplicit to also be set.3955static OverloadingResult3956IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,3957 UserDefinedConversionSequence &User,3958 OverloadCandidateSet &CandidateSet,3959 AllowedExplicit AllowExplicit,3960 bool AllowObjCConversionOnExplicit) {3961 assert(AllowExplicit != AllowedExplicit::None ||3962 !AllowObjCConversionOnExplicit);3963 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);3964 3965 // Whether we will only visit constructors.3966 bool ConstructorsOnly = false;3967 3968 // If the type we are conversion to is a class type, enumerate its3969 // constructors.3970 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {3971 // C++ [over.match.ctor]p1:3972 // When objects of class type are direct-initialized (8.5), or3973 // copy-initialized from an expression of the same or a3974 // derived class type (8.5), overload resolution selects the3975 // constructor. [...] For copy-initialization, the candidate3976 // functions are all the converting constructors (12.3.1) of3977 // that class. The argument list is the expression-list within3978 // the parentheses of the initializer.3979 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||3980 (From->getType()->isRecordType() &&3981 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))3982 ConstructorsOnly = true;3983 3984 if (!S.isCompleteType(From->getExprLoc(), ToType)) {3985 // We're not going to find any constructors.3986 } else if (auto *ToRecordDecl =3987 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {3988 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();3989 3990 Expr **Args = &From;3991 unsigned NumArgs = 1;3992 bool ListInitializing = false;3993 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {3994 // But first, see if there is an init-list-constructor that will work.3995 OverloadingResult Result = IsInitializerListConstructorConversion(3996 S, From, ToType, ToRecordDecl, User, CandidateSet,3997 AllowExplicit == AllowedExplicit::All);3998 if (Result != OR_No_Viable_Function)3999 return Result;4000 // Never mind.4001 CandidateSet.clear(4002 OverloadCandidateSet::CSK_InitByUserDefinedConversion);4003 4004 // If we're list-initializing, we pass the individual elements as4005 // arguments, not the entire list.4006 Args = InitList->getInits();4007 NumArgs = InitList->getNumInits();4008 ListInitializing = true;4009 }4010 4011 for (auto *D : S.LookupConstructors(ToRecordDecl)) {4012 auto Info = getConstructorInfo(D);4013 if (!Info)4014 continue;4015 4016 bool Usable = !Info.Constructor->isInvalidDecl();4017 if (!ListInitializing)4018 Usable = Usable && Info.Constructor->isConvertingConstructor(4019 /*AllowExplicit*/ true);4020 if (Usable) {4021 bool SuppressUserConversions = !ConstructorsOnly;4022 // C++20 [over.best.ics.general]/4.5:4023 // if the target is the first parameter of a constructor [of class4024 // X] and the constructor [...] is a candidate by [...] the second4025 // phase of [over.match.list] when the initializer list has exactly4026 // one element that is itself an initializer list, [...] and the4027 // conversion is to X or reference to cv X, user-defined conversion4028 // sequences are not considered.4029 if (SuppressUserConversions && ListInitializing) {4030 SuppressUserConversions =4031 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&4032 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,4033 ToType);4034 }4035 if (Info.ConstructorTmpl)4036 S.AddTemplateOverloadCandidate(4037 Info.ConstructorTmpl, Info.FoundDecl,4038 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),4039 CandidateSet, SuppressUserConversions,4040 /*PartialOverloading*/ false,4041 AllowExplicit == AllowedExplicit::All);4042 else4043 // Allow one user-defined conversion when user specifies a4044 // From->ToType conversion via an static cast (c-style, etc).4045 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,4046 llvm::ArrayRef(Args, NumArgs), CandidateSet,4047 SuppressUserConversions,4048 /*PartialOverloading*/ false,4049 AllowExplicit == AllowedExplicit::All);4050 }4051 }4052 }4053 }4054 4055 // Enumerate conversion functions, if we're allowed to.4056 if (ConstructorsOnly || isa<InitListExpr>(From)) {4057 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {4058 // No conversion functions from incomplete types.4059 } else if (const RecordType *FromRecordType =4060 From->getType()->getAsCanonical<RecordType>()) {4061 if (auto *FromRecordDecl =4062 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {4063 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();4064 // Add all of the conversion functions as candidates.4065 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();4066 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {4067 DeclAccessPair FoundDecl = I.getPair();4068 NamedDecl *D = FoundDecl.getDecl();4069 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());4070 if (isa<UsingShadowDecl>(D))4071 D = cast<UsingShadowDecl>(D)->getTargetDecl();4072 4073 CXXConversionDecl *Conv;4074 FunctionTemplateDecl *ConvTemplate;4075 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))4076 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());4077 else4078 Conv = cast<CXXConversionDecl>(D);4079 4080 if (ConvTemplate)4081 S.AddTemplateConversionCandidate(4082 ConvTemplate, FoundDecl, ActingContext, From, ToType,4083 CandidateSet, AllowObjCConversionOnExplicit,4084 AllowExplicit != AllowedExplicit::None);4085 else4086 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,4087 CandidateSet, AllowObjCConversionOnExplicit,4088 AllowExplicit != AllowedExplicit::None);4089 }4090 }4091 }4092 4093 bool HadMultipleCandidates = (CandidateSet.size() > 1);4094 4095 OverloadCandidateSet::iterator Best;4096 switch (auto Result =4097 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {4098 case OR_Success:4099 case OR_Deleted:4100 // Record the standard conversion we used and the conversion function.4101 if (CXXConstructorDecl *Constructor4102 = dyn_cast<CXXConstructorDecl>(Best->Function)) {4103 // C++ [over.ics.user]p1:4104 // If the user-defined conversion is specified by a4105 // constructor (12.3.1), the initial standard conversion4106 // sequence converts the source type to the type required by4107 // the argument of the constructor.4108 //4109 if (isa<InitListExpr>(From)) {4110 // Initializer lists don't have conversions as such.4111 User.Before.setAsIdentityConversion();4112 User.Before.FromBracedInitList = true;4113 } else {4114 if (Best->Conversions[0].isEllipsis())4115 User.EllipsisConversion = true;4116 else {4117 User.Before = Best->Conversions[0].Standard;4118 User.EllipsisConversion = false;4119 }4120 }4121 User.HadMultipleCandidates = HadMultipleCandidates;4122 User.ConversionFunction = Constructor;4123 User.FoundConversionFunction = Best->FoundDecl;4124 User.After.setAsIdentityConversion();4125 User.After.setFromType(Constructor->getFunctionObjectParameterType());4126 User.After.setAllToTypes(ToType);4127 return Result;4128 }4129 if (CXXConversionDecl *Conversion4130 = dyn_cast<CXXConversionDecl>(Best->Function)) {4131 4132 assert(Best->HasFinalConversion);4133 4134 // C++ [over.ics.user]p1:4135 //4136 // [...] If the user-defined conversion is specified by a4137 // conversion function (12.3.2), the initial standard4138 // conversion sequence converts the source type to the4139 // implicit object parameter of the conversion function.4140 User.Before = Best->Conversions[0].Standard;4141 User.HadMultipleCandidates = HadMultipleCandidates;4142 User.ConversionFunction = Conversion;4143 User.FoundConversionFunction = Best->FoundDecl;4144 User.EllipsisConversion = false;4145 4146 // C++ [over.ics.user]p2:4147 // The second standard conversion sequence converts the4148 // result of the user-defined conversion to the target type4149 // for the sequence. Since an implicit conversion sequence4150 // is an initialization, the special rules for4151 // initialization by user-defined conversion apply when4152 // selecting the best user-defined conversion for a4153 // user-defined conversion sequence (see 13.3.3 and4154 // 13.3.3.1).4155 User.After = Best->FinalConversion;4156 return Result;4157 }4158 llvm_unreachable("Not a constructor or conversion function?");4159 4160 case OR_No_Viable_Function:4161 return OR_No_Viable_Function;4162 4163 case OR_Ambiguous:4164 return OR_Ambiguous;4165 }4166 4167 llvm_unreachable("Invalid OverloadResult!");4168}4169 4170bool4171Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {4172 ImplicitConversionSequence ICS;4173 OverloadCandidateSet CandidateSet(From->getExprLoc(),4174 OverloadCandidateSet::CSK_Normal);4175 OverloadingResult OvResult =4176 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,4177 CandidateSet, AllowedExplicit::None, false);4178 4179 if (!(OvResult == OR_Ambiguous ||4180 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))4181 return false;4182 4183 auto Cands = CandidateSet.CompleteCandidates(4184 *this,4185 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,4186 From);4187 if (OvResult == OR_Ambiguous)4188 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)4189 << From->getType() << ToType << From->getSourceRange();4190 else { // OR_No_Viable_Function && !CandidateSet.empty()4191 if (!RequireCompleteType(From->getBeginLoc(), ToType,4192 diag::err_typecheck_nonviable_condition_incomplete,4193 From->getType(), From->getSourceRange()))4194 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)4195 << false << From->getType() << From->getSourceRange() << ToType;4196 }4197 4198 CandidateSet.NoteCandidates(4199 *this, From, Cands);4200 return true;4201}4202 4203// Helper for compareConversionFunctions that gets the FunctionType that the4204// conversion-operator return value 'points' to, or nullptr.4205static const FunctionType *4206getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {4207 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();4208 const PointerType *RetPtrTy =4209 ConvFuncTy->getReturnType()->getAs<PointerType>();4210 4211 if (!RetPtrTy)4212 return nullptr;4213 4214 return RetPtrTy->getPointeeType()->getAs<FunctionType>();4215}4216 4217/// Compare the user-defined conversion functions or constructors4218/// of two user-defined conversion sequences to determine whether any ordering4219/// is possible.4220static ImplicitConversionSequence::CompareKind4221compareConversionFunctions(Sema &S, FunctionDecl *Function1,4222 FunctionDecl *Function2) {4223 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);4224 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);4225 if (!Conv1 || !Conv2)4226 return ImplicitConversionSequence::Indistinguishable;4227 4228 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())4229 return ImplicitConversionSequence::Indistinguishable;4230 4231 // Objective-C++:4232 // If both conversion functions are implicitly-declared conversions from4233 // a lambda closure type to a function pointer and a block pointer,4234 // respectively, always prefer the conversion to a function pointer,4235 // because the function pointer is more lightweight and is more likely4236 // to keep code working.4237 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {4238 bool Block1 = Conv1->getConversionType()->isBlockPointerType();4239 bool Block2 = Conv2->getConversionType()->isBlockPointerType();4240 if (Block1 != Block2)4241 return Block1 ? ImplicitConversionSequence::Worse4242 : ImplicitConversionSequence::Better;4243 }4244 4245 // In order to support multiple calling conventions for the lambda conversion4246 // operator (such as when the free and member function calling convention is4247 // different), prefer the 'free' mechanism, followed by the calling-convention4248 // of operator(). The latter is in place to support the MSVC-like solution of4249 // defining ALL of the possible conversions in regards to calling-convention.4250 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);4251 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);4252 4253 if (Conv1FuncRet && Conv2FuncRet &&4254 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {4255 CallingConv Conv1CC = Conv1FuncRet->getCallConv();4256 CallingConv Conv2CC = Conv2FuncRet->getCallConv();4257 4258 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();4259 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();4260 4261 CallingConv CallOpCC =4262 CallOp->getType()->castAs<FunctionType>()->getCallConv();4263 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(4264 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);4265 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(4266 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);4267 4268 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};4269 for (CallingConv CC : PrefOrder) {4270 if (Conv1CC == CC)4271 return ImplicitConversionSequence::Better;4272 if (Conv2CC == CC)4273 return ImplicitConversionSequence::Worse;4274 }4275 }4276 4277 return ImplicitConversionSequence::Indistinguishable;4278}4279 4280static bool hasDeprecatedStringLiteralToCharPtrConversion(4281 const ImplicitConversionSequence &ICS) {4282 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||4283 (ICS.isUserDefined() &&4284 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);4285}4286 4287/// CompareImplicitConversionSequences - Compare two implicit4288/// conversion sequences to determine whether one is better than the4289/// other or if they are indistinguishable (C++ 13.3.3.2).4290static ImplicitConversionSequence::CompareKind4291CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,4292 const ImplicitConversionSequence& ICS1,4293 const ImplicitConversionSequence& ICS2)4294{4295 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit4296 // conversion sequences (as defined in 13.3.3.1)4297 // -- a standard conversion sequence (13.3.3.1.1) is a better4298 // conversion sequence than a user-defined conversion sequence or4299 // an ellipsis conversion sequence, and4300 // -- a user-defined conversion sequence (13.3.3.1.2) is a better4301 // conversion sequence than an ellipsis conversion sequence4302 // (13.3.3.1.3).4303 //4304 // C++0x [over.best.ics]p10:4305 // For the purpose of ranking implicit conversion sequences as4306 // described in 13.3.3.2, the ambiguous conversion sequence is4307 // treated as a user-defined sequence that is indistinguishable4308 // from any other user-defined conversion sequence.4309 4310 // String literal to 'char *' conversion has been deprecated in C++03. It has4311 // been removed from C++11. We still accept this conversion, if it happens at4312 // the best viable function. Otherwise, this conversion is considered worse4313 // than ellipsis conversion. Consider this as an extension; this is not in the4314 // standard. For example:4315 //4316 // int &f(...); // #14317 // void f(char*); // #24318 // void g() { int &r = f("foo"); }4319 //4320 // In C++03, we pick #2 as the best viable function.4321 // In C++11, we pick #1 as the best viable function, because ellipsis4322 // conversion is better than string-literal to char* conversion (since there4323 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't4324 // convert arguments, #2 would be the best viable function in C++11.4325 // If the best viable function has this conversion, a warning will be issued4326 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.4327 4328 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&4329 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=4330 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&4331 // Ill-formedness must not differ4332 ICS1.isBad() == ICS2.isBad())4333 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)4334 ? ImplicitConversionSequence::Worse4335 : ImplicitConversionSequence::Better;4336 4337 if (ICS1.getKindRank() < ICS2.getKindRank())4338 return ImplicitConversionSequence::Better;4339 if (ICS2.getKindRank() < ICS1.getKindRank())4340 return ImplicitConversionSequence::Worse;4341 4342 // The following checks require both conversion sequences to be of4343 // the same kind.4344 if (ICS1.getKind() != ICS2.getKind())4345 return ImplicitConversionSequence::Indistinguishable;4346 4347 ImplicitConversionSequence::CompareKind Result =4348 ImplicitConversionSequence::Indistinguishable;4349 4350 // Two implicit conversion sequences of the same form are4351 // indistinguishable conversion sequences unless one of the4352 // following rules apply: (C++ 13.3.3.2p3):4353 4354 // List-initialization sequence L1 is a better conversion sequence than4355 // list-initialization sequence L2 if:4356 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,4357 // if not that,4358 // — L1 and L2 convert to arrays of the same element type, and either the4359 // number of elements n_1 initialized by L1 is less than the number of4360 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to4361 // an array of unknown bound and L1 does not,4362 // even if one of the other rules in this paragraph would otherwise apply.4363 if (!ICS1.isBad()) {4364 bool StdInit1 = false, StdInit2 = false;4365 if (ICS1.hasInitializerListContainerType())4366 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),4367 nullptr);4368 if (ICS2.hasInitializerListContainerType())4369 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),4370 nullptr);4371 if (StdInit1 != StdInit2)4372 return StdInit1 ? ImplicitConversionSequence::Better4373 : ImplicitConversionSequence::Worse;4374 4375 if (ICS1.hasInitializerListContainerType() &&4376 ICS2.hasInitializerListContainerType())4377 if (auto *CAT1 = S.Context.getAsConstantArrayType(4378 ICS1.getInitializerListContainerType()))4379 if (auto *CAT2 = S.Context.getAsConstantArrayType(4380 ICS2.getInitializerListContainerType())) {4381 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),4382 CAT2->getElementType())) {4383 // Both to arrays of the same element type4384 if (CAT1->getSize() != CAT2->getSize())4385 // Different sized, the smaller wins4386 return CAT1->getSize().ult(CAT2->getSize())4387 ? ImplicitConversionSequence::Better4388 : ImplicitConversionSequence::Worse;4389 if (ICS1.isInitializerListOfIncompleteArray() !=4390 ICS2.isInitializerListOfIncompleteArray())4391 // One is incomplete, it loses4392 return ICS2.isInitializerListOfIncompleteArray()4393 ? ImplicitConversionSequence::Better4394 : ImplicitConversionSequence::Worse;4395 }4396 }4397 }4398 4399 if (ICS1.isStandard())4400 // Standard conversion sequence S1 is a better conversion sequence than4401 // standard conversion sequence S2 if [...]4402 Result = CompareStandardConversionSequences(S, Loc,4403 ICS1.Standard, ICS2.Standard);4404 else if (ICS1.isUserDefined()) {4405 // With lazy template loading, it is possible to find non-canonical4406 // FunctionDecls, depending on when redecl chains are completed. Make sure4407 // to compare the canonical decls of conversion functions. This avoids4408 // ambiguity problems for templated conversion operators.4409 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;4410 if (ConvFunc1)4411 ConvFunc1 = ConvFunc1->getCanonicalDecl();4412 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;4413 if (ConvFunc2)4414 ConvFunc2 = ConvFunc2->getCanonicalDecl();4415 // User-defined conversion sequence U1 is a better conversion4416 // sequence than another user-defined conversion sequence U2 if4417 // they contain the same user-defined conversion function or4418 // constructor and if the second standard conversion sequence of4419 // U1 is better than the second standard conversion sequence of4420 // U2 (C++ 13.3.3.2p3).4421 if (ConvFunc1 == ConvFunc2)4422 Result = CompareStandardConversionSequences(S, Loc,4423 ICS1.UserDefined.After,4424 ICS2.UserDefined.After);4425 else4426 Result = compareConversionFunctions(S,4427 ICS1.UserDefined.ConversionFunction,4428 ICS2.UserDefined.ConversionFunction);4429 }4430 4431 return Result;4432}4433 4434// Per 13.3.3.2p3, compare the given standard conversion sequences to4435// determine if one is a proper subset of the other.4436static ImplicitConversionSequence::CompareKind4437compareStandardConversionSubsets(ASTContext &Context,4438 const StandardConversionSequence& SCS1,4439 const StandardConversionSequence& SCS2) {4440 ImplicitConversionSequence::CompareKind Result4441 = ImplicitConversionSequence::Indistinguishable;4442 4443 // the identity conversion sequence is considered to be a subsequence of4444 // any non-identity conversion sequence4445 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())4446 return ImplicitConversionSequence::Better;4447 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())4448 return ImplicitConversionSequence::Worse;4449 4450 if (SCS1.Second != SCS2.Second) {4451 if (SCS1.Second == ICK_Identity)4452 Result = ImplicitConversionSequence::Better;4453 else if (SCS2.Second == ICK_Identity)4454 Result = ImplicitConversionSequence::Worse;4455 else4456 return ImplicitConversionSequence::Indistinguishable;4457 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))4458 return ImplicitConversionSequence::Indistinguishable;4459 4460 if (SCS1.Third == SCS2.Third) {4461 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result4462 : ImplicitConversionSequence::Indistinguishable;4463 }4464 4465 if (SCS1.Third == ICK_Identity)4466 return Result == ImplicitConversionSequence::Worse4467 ? ImplicitConversionSequence::Indistinguishable4468 : ImplicitConversionSequence::Better;4469 4470 if (SCS2.Third == ICK_Identity)4471 return Result == ImplicitConversionSequence::Better4472 ? ImplicitConversionSequence::Indistinguishable4473 : ImplicitConversionSequence::Worse;4474 4475 return ImplicitConversionSequence::Indistinguishable;4476}4477 4478/// Determine whether one of the given reference bindings is better4479/// than the other based on what kind of bindings they are.4480static bool4481isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,4482 const StandardConversionSequence &SCS2) {4483 // C++0x [over.ics.rank]p3b4:4484 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an4485 // implicit object parameter of a non-static member function declared4486 // without a ref-qualifier, and *either* S1 binds an rvalue reference4487 // to an rvalue and S2 binds an lvalue reference *or S1 binds an4488 // lvalue reference to a function lvalue and S2 binds an rvalue4489 // reference*.4490 //4491 // FIXME: Rvalue references. We're going rogue with the above edits,4492 // because the semantics in the current C++0x working paper (N3225 at the4493 // time of this writing) break the standard definition of std::forward4494 // and std::reference_wrapper when dealing with references to functions.4495 // Proposed wording changes submitted to CWG for consideration.4496 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||4497 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)4498 return false;4499 4500 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&4501 SCS2.IsLvalueReference) ||4502 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&4503 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);4504}4505 4506enum class FixedEnumPromotion {4507 None,4508 ToUnderlyingType,4509 ToPromotedUnderlyingType4510};4511 4512/// Returns kind of fixed enum promotion the \a SCS uses.4513static FixedEnumPromotion4514getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {4515 4516 if (SCS.Second != ICK_Integral_Promotion)4517 return FixedEnumPromotion::None;4518 4519 const auto *Enum = SCS.getFromType()->getAsEnumDecl();4520 if (!Enum)4521 return FixedEnumPromotion::None;4522 4523 if (!Enum->isFixed())4524 return FixedEnumPromotion::None;4525 4526 QualType UnderlyingType = Enum->getIntegerType();4527 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))4528 return FixedEnumPromotion::ToUnderlyingType;4529 4530 return FixedEnumPromotion::ToPromotedUnderlyingType;4531}4532 4533/// CompareStandardConversionSequences - Compare two standard4534/// conversion sequences to determine whether one is better than the4535/// other or if they are indistinguishable (C++ 13.3.3.2p3).4536static ImplicitConversionSequence::CompareKind4537CompareStandardConversionSequences(Sema &S, SourceLocation Loc,4538 const StandardConversionSequence& SCS1,4539 const StandardConversionSequence& SCS2)4540{4541 // Standard conversion sequence S1 is a better conversion sequence4542 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):4543 4544 // -- S1 is a proper subsequence of S2 (comparing the conversion4545 // sequences in the canonical form defined by 13.3.3.1.1,4546 // excluding any Lvalue Transformation; the identity conversion4547 // sequence is considered to be a subsequence of any4548 // non-identity conversion sequence) or, if not that,4549 if (ImplicitConversionSequence::CompareKind CK4550 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))4551 return CK;4552 4553 // -- the rank of S1 is better than the rank of S2 (by the rules4554 // defined below), or, if not that,4555 ImplicitConversionRank Rank1 = SCS1.getRank();4556 ImplicitConversionRank Rank2 = SCS2.getRank();4557 if (Rank1 < Rank2)4558 return ImplicitConversionSequence::Better;4559 else if (Rank2 < Rank1)4560 return ImplicitConversionSequence::Worse;4561 4562 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank4563 // are indistinguishable unless one of the following rules4564 // applies:4565 4566 // A conversion that is not a conversion of a pointer, or4567 // pointer to member, to bool is better than another conversion4568 // that is such a conversion.4569 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())4570 return SCS2.isPointerConversionToBool()4571 ? ImplicitConversionSequence::Better4572 : ImplicitConversionSequence::Worse;4573 4574 // C++14 [over.ics.rank]p4b2:4575 // This is retroactively applied to C++11 by CWG 1601.4576 //4577 // A conversion that promotes an enumeration whose underlying type is fixed4578 // to its underlying type is better than one that promotes to the promoted4579 // underlying type, if the two are different.4580 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);4581 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);4582 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&4583 FEP1 != FEP2)4584 return FEP1 == FixedEnumPromotion::ToUnderlyingType4585 ? ImplicitConversionSequence::Better4586 : ImplicitConversionSequence::Worse;4587 4588 // C++ [over.ics.rank]p4b2:4589 //4590 // If class B is derived directly or indirectly from class A,4591 // conversion of B* to A* is better than conversion of B* to4592 // void*, and conversion of A* to void* is better than conversion4593 // of B* to void*.4594 bool SCS1ConvertsToVoid4595 = SCS1.isPointerConversionToVoidPointer(S.Context);4596 bool SCS2ConvertsToVoid4597 = SCS2.isPointerConversionToVoidPointer(S.Context);4598 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {4599 // Exactly one of the conversion sequences is a conversion to4600 // a void pointer; it's the worse conversion.4601 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better4602 : ImplicitConversionSequence::Worse;4603 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {4604 // Neither conversion sequence converts to a void pointer; compare4605 // their derived-to-base conversions.4606 if (ImplicitConversionSequence::CompareKind DerivedCK4607 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))4608 return DerivedCK;4609 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&4610 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {4611 // Both conversion sequences are conversions to void4612 // pointers. Compare the source types to determine if there's an4613 // inheritance relationship in their sources.4614 QualType FromType1 = SCS1.getFromType();4615 QualType FromType2 = SCS2.getFromType();4616 4617 // Adjust the types we're converting from via the array-to-pointer4618 // conversion, if we need to.4619 if (SCS1.First == ICK_Array_To_Pointer)4620 FromType1 = S.Context.getArrayDecayedType(FromType1);4621 if (SCS2.First == ICK_Array_To_Pointer)4622 FromType2 = S.Context.getArrayDecayedType(FromType2);4623 4624 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();4625 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();4626 4627 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))4628 return ImplicitConversionSequence::Better;4629 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))4630 return ImplicitConversionSequence::Worse;4631 4632 // Objective-C++: If one interface is more specific than the4633 // other, it is the better one.4634 const ObjCObjectPointerType* FromObjCPtr14635 = FromType1->getAs<ObjCObjectPointerType>();4636 const ObjCObjectPointerType* FromObjCPtr24637 = FromType2->getAs<ObjCObjectPointerType>();4638 if (FromObjCPtr1 && FromObjCPtr2) {4639 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,4640 FromObjCPtr2);4641 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,4642 FromObjCPtr1);4643 if (AssignLeft != AssignRight) {4644 return AssignLeft? ImplicitConversionSequence::Better4645 : ImplicitConversionSequence::Worse;4646 }4647 }4648 }4649 4650 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {4651 // Check for a better reference binding based on the kind of bindings.4652 if (isBetterReferenceBindingKind(SCS1, SCS2))4653 return ImplicitConversionSequence::Better;4654 else if (isBetterReferenceBindingKind(SCS2, SCS1))4655 return ImplicitConversionSequence::Worse;4656 }4657 4658 // Compare based on qualification conversions (C++ 13.3.3.2p3,4659 // bullet 3).4660 if (ImplicitConversionSequence::CompareKind QualCK4661 = CompareQualificationConversions(S, SCS1, SCS2))4662 return QualCK;4663 4664 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {4665 // C++ [over.ics.rank]p3b4:4666 // -- S1 and S2 are reference bindings (8.5.3), and the types to4667 // which the references refer are the same type except for4668 // top-level cv-qualifiers, and the type to which the reference4669 // initialized by S2 refers is more cv-qualified than the type4670 // to which the reference initialized by S1 refers.4671 QualType T1 = SCS1.getToType(2);4672 QualType T2 = SCS2.getToType(2);4673 T1 = S.Context.getCanonicalType(T1);4674 T2 = S.Context.getCanonicalType(T2);4675 Qualifiers T1Quals, T2Quals;4676 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);4677 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);4678 if (UnqualT1 == UnqualT2) {4679 // Objective-C++ ARC: If the references refer to objects with different4680 // lifetimes, prefer bindings that don't change lifetime.4681 if (SCS1.ObjCLifetimeConversionBinding !=4682 SCS2.ObjCLifetimeConversionBinding) {4683 return SCS1.ObjCLifetimeConversionBinding4684 ? ImplicitConversionSequence::Worse4685 : ImplicitConversionSequence::Better;4686 }4687 4688 // If the type is an array type, promote the element qualifiers to the4689 // type for comparison.4690 if (isa<ArrayType>(T1) && T1Quals)4691 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);4692 if (isa<ArrayType>(T2) && T2Quals)4693 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);4694 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))4695 return ImplicitConversionSequence::Better;4696 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))4697 return ImplicitConversionSequence::Worse;4698 }4699 }4700 4701 // In Microsoft mode (below 19.28), prefer an integral conversion to a4702 // floating-to-integral conversion if the integral conversion4703 // is between types of the same size.4704 // For example:4705 // void f(float);4706 // void f(int);4707 // int main {4708 // long a;4709 // f(a);4710 // }4711 // Here, MSVC will call f(int) instead of generating a compile error4712 // as clang will do in standard mode.4713 if (S.getLangOpts().MSVCCompat &&4714 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&4715 SCS1.Second == ICK_Integral_Conversion &&4716 SCS2.Second == ICK_Floating_Integral &&4717 S.Context.getTypeSize(SCS1.getFromType()) ==4718 S.Context.getTypeSize(SCS1.getToType(2)))4719 return ImplicitConversionSequence::Better;4720 4721 // Prefer a compatible vector conversion over a lax vector conversion4722 // For example:4723 //4724 // typedef float __v4sf __attribute__((__vector_size__(16)));4725 // void f(vector float);4726 // void f(vector signed int);4727 // int main() {4728 // __v4sf a;4729 // f(a);4730 // }4731 // Here, we'd like to choose f(vector float) and not4732 // report an ambiguous call error4733 if (SCS1.Second == ICK_Vector_Conversion &&4734 SCS2.Second == ICK_Vector_Conversion) {4735 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(4736 SCS1.getFromType(), SCS1.getToType(2));4737 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(4738 SCS2.getFromType(), SCS2.getToType(2));4739 4740 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)4741 return SCS1IsCompatibleVectorConversion4742 ? ImplicitConversionSequence::Better4743 : ImplicitConversionSequence::Worse;4744 }4745 4746 if (SCS1.Second == ICK_SVE_Vector_Conversion &&4747 SCS2.Second == ICK_SVE_Vector_Conversion) {4748 bool SCS1IsCompatibleSVEVectorConversion =4749 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));4750 bool SCS2IsCompatibleSVEVectorConversion =4751 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));4752 4753 if (SCS1IsCompatibleSVEVectorConversion !=4754 SCS2IsCompatibleSVEVectorConversion)4755 return SCS1IsCompatibleSVEVectorConversion4756 ? ImplicitConversionSequence::Better4757 : ImplicitConversionSequence::Worse;4758 }4759 4760 if (SCS1.Second == ICK_RVV_Vector_Conversion &&4761 SCS2.Second == ICK_RVV_Vector_Conversion) {4762 bool SCS1IsCompatibleRVVVectorConversion =4763 S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));4764 bool SCS2IsCompatibleRVVVectorConversion =4765 S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));4766 4767 if (SCS1IsCompatibleRVVVectorConversion !=4768 SCS2IsCompatibleRVVVectorConversion)4769 return SCS1IsCompatibleRVVVectorConversion4770 ? ImplicitConversionSequence::Better4771 : ImplicitConversionSequence::Worse;4772 }4773 return ImplicitConversionSequence::Indistinguishable;4774}4775 4776/// CompareQualificationConversions - Compares two standard conversion4777/// sequences to determine whether they can be ranked based on their4778/// qualification conversions (C++ 13.3.3.2p3 bullet 3).4779static ImplicitConversionSequence::CompareKind4780CompareQualificationConversions(Sema &S,4781 const StandardConversionSequence& SCS1,4782 const StandardConversionSequence& SCS2) {4783 // C++ [over.ics.rank]p3:4784 // -- S1 and S2 differ only in their qualification conversion and4785 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]4786 // [C++98]4787 // [...] and the cv-qualification signature of type T1 is a proper subset4788 // of the cv-qualification signature of type T2, and S1 is not the4789 // deprecated string literal array-to-pointer conversion (4.2).4790 // [C++2a]4791 // [...] where T1 can be converted to T2 by a qualification conversion.4792 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||4793 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)4794 return ImplicitConversionSequence::Indistinguishable;4795 4796 // FIXME: the example in the standard doesn't use a qualification4797 // conversion (!)4798 QualType T1 = SCS1.getToType(2);4799 QualType T2 = SCS2.getToType(2);4800 T1 = S.Context.getCanonicalType(T1);4801 T2 = S.Context.getCanonicalType(T2);4802 assert(!T1->isReferenceType() && !T2->isReferenceType());4803 Qualifiers T1Quals, T2Quals;4804 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);4805 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);4806 4807 // If the types are the same, we won't learn anything by unwrapping4808 // them.4809 if (UnqualT1 == UnqualT2)4810 return ImplicitConversionSequence::Indistinguishable;4811 4812 // Don't ever prefer a standard conversion sequence that uses the deprecated4813 // string literal array to pointer conversion.4814 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;4815 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;4816 4817 // Objective-C++ ARC:4818 // Prefer qualification conversions not involving a change in lifetime4819 // to qualification conversions that do change lifetime.4820 if (SCS1.QualificationIncludesObjCLifetime &&4821 !SCS2.QualificationIncludesObjCLifetime)4822 CanPick1 = false;4823 if (SCS2.QualificationIncludesObjCLifetime &&4824 !SCS1.QualificationIncludesObjCLifetime)4825 CanPick2 = false;4826 4827 bool ObjCLifetimeConversion;4828 if (CanPick1 &&4829 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))4830 CanPick1 = false;4831 // FIXME: In Objective-C ARC, we can have qualification conversions in both4832 // directions, so we can't short-cut this second check in general.4833 if (CanPick2 &&4834 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))4835 CanPick2 = false;4836 4837 if (CanPick1 != CanPick2)4838 return CanPick1 ? ImplicitConversionSequence::Better4839 : ImplicitConversionSequence::Worse;4840 return ImplicitConversionSequence::Indistinguishable;4841}4842 4843/// CompareDerivedToBaseConversions - Compares two standard conversion4844/// sequences to determine whether they can be ranked based on their4845/// various kinds of derived-to-base conversions (C++4846/// [over.ics.rank]p4b3). As part of these checks, we also look at4847/// conversions between Objective-C interface types.4848static ImplicitConversionSequence::CompareKind4849CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,4850 const StandardConversionSequence& SCS1,4851 const StandardConversionSequence& SCS2) {4852 QualType FromType1 = SCS1.getFromType();4853 QualType ToType1 = SCS1.getToType(1);4854 QualType FromType2 = SCS2.getFromType();4855 QualType ToType2 = SCS2.getToType(1);4856 4857 // Adjust the types we're converting from via the array-to-pointer4858 // conversion, if we need to.4859 if (SCS1.First == ICK_Array_To_Pointer)4860 FromType1 = S.Context.getArrayDecayedType(FromType1);4861 if (SCS2.First == ICK_Array_To_Pointer)4862 FromType2 = S.Context.getArrayDecayedType(FromType2);4863 4864 // Canonicalize all of the types.4865 FromType1 = S.Context.getCanonicalType(FromType1);4866 ToType1 = S.Context.getCanonicalType(ToType1);4867 FromType2 = S.Context.getCanonicalType(FromType2);4868 ToType2 = S.Context.getCanonicalType(ToType2);4869 4870 // C++ [over.ics.rank]p4b3:4871 //4872 // If class B is derived directly or indirectly from class A and4873 // class C is derived directly or indirectly from B,4874 //4875 // Compare based on pointer conversions.4876 if (SCS1.Second == ICK_Pointer_Conversion &&4877 SCS2.Second == ICK_Pointer_Conversion &&4878 /*FIXME: Remove if Objective-C id conversions get their own rank*/4879 FromType1->isPointerType() && FromType2->isPointerType() &&4880 ToType1->isPointerType() && ToType2->isPointerType()) {4881 QualType FromPointee1 =4882 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();4883 QualType ToPointee1 =4884 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();4885 QualType FromPointee2 =4886 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();4887 QualType ToPointee2 =4888 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();4889 4890 // -- conversion of C* to B* is better than conversion of C* to A*,4891 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {4892 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))4893 return ImplicitConversionSequence::Better;4894 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))4895 return ImplicitConversionSequence::Worse;4896 }4897 4898 // -- conversion of B* to A* is better than conversion of C* to A*,4899 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {4900 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))4901 return ImplicitConversionSequence::Better;4902 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))4903 return ImplicitConversionSequence::Worse;4904 }4905 } else if (SCS1.Second == ICK_Pointer_Conversion &&4906 SCS2.Second == ICK_Pointer_Conversion) {4907 const ObjCObjectPointerType *FromPtr14908 = FromType1->getAs<ObjCObjectPointerType>();4909 const ObjCObjectPointerType *FromPtr24910 = FromType2->getAs<ObjCObjectPointerType>();4911 const ObjCObjectPointerType *ToPtr14912 = ToType1->getAs<ObjCObjectPointerType>();4913 const ObjCObjectPointerType *ToPtr24914 = ToType2->getAs<ObjCObjectPointerType>();4915 4916 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {4917 // Apply the same conversion ranking rules for Objective-C pointer types4918 // that we do for C++ pointers to class types. However, we employ the4919 // Objective-C pseudo-subtyping relationship used for assignment of4920 // Objective-C pointer types.4921 bool FromAssignLeft4922 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);4923 bool FromAssignRight4924 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);4925 bool ToAssignLeft4926 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);4927 bool ToAssignRight4928 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);4929 4930 // A conversion to an a non-id object pointer type or qualified 'id'4931 // type is better than a conversion to 'id'.4932 if (ToPtr1->isObjCIdType() &&4933 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))4934 return ImplicitConversionSequence::Worse;4935 if (ToPtr2->isObjCIdType() &&4936 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))4937 return ImplicitConversionSequence::Better;4938 4939 // A conversion to a non-id object pointer type is better than a4940 // conversion to a qualified 'id' type4941 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())4942 return ImplicitConversionSequence::Worse;4943 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())4944 return ImplicitConversionSequence::Better;4945 4946 // A conversion to an a non-Class object pointer type or qualified 'Class'4947 // type is better than a conversion to 'Class'.4948 if (ToPtr1->isObjCClassType() &&4949 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))4950 return ImplicitConversionSequence::Worse;4951 if (ToPtr2->isObjCClassType() &&4952 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))4953 return ImplicitConversionSequence::Better;4954 4955 // A conversion to a non-Class object pointer type is better than a4956 // conversion to a qualified 'Class' type.4957 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())4958 return ImplicitConversionSequence::Worse;4959 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())4960 return ImplicitConversionSequence::Better;4961 4962 // -- "conversion of C* to B* is better than conversion of C* to A*,"4963 if (S.Context.hasSameType(FromType1, FromType2) &&4964 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&4965 (ToAssignLeft != ToAssignRight)) {4966 if (FromPtr1->isSpecialized()) {4967 // "conversion of B<A> * to B * is better than conversion of B * to4968 // C *.4969 bool IsFirstSame =4970 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();4971 bool IsSecondSame =4972 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();4973 if (IsFirstSame) {4974 if (!IsSecondSame)4975 return ImplicitConversionSequence::Better;4976 } else if (IsSecondSame)4977 return ImplicitConversionSequence::Worse;4978 }4979 return ToAssignLeft? ImplicitConversionSequence::Worse4980 : ImplicitConversionSequence::Better;4981 }4982 4983 // -- "conversion of B* to A* is better than conversion of C* to A*,"4984 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&4985 (FromAssignLeft != FromAssignRight))4986 return FromAssignLeft? ImplicitConversionSequence::Better4987 : ImplicitConversionSequence::Worse;4988 }4989 }4990 4991 // Ranking of member-pointer types.4992 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&4993 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&4994 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {4995 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();4996 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();4997 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();4998 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();4999 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();5000 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();5001 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();5002 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();5003 // conversion of A::* to B::* is better than conversion of A::* to C::*,5004 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {5005 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))5006 return ImplicitConversionSequence::Worse;5007 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))5008 return ImplicitConversionSequence::Better;5009 }5010 // conversion of B::* to C::* is better than conversion of A::* to C::*5011 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {5012 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))5013 return ImplicitConversionSequence::Better;5014 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))5015 return ImplicitConversionSequence::Worse;5016 }5017 }5018 5019 if (SCS1.Second == ICK_Derived_To_Base) {5020 // -- conversion of C to B is better than conversion of C to A,5021 // -- binding of an expression of type C to a reference of type5022 // B& is better than binding an expression of type C to a5023 // reference of type A&,5024 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&5025 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {5026 if (S.IsDerivedFrom(Loc, ToType1, ToType2))5027 return ImplicitConversionSequence::Better;5028 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))5029 return ImplicitConversionSequence::Worse;5030 }5031 5032 // -- conversion of B to A is better than conversion of C to A.5033 // -- binding of an expression of type B to a reference of type5034 // A& is better than binding an expression of type C to a5035 // reference of type A&,5036 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&5037 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {5038 if (S.IsDerivedFrom(Loc, FromType2, FromType1))5039 return ImplicitConversionSequence::Better;5040 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))5041 return ImplicitConversionSequence::Worse;5042 }5043 }5044 5045 return ImplicitConversionSequence::Indistinguishable;5046}5047 5048static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {5049 if (!T.getQualifiers().hasUnaligned())5050 return T;5051 5052 Qualifiers Q;5053 T = Ctx.getUnqualifiedArrayType(T, Q);5054 Q.removeUnaligned();5055 return Ctx.getQualifiedType(T, Q);5056}5057 5058Sema::ReferenceCompareResult5059Sema::CompareReferenceRelationship(SourceLocation Loc,5060 QualType OrigT1, QualType OrigT2,5061 ReferenceConversions *ConvOut) {5062 assert(!OrigT1->isReferenceType() &&5063 "T1 must be the pointee type of the reference type");5064 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");5065 5066 QualType T1 = Context.getCanonicalType(OrigT1);5067 QualType T2 = Context.getCanonicalType(OrigT2);5068 Qualifiers T1Quals, T2Quals;5069 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);5070 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);5071 5072 ReferenceConversions ConvTmp;5073 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;5074 Conv = ReferenceConversions();5075 5076 // C++2a [dcl.init.ref]p4:5077 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is5078 // reference-related to "cv2 T2" if T1 is similar to T2, or5079 // T1 is a base class of T2.5080 // "cv1 T1" is reference-compatible with "cv2 T2" if5081 // a prvalue of type "pointer to cv2 T2" can be converted to the type5082 // "pointer to cv1 T1" via a standard conversion sequence.5083 5084 // Check for standard conversions we can apply to pointers: derived-to-base5085 // conversions, ObjC pointer conversions, and function pointer conversions.5086 // (Qualification conversions are checked last.)5087 if (UnqualT1 == UnqualT2) {5088 // Nothing to do.5089 } else if (isCompleteType(Loc, OrigT2) &&5090 IsDerivedFrom(Loc, UnqualT2, UnqualT1))5091 Conv |= ReferenceConversions::DerivedToBase;5092 else if (UnqualT1->isObjCObjectOrInterfaceType() &&5093 UnqualT2->isObjCObjectOrInterfaceType() &&5094 Context.canBindObjCObjectType(UnqualT1, UnqualT2))5095 Conv |= ReferenceConversions::ObjC;5096 else if (UnqualT2->isFunctionType() &&5097 IsFunctionConversion(UnqualT2, UnqualT1)) {5098 Conv |= ReferenceConversions::Function;5099 // No need to check qualifiers; function types don't have them.5100 return Ref_Compatible;5101 }5102 bool ConvertedReferent = Conv != 0;5103 5104 // We can have a qualification conversion. Compute whether the types are5105 // similar at the same time.5106 bool PreviousToQualsIncludeConst = true;5107 bool TopLevel = true;5108 do {5109 if (T1 == T2)5110 break;5111 5112 // We will need a qualification conversion.5113 Conv |= ReferenceConversions::Qualification;5114 5115 // Track whether we performed a qualification conversion anywhere other5116 // than the top level. This matters for ranking reference bindings in5117 // overload resolution.5118 if (!TopLevel)5119 Conv |= ReferenceConversions::NestedQualification;5120 5121 // MS compiler ignores __unaligned qualifier for references; do the same.5122 T1 = withoutUnaligned(Context, T1);5123 T2 = withoutUnaligned(Context, T2);5124 5125 // If we find a qualifier mismatch, the types are not reference-compatible,5126 // but are still be reference-related if they're similar.5127 bool ObjCLifetimeConversion = false;5128 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,5129 PreviousToQualsIncludeConst,5130 ObjCLifetimeConversion, getASTContext()))5131 return (ConvertedReferent || Context.hasSimilarType(T1, T2))5132 ? Ref_Related5133 : Ref_Incompatible;5134 5135 // FIXME: Should we track this for any level other than the first?5136 if (ObjCLifetimeConversion)5137 Conv |= ReferenceConversions::ObjCLifetime;5138 5139 TopLevel = false;5140 } while (Context.UnwrapSimilarTypes(T1, T2));5141 5142 // At this point, if the types are reference-related, we must either have the5143 // same inner type (ignoring qualifiers), or must have already worked out how5144 // to convert the referent.5145 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))5146 ? Ref_Compatible5147 : Ref_Incompatible;5148}5149 5150/// Look for a user-defined conversion to a value reference-compatible5151/// with DeclType. Return true if something definite is found.5152static bool5153FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,5154 QualType DeclType, SourceLocation DeclLoc,5155 Expr *Init, QualType T2, bool AllowRvalues,5156 bool AllowExplicit) {5157 assert(T2->isRecordType() && "Can only find conversions of record types.");5158 auto *T2RecordDecl = T2->castAsCXXRecordDecl();5159 OverloadCandidateSet CandidateSet(5160 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);5161 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();5162 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {5163 NamedDecl *D = *I;5164 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());5165 if (isa<UsingShadowDecl>(D))5166 D = cast<UsingShadowDecl>(D)->getTargetDecl();5167 5168 FunctionTemplateDecl *ConvTemplate5169 = dyn_cast<FunctionTemplateDecl>(D);5170 CXXConversionDecl *Conv;5171 if (ConvTemplate)5172 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());5173 else5174 Conv = cast<CXXConversionDecl>(D);5175 5176 if (AllowRvalues) {5177 // If we are initializing an rvalue reference, don't permit conversion5178 // functions that return lvalues.5179 if (!ConvTemplate && DeclType->isRValueReferenceType()) {5180 const ReferenceType *RefType5181 = Conv->getConversionType()->getAs<LValueReferenceType>();5182 if (RefType && !RefType->getPointeeType()->isFunctionType())5183 continue;5184 }5185 5186 if (!ConvTemplate &&5187 S.CompareReferenceRelationship(5188 DeclLoc,5189 Conv->getConversionType()5190 .getNonReferenceType()5191 .getUnqualifiedType(),5192 DeclType.getNonReferenceType().getUnqualifiedType()) ==5193 Sema::Ref_Incompatible)5194 continue;5195 } else {5196 // If the conversion function doesn't return a reference type,5197 // it can't be considered for this conversion. An rvalue reference5198 // is only acceptable if its referencee is a function type.5199 5200 const ReferenceType *RefType =5201 Conv->getConversionType()->getAs<ReferenceType>();5202 if (!RefType ||5203 (!RefType->isLValueReferenceType() &&5204 !RefType->getPointeeType()->isFunctionType()))5205 continue;5206 }5207 5208 if (ConvTemplate)5209 S.AddTemplateConversionCandidate(5210 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,5211 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);5212 else5213 S.AddConversionCandidate(5214 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,5215 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);5216 }5217 5218 bool HadMultipleCandidates = (CandidateSet.size() > 1);5219 5220 OverloadCandidateSet::iterator Best;5221 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {5222 case OR_Success:5223 5224 assert(Best->HasFinalConversion);5225 5226 // C++ [over.ics.ref]p1:5227 //5228 // [...] If the parameter binds directly to the result of5229 // applying a conversion function to the argument5230 // expression, the implicit conversion sequence is a5231 // user-defined conversion sequence (13.3.3.1.2), with the5232 // second standard conversion sequence either an identity5233 // conversion or, if the conversion function returns an5234 // entity of a type that is a derived class of the parameter5235 // type, a derived-to-base Conversion.5236 if (!Best->FinalConversion.DirectBinding)5237 return false;5238 5239 ICS.setUserDefined();5240 ICS.UserDefined.Before = Best->Conversions[0].Standard;5241 ICS.UserDefined.After = Best->FinalConversion;5242 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;5243 ICS.UserDefined.ConversionFunction = Best->Function;5244 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;5245 ICS.UserDefined.EllipsisConversion = false;5246 assert(ICS.UserDefined.After.ReferenceBinding &&5247 ICS.UserDefined.After.DirectBinding &&5248 "Expected a direct reference binding!");5249 return true;5250 5251 case OR_Ambiguous:5252 ICS.setAmbiguous();5253 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();5254 Cand != CandidateSet.end(); ++Cand)5255 if (Cand->Best)5256 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);5257 return true;5258 5259 case OR_No_Viable_Function:5260 case OR_Deleted:5261 // There was no suitable conversion, or we found a deleted5262 // conversion; continue with other checks.5263 return false;5264 }5265 5266 llvm_unreachable("Invalid OverloadResult!");5267}5268 5269/// Compute an implicit conversion sequence for reference5270/// initialization.5271static ImplicitConversionSequence5272TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,5273 SourceLocation DeclLoc,5274 bool SuppressUserConversions,5275 bool AllowExplicit) {5276 assert(DeclType->isReferenceType() && "Reference init needs a reference");5277 5278 // Most paths end in a failed conversion.5279 ImplicitConversionSequence ICS;5280 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);5281 5282 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();5283 QualType T2 = Init->getType();5284 5285 // If the initializer is the address of an overloaded function, try5286 // to resolve the overloaded function. If all goes well, T2 is the5287 // type of the resulting function.5288 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {5289 DeclAccessPair Found;5290 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,5291 false, Found))5292 T2 = Fn->getType();5293 }5294 5295 // Compute some basic properties of the types and the initializer.5296 bool isRValRef = DeclType->isRValueReferenceType();5297 Expr::Classification InitCategory = Init->Classify(S.Context);5298 5299 Sema::ReferenceConversions RefConv;5300 Sema::ReferenceCompareResult RefRelationship =5301 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);5302 5303 auto SetAsReferenceBinding = [&](bool BindsDirectly) {5304 ICS.setStandard();5305 ICS.Standard.First = ICK_Identity;5306 // FIXME: A reference binding can be a function conversion too. We should5307 // consider that when ordering reference-to-function bindings.5308 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)5309 ? ICK_Derived_To_Base5310 : (RefConv & Sema::ReferenceConversions::ObjC)5311 ? ICK_Compatible_Conversion5312 : ICK_Identity;5313 ICS.Standard.Dimension = ICK_Identity;5314 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank5315 // a reference binding that performs a non-top-level qualification5316 // conversion as a qualification conversion, not as an identity conversion.5317 ICS.Standard.Third = (RefConv &5318 Sema::ReferenceConversions::NestedQualification)5319 ? ICK_Qualification5320 : ICK_Identity;5321 ICS.Standard.setFromType(T2);5322 ICS.Standard.setToType(0, T2);5323 ICS.Standard.setToType(1, T1);5324 ICS.Standard.setToType(2, T1);5325 ICS.Standard.ReferenceBinding = true;5326 ICS.Standard.DirectBinding = BindsDirectly;5327 ICS.Standard.IsLvalueReference = !isRValRef;5328 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();5329 ICS.Standard.BindsToRvalue = InitCategory.isRValue();5330 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;5331 ICS.Standard.ObjCLifetimeConversionBinding =5332 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;5333 ICS.Standard.FromBracedInitList = false;5334 ICS.Standard.CopyConstructor = nullptr;5335 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;5336 };5337 5338 // C++0x [dcl.init.ref]p5:5339 // A reference to type "cv1 T1" is initialized by an expression5340 // of type "cv2 T2" as follows:5341 5342 // -- If reference is an lvalue reference and the initializer expression5343 if (!isRValRef) {5344 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is5345 // reference-compatible with "cv2 T2," or5346 //5347 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.5348 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {5349 // C++ [over.ics.ref]p1:5350 // When a parameter of reference type binds directly (8.5.3)5351 // to an argument expression, the implicit conversion sequence5352 // is the identity conversion, unless the argument expression5353 // has a type that is a derived class of the parameter type,5354 // in which case the implicit conversion sequence is a5355 // derived-to-base Conversion (13.3.3.1).5356 SetAsReferenceBinding(/*BindsDirectly=*/true);5357 5358 // Nothing more to do: the inaccessibility/ambiguity check for5359 // derived-to-base conversions is suppressed when we're5360 // computing the implicit conversion sequence (C++5361 // [over.best.ics]p2).5362 return ICS;5363 }5364 5365 // -- has a class type (i.e., T2 is a class type), where T1 is5366 // not reference-related to T2, and can be implicitly5367 // converted to an lvalue of type "cv3 T3," where "cv1 T1"5368 // is reference-compatible with "cv3 T3" 92) (this5369 // conversion is selected by enumerating the applicable5370 // conversion functions (13.3.1.6) and choosing the best5371 // one through overload resolution (13.3)),5372 if (!SuppressUserConversions && T2->isRecordType() &&5373 S.isCompleteType(DeclLoc, T2) &&5374 RefRelationship == Sema::Ref_Incompatible) {5375 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,5376 Init, T2, /*AllowRvalues=*/false,5377 AllowExplicit))5378 return ICS;5379 }5380 }5381 5382 // -- Otherwise, the reference shall be an lvalue reference to a5383 // non-volatile const type (i.e., cv1 shall be const), or the reference5384 // shall be an rvalue reference.5385 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {5386 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)5387 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);5388 return ICS;5389 }5390 5391 // -- If the initializer expression5392 //5393 // -- is an xvalue, class prvalue, array prvalue or function5394 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or5395 if (RefRelationship == Sema::Ref_Compatible &&5396 (InitCategory.isXValue() ||5397 (InitCategory.isPRValue() &&5398 (T2->isRecordType() || T2->isArrayType())) ||5399 (InitCategory.isLValue() && T2->isFunctionType()))) {5400 // In C++11, this is always a direct binding. In C++98/03, it's a direct5401 // binding unless we're binding to a class prvalue.5402 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we5403 // allow the use of rvalue references in C++98/03 for the benefit of5404 // standard library implementors; therefore, we need the xvalue check here.5405 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||5406 !(InitCategory.isPRValue() || T2->isRecordType()));5407 return ICS;5408 }5409 5410 // -- has a class type (i.e., T2 is a class type), where T1 is not5411 // reference-related to T2, and can be implicitly converted to5412 // an xvalue, class prvalue, or function lvalue of type5413 // "cv3 T3", where "cv1 T1" is reference-compatible with5414 // "cv3 T3",5415 //5416 // then the reference is bound to the value of the initializer5417 // expression in the first case and to the result of the conversion5418 // in the second case (or, in either case, to an appropriate base5419 // class subobject).5420 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&5421 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&5422 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,5423 Init, T2, /*AllowRvalues=*/true,5424 AllowExplicit)) {5425 // In the second case, if the reference is an rvalue reference5426 // and the second standard conversion sequence of the5427 // user-defined conversion sequence includes an lvalue-to-rvalue5428 // conversion, the program is ill-formed.5429 if (ICS.isUserDefined() && isRValRef &&5430 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)5431 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);5432 5433 return ICS;5434 }5435 5436 // A temporary of function type cannot be created; don't even try.5437 if (T1->isFunctionType())5438 return ICS;5439 5440 // -- Otherwise, a temporary of type "cv1 T1" is created and5441 // initialized from the initializer expression using the5442 // rules for a non-reference copy initialization (8.5). The5443 // reference is then bound to the temporary. If T1 is5444 // reference-related to T2, cv1 must be the same5445 // cv-qualification as, or greater cv-qualification than,5446 // cv2; otherwise, the program is ill-formed.5447 if (RefRelationship == Sema::Ref_Related) {5448 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then5449 // we would be reference-compatible or reference-compatible with5450 // added qualification. But that wasn't the case, so the reference5451 // initialization fails.5452 //5453 // Note that we only want to check address spaces and cvr-qualifiers here.5454 // ObjC GC, lifetime and unaligned qualifiers aren't important.5455 Qualifiers T1Quals = T1.getQualifiers();5456 Qualifiers T2Quals = T2.getQualifiers();5457 T1Quals.removeObjCGCAttr();5458 T1Quals.removeObjCLifetime();5459 T2Quals.removeObjCGCAttr();5460 T2Quals.removeObjCLifetime();5461 // MS compiler ignores __unaligned qualifier for references; do the same.5462 T1Quals.removeUnaligned();5463 T2Quals.removeUnaligned();5464 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))5465 return ICS;5466 }5467 5468 // If at least one of the types is a class type, the types are not5469 // related, and we aren't allowed any user conversions, the5470 // reference binding fails. This case is important for breaking5471 // recursion, since TryImplicitConversion below will attempt to5472 // create a temporary through the use of a copy constructor.5473 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&5474 (T1->isRecordType() || T2->isRecordType()))5475 return ICS;5476 5477 // If T1 is reference-related to T2 and the reference is an rvalue5478 // reference, the initializer expression shall not be an lvalue.5479 if (RefRelationship >= Sema::Ref_Related && isRValRef &&5480 Init->Classify(S.Context).isLValue()) {5481 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);5482 return ICS;5483 }5484 5485 // C++ [over.ics.ref]p2:5486 // When a parameter of reference type is not bound directly to5487 // an argument expression, the conversion sequence is the one5488 // required to convert the argument expression to the5489 // underlying type of the reference according to5490 // 13.3.3.1. Conceptually, this conversion sequence corresponds5491 // to copy-initializing a temporary of the underlying type with5492 // the argument expression. Any difference in top-level5493 // cv-qualification is subsumed by the initialization itself5494 // and does not constitute a conversion.5495 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,5496 AllowedExplicit::None,5497 /*InOverloadResolution=*/false,5498 /*CStyle=*/false,5499 /*AllowObjCWritebackConversion=*/false,5500 /*AllowObjCConversionOnExplicit=*/false);5501 5502 // Of course, that's still a reference binding.5503 if (ICS.isStandard()) {5504 ICS.Standard.ReferenceBinding = true;5505 ICS.Standard.IsLvalueReference = !isRValRef;5506 ICS.Standard.BindsToFunctionLvalue = false;5507 ICS.Standard.BindsToRvalue = true;5508 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;5509 ICS.Standard.ObjCLifetimeConversionBinding = false;5510 } else if (ICS.isUserDefined()) {5511 const ReferenceType *LValRefType =5512 ICS.UserDefined.ConversionFunction->getReturnType()5513 ->getAs<LValueReferenceType>();5514 5515 // C++ [over.ics.ref]p3:5516 // Except for an implicit object parameter, for which see 13.3.1, a5517 // standard conversion sequence cannot be formed if it requires [...]5518 // binding an rvalue reference to an lvalue other than a function5519 // lvalue.5520 // Note that the function case is not possible here.5521 if (isRValRef && LValRefType) {5522 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);5523 return ICS;5524 }5525 5526 ICS.UserDefined.After.ReferenceBinding = true;5527 ICS.UserDefined.After.IsLvalueReference = !isRValRef;5528 ICS.UserDefined.After.BindsToFunctionLvalue = false;5529 ICS.UserDefined.After.BindsToRvalue = !LValRefType;5530 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;5531 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;5532 ICS.UserDefined.After.FromBracedInitList = false;5533 }5534 5535 return ICS;5536}5537 5538static ImplicitConversionSequence5539TryCopyInitialization(Sema &S, Expr *From, QualType ToType,5540 bool SuppressUserConversions,5541 bool InOverloadResolution,5542 bool AllowObjCWritebackConversion,5543 bool AllowExplicit = false);5544 5545/// TryListConversion - Try to copy-initialize a value of type ToType from the5546/// initializer list From.5547static ImplicitConversionSequence5548TryListConversion(Sema &S, InitListExpr *From, QualType ToType,5549 bool SuppressUserConversions,5550 bool InOverloadResolution,5551 bool AllowObjCWritebackConversion) {5552 // C++11 [over.ics.list]p1:5553 // When an argument is an initializer list, it is not an expression and5554 // special rules apply for converting it to a parameter type.5555 5556 ImplicitConversionSequence Result;5557 Result.setBad(BadConversionSequence::no_conversion, From, ToType);5558 5559 // We need a complete type for what follows. With one C++20 exception,5560 // incomplete types can never be initialized from init lists.5561 QualType InitTy = ToType;5562 const ArrayType *AT = S.Context.getAsArrayType(ToType);5563 if (AT && S.getLangOpts().CPlusPlus20)5564 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))5565 // C++20 allows list initialization of an incomplete array type.5566 InitTy = IAT->getElementType();5567 if (!S.isCompleteType(From->getBeginLoc(), InitTy))5568 return Result;5569 5570 // C++20 [over.ics.list]/2:5571 // If the initializer list is a designated-initializer-list, a conversion5572 // is only possible if the parameter has an aggregate type5573 //5574 // FIXME: The exception for reference initialization here is not part of the5575 // language rules, but follow other compilers in adding it as a tentative DR5576 // resolution.5577 bool IsDesignatedInit = From->hasDesignatedInit();5578 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&5579 IsDesignatedInit)5580 return Result;5581 5582 // Per DR1467 and DR2137:5583 // If the parameter type is an aggregate class X and the initializer list5584 // has a single element of type cv U, where U is X or a class derived from5585 // X, the implicit conversion sequence is the one required to convert the5586 // element to the parameter type.5587 //5588 // Otherwise, if the parameter type is a character array [... ]5589 // and the initializer list has a single element that is an5590 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the5591 // implicit conversion sequence is the identity conversion.5592 if (From->getNumInits() == 1 && !IsDesignatedInit) {5593 if (ToType->isRecordType() && ToType->isAggregateType()) {5594 QualType InitType = From->getInit(0)->getType();5595 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||5596 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))5597 return TryCopyInitialization(S, From->getInit(0), ToType,5598 SuppressUserConversions,5599 InOverloadResolution,5600 AllowObjCWritebackConversion);5601 }5602 5603 if (AT && S.IsStringInit(From->getInit(0), AT)) {5604 InitializedEntity Entity =5605 InitializedEntity::InitializeParameter(S.Context, ToType,5606 /*Consumed=*/false);5607 if (S.CanPerformCopyInitialization(Entity, From)) {5608 Result.setStandard();5609 Result.Standard.setAsIdentityConversion();5610 Result.Standard.setFromType(ToType);5611 Result.Standard.setAllToTypes(ToType);5612 return Result;5613 }5614 }5615 }5616 5617 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).5618 // C++11 [over.ics.list]p2:5619 // If the parameter type is std::initializer_list<X> or "array of X" and5620 // all the elements can be implicitly converted to X, the implicit5621 // conversion sequence is the worst conversion necessary to convert an5622 // element of the list to X.5623 //5624 // C++14 [over.ics.list]p3:5625 // Otherwise, if the parameter type is "array of N X", if the initializer5626 // list has exactly N elements or if it has fewer than N elements and X is5627 // default-constructible, and if all the elements of the initializer list5628 // can be implicitly converted to X, the implicit conversion sequence is5629 // the worst conversion necessary to convert an element of the list to X.5630 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {5631 unsigned e = From->getNumInits();5632 ImplicitConversionSequence DfltElt;5633 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),5634 QualType());5635 QualType ContTy = ToType;5636 bool IsUnbounded = false;5637 if (AT) {5638 InitTy = AT->getElementType();5639 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {5640 if (CT->getSize().ult(e)) {5641 // Too many inits, fatally bad5642 Result.setBad(BadConversionSequence::too_many_initializers, From,5643 ToType);5644 Result.setInitializerListContainerType(ContTy, IsUnbounded);5645 return Result;5646 }5647 if (CT->getSize().ugt(e)) {5648 // Need an init from empty {}, is there one?5649 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},5650 From->getEndLoc());5651 EmptyList.setType(S.Context.VoidTy);5652 DfltElt = TryListConversion(5653 S, &EmptyList, InitTy, SuppressUserConversions,5654 InOverloadResolution, AllowObjCWritebackConversion);5655 if (DfltElt.isBad()) {5656 // No {} init, fatally bad5657 Result.setBad(BadConversionSequence::too_few_initializers, From,5658 ToType);5659 Result.setInitializerListContainerType(ContTy, IsUnbounded);5660 return Result;5661 }5662 }5663 } else {5664 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");5665 IsUnbounded = true;5666 if (!e) {5667 // Cannot convert to zero-sized.5668 Result.setBad(BadConversionSequence::too_few_initializers, From,5669 ToType);5670 Result.setInitializerListContainerType(ContTy, IsUnbounded);5671 return Result;5672 }5673 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);5674 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,5675 ArraySizeModifier::Normal, 0);5676 }5677 }5678 5679 Result.setStandard();5680 Result.Standard.setAsIdentityConversion();5681 Result.Standard.setFromType(InitTy);5682 Result.Standard.setAllToTypes(InitTy);5683 for (unsigned i = 0; i < e; ++i) {5684 Expr *Init = From->getInit(i);5685 ImplicitConversionSequence ICS = TryCopyInitialization(5686 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,5687 AllowObjCWritebackConversion);5688 5689 // Keep the worse conversion seen so far.5690 // FIXME: Sequences are not totally ordered, so 'worse' can be5691 // ambiguous. CWG has been informed.5692 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,5693 Result) ==5694 ImplicitConversionSequence::Worse) {5695 Result = ICS;5696 // Bail as soon as we find something unconvertible.5697 if (Result.isBad()) {5698 Result.setInitializerListContainerType(ContTy, IsUnbounded);5699 return Result;5700 }5701 }5702 }5703 5704 // If we needed any implicit {} initialization, compare that now.5705 // over.ics.list/6 indicates we should compare that conversion. Again CWG5706 // has been informed that this might not be the best thing.5707 if (!DfltElt.isBad() && CompareImplicitConversionSequences(5708 S, From->getEndLoc(), DfltElt, Result) ==5709 ImplicitConversionSequence::Worse)5710 Result = DfltElt;5711 // Record the type being initialized so that we may compare sequences5712 Result.setInitializerListContainerType(ContTy, IsUnbounded);5713 return Result;5714 }5715 5716 // C++14 [over.ics.list]p4:5717 // C++11 [over.ics.list]p3:5718 // Otherwise, if the parameter is a non-aggregate class X and overload5719 // resolution chooses a single best constructor [...] the implicit5720 // conversion sequence is a user-defined conversion sequence. If multiple5721 // constructors are viable but none is better than the others, the5722 // implicit conversion sequence is a user-defined conversion sequence.5723 if (ToType->isRecordType() && !ToType->isAggregateType()) {5724 // This function can deal with initializer lists.5725 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,5726 AllowedExplicit::None,5727 InOverloadResolution, /*CStyle=*/false,5728 AllowObjCWritebackConversion,5729 /*AllowObjCConversionOnExplicit=*/false);5730 }5731 5732 // C++14 [over.ics.list]p5:5733 // C++11 [over.ics.list]p4:5734 // Otherwise, if the parameter has an aggregate type which can be5735 // initialized from the initializer list [...] the implicit conversion5736 // sequence is a user-defined conversion sequence.5737 if (ToType->isAggregateType()) {5738 // Type is an aggregate, argument is an init list. At this point it comes5739 // down to checking whether the initialization works.5740 // FIXME: Find out whether this parameter is consumed or not.5741 InitializedEntity Entity =5742 InitializedEntity::InitializeParameter(S.Context, ToType,5743 /*Consumed=*/false);5744 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,5745 From)) {5746 Result.setUserDefined();5747 Result.UserDefined.Before.setAsIdentityConversion();5748 // Initializer lists don't have a type.5749 Result.UserDefined.Before.setFromType(QualType());5750 Result.UserDefined.Before.setAllToTypes(QualType());5751 5752 Result.UserDefined.After.setAsIdentityConversion();5753 Result.UserDefined.After.setFromType(ToType);5754 Result.UserDefined.After.setAllToTypes(ToType);5755 Result.UserDefined.ConversionFunction = nullptr;5756 }5757 return Result;5758 }5759 5760 // C++14 [over.ics.list]p6:5761 // C++11 [over.ics.list]p5:5762 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.5763 if (ToType->isReferenceType()) {5764 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't5765 // mention initializer lists in any way. So we go by what list-5766 // initialization would do and try to extrapolate from that.5767 5768 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();5769 5770 // If the initializer list has a single element that is reference-related5771 // to the parameter type, we initialize the reference from that.5772 if (From->getNumInits() == 1 && !IsDesignatedInit) {5773 Expr *Init = From->getInit(0);5774 5775 QualType T2 = Init->getType();5776 5777 // If the initializer is the address of an overloaded function, try5778 // to resolve the overloaded function. If all goes well, T2 is the5779 // type of the resulting function.5780 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {5781 DeclAccessPair Found;5782 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(5783 Init, ToType, false, Found))5784 T2 = Fn->getType();5785 }5786 5787 // Compute some basic properties of the types and the initializer.5788 Sema::ReferenceCompareResult RefRelationship =5789 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);5790 5791 if (RefRelationship >= Sema::Ref_Related) {5792 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),5793 SuppressUserConversions,5794 /*AllowExplicit=*/false);5795 }5796 }5797 5798 // Otherwise, we bind the reference to a temporary created from the5799 // initializer list.5800 Result = TryListConversion(S, From, T1, SuppressUserConversions,5801 InOverloadResolution,5802 AllowObjCWritebackConversion);5803 if (Result.isFailure())5804 return Result;5805 assert(!Result.isEllipsis() &&5806 "Sub-initialization cannot result in ellipsis conversion.");5807 5808 // Can we even bind to a temporary?5809 if (ToType->isRValueReferenceType() ||5810 (T1.isConstQualified() && !T1.isVolatileQualified())) {5811 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :5812 Result.UserDefined.After;5813 SCS.ReferenceBinding = true;5814 SCS.IsLvalueReference = ToType->isLValueReferenceType();5815 SCS.BindsToRvalue = true;5816 SCS.BindsToFunctionLvalue = false;5817 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;5818 SCS.ObjCLifetimeConversionBinding = false;5819 SCS.FromBracedInitList = false;5820 5821 } else5822 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,5823 From, ToType);5824 return Result;5825 }5826 5827 // C++14 [over.ics.list]p7:5828 // C++11 [over.ics.list]p6:5829 // Otherwise, if the parameter type is not a class:5830 if (!ToType->isRecordType()) {5831 // - if the initializer list has one element that is not itself an5832 // initializer list, the implicit conversion sequence is the one5833 // required to convert the element to the parameter type.5834 // Bail out on EmbedExpr as well since we never create EmbedExpr for a5835 // single integer.5836 unsigned NumInits = From->getNumInits();5837 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&5838 !isa<EmbedExpr>(From->getInit(0))) {5839 Result = TryCopyInitialization(5840 S, From->getInit(0), ToType, SuppressUserConversions,5841 InOverloadResolution, AllowObjCWritebackConversion);5842 if (Result.isStandard())5843 Result.Standard.FromBracedInitList = true;5844 }5845 // - if the initializer list has no elements, the implicit conversion5846 // sequence is the identity conversion.5847 else if (NumInits == 0) {5848 Result.setStandard();5849 Result.Standard.setAsIdentityConversion();5850 Result.Standard.setFromType(ToType);5851 Result.Standard.setAllToTypes(ToType);5852 }5853 return Result;5854 }5855 5856 // C++14 [over.ics.list]p8:5857 // C++11 [over.ics.list]p7:5858 // In all cases other than those enumerated above, no conversion is possible5859 return Result;5860}5861 5862/// TryCopyInitialization - Try to copy-initialize a value of type5863/// ToType from the expression From. Return the implicit conversion5864/// sequence required to pass this argument, which may be a bad5865/// conversion sequence (meaning that the argument cannot be passed to5866/// a parameter of this type). If @p SuppressUserConversions, then we5867/// do not permit any user-defined conversion sequences.5868static ImplicitConversionSequence5869TryCopyInitialization(Sema &S, Expr *From, QualType ToType,5870 bool SuppressUserConversions,5871 bool InOverloadResolution,5872 bool AllowObjCWritebackConversion,5873 bool AllowExplicit) {5874 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))5875 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,5876 InOverloadResolution,AllowObjCWritebackConversion);5877 5878 if (ToType->isReferenceType())5879 return TryReferenceInit(S, From, ToType,5880 /*FIXME:*/ From->getBeginLoc(),5881 SuppressUserConversions, AllowExplicit);5882 5883 return TryImplicitConversion(S, From, ToType,5884 SuppressUserConversions,5885 AllowedExplicit::None,5886 InOverloadResolution,5887 /*CStyle=*/false,5888 AllowObjCWritebackConversion,5889 /*AllowObjCConversionOnExplicit=*/false);5890}5891 5892static bool TryCopyInitialization(const CanQualType FromQTy,5893 const CanQualType ToQTy,5894 Sema &S,5895 SourceLocation Loc,5896 ExprValueKind FromVK) {5897 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);5898 ImplicitConversionSequence ICS =5899 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);5900 5901 return !ICS.isBad();5902}5903 5904/// TryObjectArgumentInitialization - Try to initialize the object5905/// parameter of the given member function (@c Method) from the5906/// expression @p From.5907static ImplicitConversionSequence TryObjectArgumentInitialization(5908 Sema &S, SourceLocation Loc, QualType FromType,5909 Expr::Classification FromClassification, CXXMethodDecl *Method,5910 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,5911 QualType ExplicitParameterType = QualType(),5912 bool SuppressUserConversion = false) {5913 5914 // We need to have an object of class type.5915 if (const auto *PT = FromType->getAs<PointerType>()) {5916 FromType = PT->getPointeeType();5917 5918 // When we had a pointer, it's implicitly dereferenced, so we5919 // better have an lvalue.5920 assert(FromClassification.isLValue());5921 }5922 5923 auto ValueKindFromClassification = [](Expr::Classification C) {5924 if (C.isPRValue())5925 return clang::VK_PRValue;5926 if (C.isXValue())5927 return VK_XValue;5928 return clang::VK_LValue;5929 };5930 5931 if (Method->isExplicitObjectMemberFunction()) {5932 if (ExplicitParameterType.isNull())5933 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();5934 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),5935 ValueKindFromClassification(FromClassification));5936 ImplicitConversionSequence ICS = TryCopyInitialization(5937 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,5938 /*InOverloadResolution=*/true, false);5939 if (ICS.isBad())5940 ICS.Bad.FromExpr = nullptr;5941 return ICS;5942 }5943 5944 assert(FromType->isRecordType());5945 5946 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);5947 // C++98 [class.dtor]p2:5948 // A destructor can be invoked for a const, volatile or const volatile5949 // object.5950 // C++98 [over.match.funcs]p4:5951 // For static member functions, the implicit object parameter is considered5952 // to match any object (since if the function is selected, the object is5953 // discarded).5954 Qualifiers Quals = Method->getMethodQualifiers();5955 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {5956 Quals.addConst();5957 Quals.addVolatile();5958 }5959 5960 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);5961 5962 // Set up the conversion sequence as a "bad" conversion, to allow us5963 // to exit early.5964 ImplicitConversionSequence ICS;5965 5966 // C++0x [over.match.funcs]p4:5967 // For non-static member functions, the type of the implicit object5968 // parameter is5969 //5970 // - "lvalue reference to cv X" for functions declared without a5971 // ref-qualifier or with the & ref-qualifier5972 // - "rvalue reference to cv X" for functions declared with the &&5973 // ref-qualifier5974 //5975 // where X is the class of which the function is a member and cv is the5976 // cv-qualification on the member function declaration.5977 //5978 // However, when finding an implicit conversion sequence for the argument, we5979 // are not allowed to perform user-defined conversions5980 // (C++ [over.match.funcs]p5). We perform a simplified version of5981 // reference binding here, that allows class rvalues to bind to5982 // non-constant references.5983 5984 // First check the qualifiers.5985 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);5986 // MSVC ignores __unaligned qualifier for overload candidates; do the same.5987 if (ImplicitParamType.getCVRQualifiers() !=5988 FromTypeCanon.getLocalCVRQualifiers() &&5989 !ImplicitParamType.isAtLeastAsQualifiedAs(5990 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {5991 ICS.setBad(BadConversionSequence::bad_qualifiers,5992 FromType, ImplicitParamType);5993 return ICS;5994 }5995 5996 if (FromTypeCanon.hasAddressSpace()) {5997 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();5998 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();5999 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,6000 S.getASTContext())) {6001 ICS.setBad(BadConversionSequence::bad_qualifiers,6002 FromType, ImplicitParamType);6003 return ICS;6004 }6005 }6006 6007 // Check that we have either the same type or a derived type. It6008 // affects the conversion rank.6009 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);6010 ImplicitConversionKind SecondKind;6011 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {6012 SecondKind = ICK_Identity;6013 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {6014 SecondKind = ICK_Derived_To_Base;6015 } else if (!Method->isExplicitObjectMemberFunction()) {6016 ICS.setBad(BadConversionSequence::unrelated_class,6017 FromType, ImplicitParamType);6018 return ICS;6019 }6020 6021 // Check the ref-qualifier.6022 switch (Method->getRefQualifier()) {6023 case RQ_None:6024 // Do nothing; we don't care about lvalueness or rvalueness.6025 break;6026 6027 case RQ_LValue:6028 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {6029 // non-const lvalue reference cannot bind to an rvalue6030 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,6031 ImplicitParamType);6032 return ICS;6033 }6034 break;6035 6036 case RQ_RValue:6037 if (!FromClassification.isRValue()) {6038 // rvalue reference cannot bind to an lvalue6039 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,6040 ImplicitParamType);6041 return ICS;6042 }6043 break;6044 }6045 6046 // Success. Mark this as a reference binding.6047 ICS.setStandard();6048 ICS.Standard.setAsIdentityConversion();6049 ICS.Standard.Second = SecondKind;6050 ICS.Standard.setFromType(FromType);6051 ICS.Standard.setAllToTypes(ImplicitParamType);6052 ICS.Standard.ReferenceBinding = true;6053 ICS.Standard.DirectBinding = true;6054 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;6055 ICS.Standard.BindsToFunctionLvalue = false;6056 ICS.Standard.BindsToRvalue = FromClassification.isRValue();6057 ICS.Standard.FromBracedInitList = false;6058 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier6059 = (Method->getRefQualifier() == RQ_None);6060 return ICS;6061}6062 6063/// PerformObjectArgumentInitialization - Perform initialization of6064/// the implicit object parameter for the given Method with the given6065/// expression.6066ExprResult Sema::PerformImplicitObjectArgumentInitialization(6067 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,6068 CXXMethodDecl *Method) {6069 QualType FromRecordType, DestType;6070 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();6071 6072 Expr::Classification FromClassification;6073 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {6074 FromRecordType = PT->getPointeeType();6075 DestType = Method->getThisType();6076 FromClassification = Expr::Classification::makeSimpleLValue();6077 } else {6078 FromRecordType = From->getType();6079 DestType = ImplicitParamRecordType;6080 FromClassification = From->Classify(Context);6081 6082 // CWG2813 [expr.call]p6:6083 // If the function is an implicit object member function, the object6084 // expression of the class member access shall be a glvalue [...]6085 if (From->isPRValue()) {6086 From = CreateMaterializeTemporaryExpr(FromRecordType, From,6087 Method->getRefQualifier() !=6088 RefQualifierKind::RQ_RValue);6089 }6090 }6091 6092 // Note that we always use the true parent context when performing6093 // the actual argument initialization.6094 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(6095 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,6096 Method->getParent());6097 if (ICS.isBad()) {6098 switch (ICS.Bad.Kind) {6099 case BadConversionSequence::bad_qualifiers: {6100 Qualifiers FromQs = FromRecordType.getQualifiers();6101 Qualifiers ToQs = DestType.getQualifiers();6102 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();6103 if (CVR) {6104 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)6105 << Method->getDeclName() << FromRecordType << (CVR - 1)6106 << From->getSourceRange();6107 Diag(Method->getLocation(), diag::note_previous_decl)6108 << Method->getDeclName();6109 return ExprError();6110 }6111 break;6112 }6113 6114 case BadConversionSequence::lvalue_ref_to_rvalue:6115 case BadConversionSequence::rvalue_ref_to_lvalue: {6116 bool IsRValueQualified =6117 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;6118 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)6119 << Method->getDeclName() << FromClassification.isRValue()6120 << IsRValueQualified;6121 Diag(Method->getLocation(), diag::note_previous_decl)6122 << Method->getDeclName();6123 return ExprError();6124 }6125 6126 case BadConversionSequence::no_conversion:6127 case BadConversionSequence::unrelated_class:6128 break;6129 6130 case BadConversionSequence::too_few_initializers:6131 case BadConversionSequence::too_many_initializers:6132 llvm_unreachable("Lists are not objects");6133 }6134 6135 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)6136 << ImplicitParamRecordType << FromRecordType6137 << From->getSourceRange();6138 }6139 6140 if (ICS.Standard.Second == ICK_Derived_To_Base) {6141 ExprResult FromRes =6142 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);6143 if (FromRes.isInvalid())6144 return ExprError();6145 From = FromRes.get();6146 }6147 6148 if (!Context.hasSameType(From->getType(), DestType)) {6149 CastKind CK;6150 QualType PteeTy = DestType->getPointeeType();6151 LangAS DestAS =6152 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();6153 if (FromRecordType.getAddressSpace() != DestAS)6154 CK = CK_AddressSpaceConversion;6155 else6156 CK = CK_NoOp;6157 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();6158 }6159 return From;6160}6161 6162/// TryContextuallyConvertToBool - Attempt to contextually convert the6163/// expression From to bool (C++0x [conv]p3).6164static ImplicitConversionSequence6165TryContextuallyConvertToBool(Sema &S, Expr *From) {6166 // C++ [dcl.init]/17.8:6167 // - Otherwise, if the initialization is direct-initialization, the source6168 // type is std::nullptr_t, and the destination type is bool, the initial6169 // value of the object being initialized is false.6170 if (From->getType()->isNullPtrType())6171 return ImplicitConversionSequence::getNullptrToBool(From->getType(),6172 S.Context.BoolTy,6173 From->isGLValue());6174 6175 // All other direct-initialization of bool is equivalent to an implicit6176 // conversion to bool in which explicit conversions are permitted.6177 return TryImplicitConversion(S, From, S.Context.BoolTy,6178 /*SuppressUserConversions=*/false,6179 AllowedExplicit::Conversions,6180 /*InOverloadResolution=*/false,6181 /*CStyle=*/false,6182 /*AllowObjCWritebackConversion=*/false,6183 /*AllowObjCConversionOnExplicit=*/false);6184}6185 6186ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {6187 if (checkPlaceholderForOverload(*this, From))6188 return ExprError();6189 6190 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);6191 if (!ICS.isBad())6192 return PerformImplicitConversion(From, Context.BoolTy, ICS,6193 AssignmentAction::Converting);6194 6195 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))6196 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)6197 << From->getType() << From->getSourceRange();6198 return ExprError();6199}6200 6201/// Check that the specified conversion is permitted in a converted constant6202/// expression, according to C++11 [expr.const]p3. Return true if the conversion6203/// is acceptable.6204static bool CheckConvertedConstantConversions(Sema &S,6205 StandardConversionSequence &SCS) {6206 // Since we know that the target type is an integral or unscoped enumeration6207 // type, most conversion kinds are impossible. All possible First and Third6208 // conversions are fine.6209 switch (SCS.Second) {6210 case ICK_Identity:6211 case ICK_Integral_Promotion:6212 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.6213 case ICK_Zero_Queue_Conversion:6214 return true;6215 6216 case ICK_Boolean_Conversion:6217 // Conversion from an integral or unscoped enumeration type to bool is6218 // classified as ICK_Boolean_Conversion, but it's also arguably an integral6219 // conversion, so we allow it in a converted constant expression.6220 //6221 // FIXME: Per core issue 1407, we should not allow this, but that breaks6222 // a lot of popular code. We should at least add a warning for this6223 // (non-conforming) extension.6224 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&6225 SCS.getToType(2)->isBooleanType();6226 6227 case ICK_Pointer_Conversion:6228 case ICK_Pointer_Member:6229 // C++1z: null pointer conversions and null member pointer conversions are6230 // only permitted if the source type is std::nullptr_t.6231 return SCS.getFromType()->isNullPtrType();6232 6233 case ICK_Floating_Promotion:6234 case ICK_Complex_Promotion:6235 case ICK_Floating_Conversion:6236 case ICK_Complex_Conversion:6237 case ICK_Floating_Integral:6238 case ICK_Compatible_Conversion:6239 case ICK_Derived_To_Base:6240 case ICK_Vector_Conversion:6241 case ICK_SVE_Vector_Conversion:6242 case ICK_RVV_Vector_Conversion:6243 case ICK_HLSL_Vector_Splat:6244 case ICK_Vector_Splat:6245 case ICK_Complex_Real:6246 case ICK_Block_Pointer_Conversion:6247 case ICK_TransparentUnionConversion:6248 case ICK_Writeback_Conversion:6249 case ICK_Zero_Event_Conversion:6250 case ICK_C_Only_Conversion:6251 case ICK_Incompatible_Pointer_Conversion:6252 case ICK_Fixed_Point_Conversion:6253 case ICK_HLSL_Vector_Truncation:6254 return false;6255 6256 case ICK_Lvalue_To_Rvalue:6257 case ICK_Array_To_Pointer:6258 case ICK_Function_To_Pointer:6259 case ICK_HLSL_Array_RValue:6260 llvm_unreachable("found a first conversion kind in Second");6261 6262 case ICK_Function_Conversion:6263 case ICK_Qualification:6264 llvm_unreachable("found a third conversion kind in Second");6265 6266 case ICK_Num_Conversion_Kinds:6267 break;6268 }6269 6270 llvm_unreachable("unknown conversion kind");6271}6272 6273/// BuildConvertedConstantExpression - Check that the expression From is a6274/// converted constant expression of type T, perform the conversion but6275/// does not evaluate the expression6276static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,6277 QualType T, CCEKind CCE,6278 NamedDecl *Dest,6279 APValue &PreNarrowingValue) {6280 [[maybe_unused]] bool isCCEAllowedPreCXX11 =6281 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool);6282 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&6283 "converted constant expression outside C++11 or TTP matching");6284 6285 if (checkPlaceholderForOverload(S, From))6286 return ExprError();6287 6288 // C++1z [expr.const]p3:6289 // A converted constant expression of type T is an expression,6290 // implicitly converted to type T, where the converted6291 // expression is a constant expression and the implicit conversion6292 // sequence contains only [... list of conversions ...].6293 ImplicitConversionSequence ICS =6294 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)6295 ? TryContextuallyConvertToBool(S, From)6296 : TryCopyInitialization(S, From, T,6297 /*SuppressUserConversions=*/false,6298 /*InOverloadResolution=*/false,6299 /*AllowObjCWritebackConversion=*/false,6300 /*AllowExplicit=*/false);6301 StandardConversionSequence *SCS = nullptr;6302 switch (ICS.getKind()) {6303 case ImplicitConversionSequence::StandardConversion:6304 SCS = &ICS.Standard;6305 break;6306 case ImplicitConversionSequence::UserDefinedConversion:6307 if (T->isRecordType())6308 SCS = &ICS.UserDefined.Before;6309 else6310 SCS = &ICS.UserDefined.After;6311 break;6312 case ImplicitConversionSequence::AmbiguousConversion:6313 case ImplicitConversionSequence::BadConversion:6314 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))6315 return S.Diag(From->getBeginLoc(),6316 diag::err_typecheck_converted_constant_expression)6317 << From->getType() << From->getSourceRange() << T;6318 return ExprError();6319 6320 case ImplicitConversionSequence::EllipsisConversion:6321 case ImplicitConversionSequence::StaticObjectArgumentConversion:6322 llvm_unreachable("bad conversion in converted constant expression");6323 }6324 6325 // Check that we would only use permitted conversions.6326 if (!CheckConvertedConstantConversions(S, *SCS)) {6327 return S.Diag(From->getBeginLoc(),6328 diag::err_typecheck_converted_constant_expression_disallowed)6329 << From->getType() << From->getSourceRange() << T;6330 }6331 // [...] and where the reference binding (if any) binds directly.6332 if (SCS->ReferenceBinding && !SCS->DirectBinding) {6333 return S.Diag(From->getBeginLoc(),6334 diag::err_typecheck_converted_constant_expression_indirect)6335 << From->getType() << From->getSourceRange() << T;6336 }6337 // 'TryCopyInitialization' returns incorrect info for attempts to bind6338 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,6339 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not6340 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this6341 // case explicitly.6342 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {6343 return S.Diag(From->getBeginLoc(),6344 diag::err_reference_bind_to_bitfield_in_cce)6345 << From->getSourceRange();6346 }6347 6348 // Usually we can simply apply the ImplicitConversionSequence we formed6349 // earlier, but that's not guaranteed to work when initializing an object of6350 // class type.6351 ExprResult Result;6352 bool IsTemplateArgument =6353 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;6354 if (T->isRecordType()) {6355 assert(IsTemplateArgument &&6356 "unexpected class type converted constant expr");6357 Result = S.PerformCopyInitialization(6358 InitializedEntity::InitializeTemplateParameter(6359 T, cast<NonTypeTemplateParmDecl>(Dest)),6360 SourceLocation(), From);6361 } else {6362 Result =6363 S.PerformImplicitConversion(From, T, ICS, AssignmentAction::Converting);6364 }6365 if (Result.isInvalid())6366 return Result;6367 6368 // C++2a [intro.execution]p5:6369 // A full-expression is [...] a constant-expression [...]6370 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),6371 /*DiscardedValue=*/false, /*IsConstexpr=*/true,6372 IsTemplateArgument);6373 if (Result.isInvalid())6374 return Result;6375 6376 // Check for a narrowing implicit conversion.6377 bool ReturnPreNarrowingValue = false;6378 QualType PreNarrowingType;6379 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,6380 PreNarrowingType)) {6381 case NK_Variable_Narrowing:6382 // Implicit conversion to a narrower type, and the value is not a constant6383 // expression. We'll diagnose this in a moment.6384 case NK_Not_Narrowing:6385 break;6386 6387 case NK_Constant_Narrowing:6388 if (CCE == CCEKind::ArrayBound &&6389 PreNarrowingType->isIntegralOrEnumerationType() &&6390 PreNarrowingValue.isInt()) {6391 // Don't diagnose array bound narrowing here; we produce more precise6392 // errors by allowing the un-narrowed value through.6393 ReturnPreNarrowingValue = true;6394 break;6395 }6396 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)6397 << CCE << /*Constant*/ 16398 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;6399 break;6400 6401 case NK_Dependent_Narrowing:6402 // Implicit conversion to a narrower type, but the expression is6403 // value-dependent so we can't tell whether it's actually narrowing.6404 // For matching the parameters of a TTP, the conversion is ill-formed6405 // if it may narrow.6406 if (CCE != CCEKind::TempArgStrict)6407 break;6408 [[fallthrough]];6409 case NK_Type_Narrowing:6410 // FIXME: It would be better to diagnose that the expression is not a6411 // constant expression.6412 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)6413 << CCE << /*Constant*/ 0 << From->getType() << T;6414 break;6415 }6416 if (!ReturnPreNarrowingValue)6417 PreNarrowingValue = {};6418 6419 return Result;6420}6421 6422/// CheckConvertedConstantExpression - Check that the expression From is a6423/// converted constant expression of type T, perform the conversion and produce6424/// the converted expression, per C++11 [expr.const]p3.6425static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,6426 QualType T, APValue &Value,6427 CCEKind CCE, bool RequireInt,6428 NamedDecl *Dest) {6429 6430 APValue PreNarrowingValue;6431 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,6432 PreNarrowingValue);6433 if (Result.isInvalid() || Result.get()->isValueDependent()) {6434 Value = APValue();6435 return Result;6436 }6437 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,6438 RequireInt, PreNarrowingValue);6439}6440 6441ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,6442 CCEKind CCE,6443 NamedDecl *Dest) {6444 APValue PreNarrowingValue;6445 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,6446 PreNarrowingValue);6447}6448 6449ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,6450 APValue &Value, CCEKind CCE,6451 NamedDecl *Dest) {6452 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,6453 Dest);6454}6455 6456ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,6457 llvm::APSInt &Value,6458 CCEKind CCE) {6459 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");6460 6461 APValue V;6462 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,6463 /*Dest=*/nullptr);6464 if (!R.isInvalid() && !R.get()->isValueDependent())6465 Value = V.getInt();6466 return R;6467}6468 6469ExprResult6470Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,6471 CCEKind CCE, bool RequireInt,6472 const APValue &PreNarrowingValue) {6473 6474 ExprResult Result = E;6475 // Check the expression is a constant expression.6476 SmallVector<PartialDiagnosticAt, 8> Notes;6477 Expr::EvalResult Eval;6478 Eval.Diag = &Notes;6479 6480 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");6481 6482 ConstantExprKind Kind;6483 if (CCE == CCEKind::TemplateArg && T->isRecordType())6484 Kind = ConstantExprKind::ClassTemplateArgument;6485 else if (CCE == CCEKind::TemplateArg)6486 Kind = ConstantExprKind::NonClassTemplateArgument;6487 else6488 Kind = ConstantExprKind::Normal;6489 6490 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||6491 (RequireInt && !Eval.Val.isInt())) {6492 // The expression can't be folded, so we can't keep it at this position in6493 // the AST.6494 Result = ExprError();6495 } else {6496 Value = Eval.Val;6497 6498 if (Notes.empty()) {6499 // It's a constant expression.6500 Expr *E = Result.get();6501 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {6502 // We expect a ConstantExpr to have a value associated with it6503 // by this point.6504 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&6505 "ConstantExpr has no value associated with it");6506 (void)CE;6507 } else {6508 E = ConstantExpr::Create(Context, Result.get(), Value);6509 }6510 if (!PreNarrowingValue.isAbsent())6511 Value = std::move(PreNarrowingValue);6512 return E;6513 }6514 }6515 6516 // It's not a constant expression. Produce an appropriate diagnostic.6517 if (Notes.size() == 1 &&6518 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {6519 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;6520 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==6521 diag::note_constexpr_invalid_template_arg) {6522 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);6523 for (unsigned I = 0; I < Notes.size(); ++I)6524 Diag(Notes[I].first, Notes[I].second);6525 } else {6526 Diag(E->getBeginLoc(), diag::err_expr_not_cce)6527 << CCE << E->getSourceRange();6528 for (unsigned I = 0; I < Notes.size(); ++I)6529 Diag(Notes[I].first, Notes[I].second);6530 }6531 return ExprError();6532}6533 6534/// dropPointerConversions - If the given standard conversion sequence6535/// involves any pointer conversions, remove them. This may change6536/// the result type of the conversion sequence.6537static void dropPointerConversion(StandardConversionSequence &SCS) {6538 if (SCS.Second == ICK_Pointer_Conversion) {6539 SCS.Second = ICK_Identity;6540 SCS.Dimension = ICK_Identity;6541 SCS.Third = ICK_Identity;6542 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];6543 }6544}6545 6546/// TryContextuallyConvertToObjCPointer - Attempt to contextually6547/// convert the expression From to an Objective-C pointer type.6548static ImplicitConversionSequence6549TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {6550 // Do an implicit conversion to 'id'.6551 QualType Ty = S.Context.getObjCIdType();6552 ImplicitConversionSequence ICS6553 = TryImplicitConversion(S, From, Ty,6554 // FIXME: Are these flags correct?6555 /*SuppressUserConversions=*/false,6556 AllowedExplicit::Conversions,6557 /*InOverloadResolution=*/false,6558 /*CStyle=*/false,6559 /*AllowObjCWritebackConversion=*/false,6560 /*AllowObjCConversionOnExplicit=*/true);6561 6562 // Strip off any final conversions to 'id'.6563 switch (ICS.getKind()) {6564 case ImplicitConversionSequence::BadConversion:6565 case ImplicitConversionSequence::AmbiguousConversion:6566 case ImplicitConversionSequence::EllipsisConversion:6567 case ImplicitConversionSequence::StaticObjectArgumentConversion:6568 break;6569 6570 case ImplicitConversionSequence::UserDefinedConversion:6571 dropPointerConversion(ICS.UserDefined.After);6572 break;6573 6574 case ImplicitConversionSequence::StandardConversion:6575 dropPointerConversion(ICS.Standard);6576 break;6577 }6578 6579 return ICS;6580}6581 6582ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {6583 if (checkPlaceholderForOverload(*this, From))6584 return ExprError();6585 6586 QualType Ty = Context.getObjCIdType();6587 ImplicitConversionSequence ICS =6588 TryContextuallyConvertToObjCPointer(*this, From);6589 if (!ICS.isBad())6590 return PerformImplicitConversion(From, Ty, ICS,6591 AssignmentAction::Converting);6592 return ExprResult();6593}6594 6595static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {6596 const Expr *Base = nullptr;6597 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&6598 "expected a member expression");6599 6600 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);6601 M && !M->isImplicitAccess())6602 Base = M->getBase();6603 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);6604 M && !M->isImplicitAccess())6605 Base = M->getBase();6606 6607 QualType T = Base ? Base->getType() : S.getCurrentThisType();6608 6609 if (T->isPointerType())6610 T = T->getPointeeType();6611 6612 return T;6613}6614 6615static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,6616 const FunctionDecl *Fun) {6617 QualType ObjType = Obj->getType();6618 if (ObjType->isPointerType()) {6619 ObjType = ObjType->getPointeeType();6620 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,6621 VK_LValue, OK_Ordinary, SourceLocation(),6622 /*CanOverflow=*/false, FPOptionsOverride());6623 }6624 return Obj;6625}6626 6627ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,6628 FunctionDecl *Fun) {6629 Obj = GetExplicitObjectExpr(S, Obj, Fun);6630 return S.PerformCopyInitialization(6631 InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)),6632 Obj->getExprLoc(), Obj);6633}6634 6635static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,6636 Expr *Object, MultiExprArg &Args,6637 SmallVectorImpl<Expr *> &NewArgs) {6638 assert(Method->isExplicitObjectMemberFunction() &&6639 "Method is not an explicit member function");6640 assert(NewArgs.empty() && "NewArgs should be empty");6641 6642 NewArgs.reserve(Args.size() + 1);6643 Expr *This = GetExplicitObjectExpr(S, Object, Method);6644 NewArgs.push_back(This);6645 NewArgs.append(Args.begin(), Args.end());6646 Args = NewArgs;6647 return S.DiagnoseInvalidExplicitObjectParameterInLambda(6648 Method, Object->getBeginLoc());6649}6650 6651/// Determine whether the provided type is an integral type, or an enumeration6652/// type of a permitted flavor.6653bool Sema::ICEConvertDiagnoser::match(QualType T) {6654 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()6655 : T->isIntegralOrUnscopedEnumerationType();6656}6657 6658static ExprResult6659diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,6660 Sema::ContextualImplicitConverter &Converter,6661 QualType T, UnresolvedSetImpl &ViableConversions) {6662 6663 if (Converter.Suppress)6664 return ExprError();6665 6666 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();6667 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {6668 CXXConversionDecl *Conv =6669 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());6670 QualType ConvTy = Conv->getConversionType().getNonReferenceType();6671 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);6672 }6673 return From;6674}6675 6676static bool6677diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,6678 Sema::ContextualImplicitConverter &Converter,6679 QualType T, bool HadMultipleCandidates,6680 UnresolvedSetImpl &ExplicitConversions) {6681 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {6682 DeclAccessPair Found = ExplicitConversions[0];6683 CXXConversionDecl *Conversion =6684 cast<CXXConversionDecl>(Found->getUnderlyingDecl());6685 6686 // The user probably meant to invoke the given explicit6687 // conversion; use it.6688 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();6689 std::string TypeStr;6690 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());6691 6692 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)6693 << FixItHint::CreateInsertion(From->getBeginLoc(),6694 "static_cast<" + TypeStr + ">(")6695 << FixItHint::CreateInsertion(6696 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");6697 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);6698 6699 // If we aren't in a SFINAE context, build a call to the6700 // explicit conversion function.6701 if (SemaRef.isSFINAEContext())6702 return true;6703 6704 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);6705 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,6706 HadMultipleCandidates);6707 if (Result.isInvalid())6708 return true;6709 6710 // Replace the conversion with a RecoveryExpr, so we don't try to6711 // instantiate it later, but can further diagnose here.6712 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),6713 From, Result.get()->getType());6714 if (Result.isInvalid())6715 return true;6716 From = Result.get();6717 }6718 return false;6719}6720 6721static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,6722 Sema::ContextualImplicitConverter &Converter,6723 QualType T, bool HadMultipleCandidates,6724 DeclAccessPair &Found) {6725 CXXConversionDecl *Conversion =6726 cast<CXXConversionDecl>(Found->getUnderlyingDecl());6727 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);6728 6729 QualType ToType = Conversion->getConversionType().getNonReferenceType();6730 if (!Converter.SuppressConversion) {6731 if (SemaRef.isSFINAEContext())6732 return true;6733 6734 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)6735 << From->getSourceRange();6736 }6737 6738 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,6739 HadMultipleCandidates);6740 if (Result.isInvalid())6741 return true;6742 // Record usage of conversion in an implicit cast.6743 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),6744 CK_UserDefinedConversion, Result.get(),6745 nullptr, Result.get()->getValueKind(),6746 SemaRef.CurFPFeatureOverrides());6747 return false;6748}6749 6750static ExprResult finishContextualImplicitConversion(6751 Sema &SemaRef, SourceLocation Loc, Expr *From,6752 Sema::ContextualImplicitConverter &Converter) {6753 if (!Converter.match(From->getType()) && !Converter.Suppress)6754 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())6755 << From->getSourceRange();6756 6757 return SemaRef.DefaultLvalueConversion(From);6758}6759 6760static void6761collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,6762 UnresolvedSetImpl &ViableConversions,6763 OverloadCandidateSet &CandidateSet) {6764 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {6765 NamedDecl *D = FoundDecl.getDecl();6766 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());6767 if (isa<UsingShadowDecl>(D))6768 D = cast<UsingShadowDecl>(D)->getTargetDecl();6769 6770 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {6771 SemaRef.AddTemplateConversionCandidate(6772 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,6773 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);6774 continue;6775 }6776 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);6777 SemaRef.AddConversionCandidate(6778 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,6779 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);6780 }6781}6782 6783/// Attempt to convert the given expression to a type which is accepted6784/// by the given converter.6785///6786/// This routine will attempt to convert an expression of class type to a6787/// type accepted by the specified converter. In C++11 and before, the class6788/// must have a single non-explicit conversion function converting to a matching6789/// type. In C++1y, there can be multiple such conversion functions, but only6790/// one target type.6791///6792/// \param Loc The source location of the construct that requires the6793/// conversion.6794///6795/// \param From The expression we're converting from.6796///6797/// \param Converter Used to control and diagnose the conversion process.6798///6799/// \returns The expression, converted to an integral or enumeration type if6800/// successful.6801ExprResult Sema::PerformContextualImplicitConversion(6802 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {6803 // We can't perform any more checking for type-dependent expressions.6804 if (From->isTypeDependent())6805 return From;6806 6807 // Process placeholders immediately.6808 if (From->hasPlaceholderType()) {6809 ExprResult result = CheckPlaceholderExpr(From);6810 if (result.isInvalid())6811 return result;6812 From = result.get();6813 }6814 6815 // Try converting the expression to an Lvalue first, to get rid of qualifiers.6816 ExprResult Converted = DefaultLvalueConversion(From);6817 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();6818 // If the expression already has a matching type, we're golden.6819 if (Converter.match(T))6820 return Converted;6821 6822 // FIXME: Check for missing '()' if T is a function type?6823 6824 // We can only perform contextual implicit conversions on objects of class6825 // type.6826 const RecordType *RecordTy = T->getAsCanonical<RecordType>();6827 if (!RecordTy || !getLangOpts().CPlusPlus) {6828 if (!Converter.Suppress)6829 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();6830 return From;6831 }6832 6833 // We must have a complete class type.6834 struct TypeDiagnoserPartialDiag : TypeDiagnoser {6835 ContextualImplicitConverter &Converter;6836 Expr *From;6837 6838 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)6839 : Converter(Converter), From(From) {}6840 6841 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {6842 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();6843 }6844 } IncompleteDiagnoser(Converter, From);6845 6846 if (Converter.Suppress ? !isCompleteType(Loc, T)6847 : RequireCompleteType(Loc, T, IncompleteDiagnoser))6848 return From;6849 6850 // Look for a conversion to an integral or enumeration type.6851 UnresolvedSet<4>6852 ViableConversions; // These are *potentially* viable in C++1y.6853 UnresolvedSet<4> ExplicitConversions;6854 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())6855 ->getDefinitionOrSelf()6856 ->getVisibleConversionFunctions();6857 6858 bool HadMultipleCandidates =6859 (std::distance(Conversions.begin(), Conversions.end()) > 1);6860 6861 // To check that there is only one target type, in C++1y:6862 QualType ToType;6863 bool HasUniqueTargetType = true;6864 6865 // Collect explicit or viable (potentially in C++1y) conversions.6866 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {6867 NamedDecl *D = (*I)->getUnderlyingDecl();6868 CXXConversionDecl *Conversion;6869 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);6870 if (ConvTemplate) {6871 if (getLangOpts().CPlusPlus14)6872 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());6873 else6874 continue; // C++11 does not consider conversion operator templates(?).6875 } else6876 Conversion = cast<CXXConversionDecl>(D);6877 6878 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&6879 "Conversion operator templates are considered potentially "6880 "viable in C++1y");6881 6882 QualType CurToType = Conversion->getConversionType().getNonReferenceType();6883 if (Converter.match(CurToType) || ConvTemplate) {6884 6885 if (Conversion->isExplicit()) {6886 // FIXME: For C++1y, do we need this restriction?6887 // cf. diagnoseNoViableConversion()6888 if (!ConvTemplate)6889 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());6890 } else {6891 if (!ConvTemplate && getLangOpts().CPlusPlus14) {6892 if (ToType.isNull())6893 ToType = CurToType.getUnqualifiedType();6894 else if (HasUniqueTargetType &&6895 (CurToType.getUnqualifiedType() != ToType))6896 HasUniqueTargetType = false;6897 }6898 ViableConversions.addDecl(I.getDecl(), I.getAccess());6899 }6900 }6901 }6902 6903 if (getLangOpts().CPlusPlus14) {6904 // C++1y [conv]p6:6905 // ... An expression e of class type E appearing in such a context6906 // is said to be contextually implicitly converted to a specified6907 // type T and is well-formed if and only if e can be implicitly6908 // converted to a type T that is determined as follows: E is searched6909 // for conversion functions whose return type is cv T or reference to6910 // cv T such that T is allowed by the context. There shall be6911 // exactly one such T.6912 6913 // If no unique T is found:6914 if (ToType.isNull()) {6915 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,6916 HadMultipleCandidates,6917 ExplicitConversions))6918 return ExprError();6919 return finishContextualImplicitConversion(*this, Loc, From, Converter);6920 }6921 6922 // If more than one unique Ts are found:6923 if (!HasUniqueTargetType)6924 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,6925 ViableConversions);6926 6927 // If one unique T is found:6928 // First, build a candidate set from the previously recorded6929 // potentially viable conversions.6930 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);6931 collectViableConversionCandidates(*this, From, ToType, ViableConversions,6932 CandidateSet);6933 6934 // Then, perform overload resolution over the candidate set.6935 OverloadCandidateSet::iterator Best;6936 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {6937 case OR_Success: {6938 // Apply this conversion.6939 DeclAccessPair Found =6940 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());6941 if (recordConversion(*this, Loc, From, Converter, T,6942 HadMultipleCandidates, Found))6943 return ExprError();6944 break;6945 }6946 case OR_Ambiguous:6947 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,6948 ViableConversions);6949 case OR_No_Viable_Function:6950 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,6951 HadMultipleCandidates,6952 ExplicitConversions))6953 return ExprError();6954 [[fallthrough]];6955 case OR_Deleted:6956 // We'll complain below about a non-integral condition type.6957 break;6958 }6959 } else {6960 switch (ViableConversions.size()) {6961 case 0: {6962 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,6963 HadMultipleCandidates,6964 ExplicitConversions))6965 return ExprError();6966 6967 // We'll complain below about a non-integral condition type.6968 break;6969 }6970 case 1: {6971 // Apply this conversion.6972 DeclAccessPair Found = ViableConversions[0];6973 if (recordConversion(*this, Loc, From, Converter, T,6974 HadMultipleCandidates, Found))6975 return ExprError();6976 break;6977 }6978 default:6979 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,6980 ViableConversions);6981 }6982 }6983 6984 return finishContextualImplicitConversion(*this, Loc, From, Converter);6985}6986 6987/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is6988/// an acceptable non-member overloaded operator for a call whose6989/// arguments have types T1 (and, if non-empty, T2). This routine6990/// implements the check in C++ [over.match.oper]p3b2 concerning6991/// enumeration types.6992static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,6993 FunctionDecl *Fn,6994 ArrayRef<Expr *> Args) {6995 QualType T1 = Args[0]->getType();6996 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();6997 6998 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))6999 return true;7000 7001 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))7002 return true;7003 7004 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();7005 if (Proto->getNumParams() < 1)7006 return false;7007 7008 if (T1->isEnumeralType()) {7009 QualType ArgType = Proto->getParamType(0).getNonReferenceType();7010 if (Context.hasSameUnqualifiedType(T1, ArgType))7011 return true;7012 }7013 7014 if (Proto->getNumParams() < 2)7015 return false;7016 7017 if (!T2.isNull() && T2->isEnumeralType()) {7018 QualType ArgType = Proto->getParamType(1).getNonReferenceType();7019 if (Context.hasSameUnqualifiedType(T2, ArgType))7020 return true;7021 }7022 7023 return false;7024}7025 7026static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {7027 if (FD->isTargetMultiVersionDefault())7028 return false;7029 7030 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())7031 return FD->isTargetMultiVersion();7032 7033 if (!FD->isMultiVersion())7034 return false;7035 7036 // Among multiple target versions consider either the default,7037 // or the first non-default in the absence of default version.7038 unsigned SeenAt = 0;7039 unsigned I = 0;7040 bool HasDefault = false;7041 FD->getASTContext().forEachMultiversionedFunctionVersion(7042 FD, [&](const FunctionDecl *CurFD) {7043 if (FD == CurFD)7044 SeenAt = I;7045 else if (CurFD->isTargetMultiVersionDefault())7046 HasDefault = true;7047 ++I;7048 });7049 return HasDefault || SeenAt != 0;7050}7051 7052void Sema::AddOverloadCandidate(7053 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,7054 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,7055 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,7056 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,7057 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,7058 bool StrictPackMatch) {7059 const FunctionProtoType *Proto7060 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());7061 assert(Proto && "Functions without a prototype cannot be overloaded");7062 assert(!Function->getDescribedFunctionTemplate() &&7063 "Use AddTemplateOverloadCandidate for function templates");7064 7065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {7066 if (!isa<CXXConstructorDecl>(Method)) {7067 // If we get here, it's because we're calling a member function7068 // that is named without a member access expression (e.g.,7069 // "this->f") that was either written explicitly or created7070 // implicitly. This can happen with a qualified call to a member7071 // function, e.g., X::f(). We use an empty type for the implied7072 // object argument (C++ [over.call.func]p3), and the acting context7073 // is irrelevant.7074 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),7075 Expr::Classification::makeSimpleLValue(), Args,7076 CandidateSet, SuppressUserConversions,7077 PartialOverloading, EarlyConversions, PO,7078 StrictPackMatch);7079 return;7080 }7081 // We treat a constructor like a non-member function, since its object7082 // argument doesn't participate in overload resolution.7083 }7084 7085 if (!CandidateSet.isNewCandidate(Function, PO))7086 return;7087 7088 // C++11 [class.copy]p11: [DR1402]7089 // A defaulted move constructor that is defined as deleted is ignored by7090 // overload resolution.7091 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);7092 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&7093 Constructor->isMoveConstructor())7094 return;7095 7096 // Overload resolution is always an unevaluated context.7097 EnterExpressionEvaluationContext Unevaluated(7098 *this, Sema::ExpressionEvaluationContext::Unevaluated);7099 7100 // C++ [over.match.oper]p3:7101 // if no operand has a class type, only those non-member functions in the7102 // lookup set that have a first parameter of type T1 or "reference to7103 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there7104 // is a right operand) a second parameter of type T2 or "reference to7105 // (possibly cv-qualified) T2", when T2 is an enumeration type, are7106 // candidate functions.7107 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&7108 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))7109 return;7110 7111 // Add this candidate7112 OverloadCandidate &Candidate =7113 CandidateSet.addCandidate(Args.size(), EarlyConversions);7114 Candidate.FoundDecl = FoundDecl;7115 Candidate.Function = Function;7116 Candidate.Viable = true;7117 Candidate.RewriteKind =7118 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);7119 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);7120 Candidate.ExplicitCallArguments = Args.size();7121 Candidate.StrictPackMatch = StrictPackMatch;7122 7123 // Explicit functions are not actually candidates at all if we're not7124 // allowing them in this context, but keep them around so we can point7125 // to them in diagnostics.7126 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {7127 Candidate.Viable = false;7128 Candidate.FailureKind = ovl_fail_explicit;7129 return;7130 }7131 7132 // Functions with internal linkage are only viable in the same module unit.7133 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {7134 /// FIXME: Currently, the semantics of linkage in clang is slightly7135 /// different from the semantics in C++ spec. In C++ spec, only names7136 /// have linkage. So that all entities of the same should share one7137 /// linkage. But in clang, different entities of the same could have7138 /// different linkage.7139 const NamedDecl *ND = Function;7140 bool IsImplicitlyInstantiated = false;7141 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {7142 ND = SpecInfo->getTemplate();7143 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==7144 TSK_ImplicitInstantiation;7145 }7146 7147 /// Don't remove inline functions with internal linkage from the overload7148 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.7149 /// However:7150 /// - Inline functions with internal linkage are a common pattern in7151 /// headers to avoid ODR issues.7152 /// - The global module is meant to be a transition mechanism for C and C++7153 /// headers, and the current rules as written work against that goal.7154 const bool IsInlineFunctionInGMF =7155 Function->isFromGlobalModule() &&7156 (IsImplicitlyInstantiated || Function->isInlined());7157 7158 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {7159 Candidate.Viable = false;7160 Candidate.FailureKind = ovl_fail_module_mismatched;7161 return;7162 }7163 }7164 7165 if (isNonViableMultiVersionOverload(Function)) {7166 Candidate.Viable = false;7167 Candidate.FailureKind = ovl_non_default_multiversion_function;7168 return;7169 }7170 7171 if (Constructor) {7172 // C++ [class.copy]p3:7173 // A member function template is never instantiated to perform the copy7174 // of a class object to an object of its class type.7175 CanQualType ClassType =7176 Context.getCanonicalTagType(Constructor->getParent());7177 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&7178 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||7179 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),7180 ClassType))) {7181 Candidate.Viable = false;7182 Candidate.FailureKind = ovl_fail_illegal_constructor;7183 return;7184 }7185 7186 // C++ [over.match.funcs]p8: (proposed DR resolution)7187 // A constructor inherited from class type C that has a first parameter7188 // of type "reference to P" (including such a constructor instantiated7189 // from a template) is excluded from the set of candidate functions when7190 // constructing an object of type cv D if the argument list has exactly7191 // one argument and D is reference-related to P and P is reference-related7192 // to C.7193 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());7194 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&7195 Constructor->getParamDecl(0)->getType()->isReferenceType()) {7196 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();7197 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());7198 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());7199 SourceLocation Loc = Args.front()->getExprLoc();7200 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&7201 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {7202 Candidate.Viable = false;7203 Candidate.FailureKind = ovl_fail_inhctor_slice;7204 return;7205 }7206 }7207 7208 // Check that the constructor is capable of constructing an object in the7209 // destination address space.7210 if (!Qualifiers::isAddressSpaceSupersetOf(7211 Constructor->getMethodQualifiers().getAddressSpace(),7212 CandidateSet.getDestAS(), getASTContext())) {7213 Candidate.Viable = false;7214 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;7215 }7216 }7217 7218 unsigned NumParams = Proto->getNumParams();7219 7220 // (C++ 13.3.2p2): A candidate function having fewer than m7221 // parameters is viable only if it has an ellipsis in its parameter7222 // list (8.3.5).7223 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&7224 !Proto->isVariadic() &&7225 shouldEnforceArgLimit(PartialOverloading, Function)) {7226 Candidate.Viable = false;7227 Candidate.FailureKind = ovl_fail_too_many_arguments;7228 return;7229 }7230 7231 // (C++ 13.3.2p2): A candidate function having more than m parameters7232 // is viable only if the (m+1)st parameter has a default argument7233 // (8.3.6). For the purposes of overload resolution, the7234 // parameter list is truncated on the right, so that there are7235 // exactly m parameters.7236 unsigned MinRequiredArgs = Function->getMinRequiredArguments();7237 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&7238 !PartialOverloading) {7239 // Not enough arguments.7240 Candidate.Viable = false;7241 Candidate.FailureKind = ovl_fail_too_few_arguments;7242 return;7243 }7244 7245 // (CUDA B.1): Check for invalid calls between targets.7246 if (getLangOpts().CUDA) {7247 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);7248 // Skip the check for callers that are implicit members, because in this7249 // case we may not yet know what the member's target is; the target is7250 // inferred for the member automatically, based on the bases and fields of7251 // the class.7252 if (!(Caller && Caller->isImplicit()) &&7253 !CUDA().IsAllowedCall(Caller, Function)) {7254 Candidate.Viable = false;7255 Candidate.FailureKind = ovl_fail_bad_target;7256 return;7257 }7258 }7259 7260 if (Function->getTrailingRequiresClause()) {7261 ConstraintSatisfaction Satisfaction;7262 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},7263 /*ForOverloadResolution*/ true) ||7264 !Satisfaction.IsSatisfied) {7265 Candidate.Viable = false;7266 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;7267 return;7268 }7269 }7270 7271 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);7272 // Determine the implicit conversion sequences for each of the7273 // arguments.7274 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {7275 unsigned ConvIdx =7276 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;7277 if (Candidate.Conversions[ConvIdx].isInitialized()) {7278 // We already formed a conversion sequence for this parameter during7279 // template argument deduction.7280 } else if (ArgIdx < NumParams) {7281 // (C++ 13.3.2p3): for F to be a viable function, there shall7282 // exist for each argument an implicit conversion sequence7283 // (13.3.3.1) that converts that argument to the corresponding7284 // parameter of F.7285 QualType ParamType = Proto->getParamType(ArgIdx);7286 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();7287 if (ParamABI == ParameterABI::HLSLOut ||7288 ParamABI == ParameterABI::HLSLInOut)7289 ParamType = ParamType.getNonReferenceType();7290 Candidate.Conversions[ConvIdx] = TryCopyInitialization(7291 *this, Args[ArgIdx], ParamType, SuppressUserConversions,7292 /*InOverloadResolution=*/true,7293 /*AllowObjCWritebackConversion=*/7294 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);7295 if (Candidate.Conversions[ConvIdx].isBad()) {7296 Candidate.Viable = false;7297 Candidate.FailureKind = ovl_fail_bad_conversion;7298 return;7299 }7300 } else {7301 // (C++ 13.3.2p2): For the purposes of overload resolution, any7302 // argument for which there is no corresponding parameter is7303 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).7304 Candidate.Conversions[ConvIdx].setEllipsis();7305 }7306 }7307 7308 if (EnableIfAttr *FailedAttr =7309 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {7310 Candidate.Viable = false;7311 Candidate.FailureKind = ovl_fail_enable_if;7312 Candidate.DeductionFailure.Data = FailedAttr;7313 return;7314 }7315}7316 7317ObjCMethodDecl *7318Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,7319 SmallVectorImpl<ObjCMethodDecl *> &Methods) {7320 if (Methods.size() <= 1)7321 return nullptr;7322 7323 for (unsigned b = 0, e = Methods.size(); b < e; b++) {7324 bool Match = true;7325 ObjCMethodDecl *Method = Methods[b];7326 unsigned NumNamedArgs = Sel.getNumArgs();7327 // Method might have more arguments than selector indicates. This is due7328 // to addition of c-style arguments in method.7329 if (Method->param_size() > NumNamedArgs)7330 NumNamedArgs = Method->param_size();7331 if (Args.size() < NumNamedArgs)7332 continue;7333 7334 for (unsigned i = 0; i < NumNamedArgs; i++) {7335 // We can't do any type-checking on a type-dependent argument.7336 if (Args[i]->isTypeDependent()) {7337 Match = false;7338 break;7339 }7340 7341 ParmVarDecl *param = Method->parameters()[i];7342 Expr *argExpr = Args[i];7343 assert(argExpr && "SelectBestMethod(): missing expression");7344 7345 // Strip the unbridged-cast placeholder expression off unless it's7346 // a consumed argument.7347 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&7348 !param->hasAttr<CFConsumedAttr>())7349 argExpr = ObjC().stripARCUnbridgedCast(argExpr);7350 7351 // If the parameter is __unknown_anytype, move on to the next method.7352 if (param->getType() == Context.UnknownAnyTy) {7353 Match = false;7354 break;7355 }7356 7357 ImplicitConversionSequence ConversionState7358 = TryCopyInitialization(*this, argExpr, param->getType(),7359 /*SuppressUserConversions*/false,7360 /*InOverloadResolution=*/true,7361 /*AllowObjCWritebackConversion=*/7362 getLangOpts().ObjCAutoRefCount,7363 /*AllowExplicit*/false);7364 // This function looks for a reasonably-exact match, so we consider7365 // incompatible pointer conversions to be a failure here.7366 if (ConversionState.isBad() ||7367 (ConversionState.isStandard() &&7368 ConversionState.Standard.Second ==7369 ICK_Incompatible_Pointer_Conversion)) {7370 Match = false;7371 break;7372 }7373 }7374 // Promote additional arguments to variadic methods.7375 if (Match && Method->isVariadic()) {7376 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {7377 if (Args[i]->isTypeDependent()) {7378 Match = false;7379 break;7380 }7381 ExprResult Arg = DefaultVariadicArgumentPromotion(7382 Args[i], VariadicCallType::Method, nullptr);7383 if (Arg.isInvalid()) {7384 Match = false;7385 break;7386 }7387 }7388 } else {7389 // Check for extra arguments to non-variadic methods.7390 if (Args.size() != NumNamedArgs)7391 Match = false;7392 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {7393 // Special case when selectors have no argument. In this case, select7394 // one with the most general result type of 'id'.7395 for (unsigned b = 0, e = Methods.size(); b < e; b++) {7396 QualType ReturnT = Methods[b]->getReturnType();7397 if (ReturnT->isObjCIdType())7398 return Methods[b];7399 }7400 }7401 }7402 7403 if (Match)7404 return Method;7405 }7406 return nullptr;7407}7408 7409static bool convertArgsForAvailabilityChecks(7410 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,7411 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,7412 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {7413 if (ThisArg) {7414 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);7415 assert(!isa<CXXConstructorDecl>(Method) &&7416 "Shouldn't have `this` for ctors!");7417 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");7418 ExprResult R = S.PerformImplicitObjectArgumentInitialization(7419 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);7420 if (R.isInvalid())7421 return false;7422 ConvertedThis = R.get();7423 } else {7424 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {7425 (void)MD;7426 assert((MissingImplicitThis || MD->isStatic() ||7427 isa<CXXConstructorDecl>(MD)) &&7428 "Expected `this` for non-ctor instance methods");7429 }7430 ConvertedThis = nullptr;7431 }7432 7433 // Ignore any variadic arguments. Converting them is pointless, since the7434 // user can't refer to them in the function condition.7435 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());7436 7437 // Convert the arguments.7438 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {7439 ExprResult R;7440 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(7441 S.Context, Function->getParamDecl(I)),7442 SourceLocation(), Args[I]);7443 7444 if (R.isInvalid())7445 return false;7446 7447 ConvertedArgs.push_back(R.get());7448 }7449 7450 if (Trap.hasErrorOccurred())7451 return false;7452 7453 // Push default arguments if needed.7454 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {7455 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {7456 ParmVarDecl *P = Function->getParamDecl(i);7457 if (!P->hasDefaultArg())7458 return false;7459 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);7460 if (R.isInvalid())7461 return false;7462 ConvertedArgs.push_back(R.get());7463 }7464 7465 if (Trap.hasErrorOccurred())7466 return false;7467 }7468 return true;7469}7470 7471EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,7472 SourceLocation CallLoc,7473 ArrayRef<Expr *> Args,7474 bool MissingImplicitThis) {7475 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();7476 if (EnableIfAttrs.begin() == EnableIfAttrs.end())7477 return nullptr;7478 7479 SFINAETrap Trap(*this);7480 SmallVector<Expr *, 16> ConvertedArgs;7481 // FIXME: We should look into making enable_if late-parsed.7482 Expr *DiscardedThis;7483 if (!convertArgsForAvailabilityChecks(7484 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,7485 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))7486 return *EnableIfAttrs.begin();7487 7488 for (auto *EIA : EnableIfAttrs) {7489 APValue Result;7490 // FIXME: This doesn't consider value-dependent cases, because doing so is7491 // very difficult. Ideally, we should handle them more gracefully.7492 if (EIA->getCond()->isValueDependent() ||7493 !EIA->getCond()->EvaluateWithSubstitution(7494 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))7495 return EIA;7496 7497 if (!Result.isInt() || !Result.getInt().getBoolValue())7498 return EIA;7499 }7500 return nullptr;7501}7502 7503template <typename CheckFn>7504static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,7505 bool ArgDependent, SourceLocation Loc,7506 CheckFn &&IsSuccessful) {7507 SmallVector<const DiagnoseIfAttr *, 8> Attrs;7508 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {7509 if (ArgDependent == DIA->getArgDependent())7510 Attrs.push_back(DIA);7511 }7512 7513 // Common case: No diagnose_if attributes, so we can quit early.7514 if (Attrs.empty())7515 return false;7516 7517 auto WarningBegin = std::stable_partition(7518 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {7519 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&7520 DIA->getWarningGroup().empty();7521 });7522 7523 // Note that diagnose_if attributes are late-parsed, so they appear in the7524 // correct order (unlike enable_if attributes).7525 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),7526 IsSuccessful);7527 if (ErrAttr != WarningBegin) {7528 const DiagnoseIfAttr *DIA = *ErrAttr;7529 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();7530 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)7531 << DIA->getParent() << DIA->getCond()->getSourceRange();7532 return true;7533 }7534 7535 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {7536 switch (Sev) {7537 case DiagnoseIfAttr::DS_warning:7538 return diag::Severity::Warning;7539 case DiagnoseIfAttr::DS_error:7540 return diag::Severity::Error;7541 }7542 llvm_unreachable("Fully covered switch above!");7543 };7544 7545 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))7546 if (IsSuccessful(DIA)) {7547 if (DIA->getWarningGroup().empty() &&7548 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {7549 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();7550 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)7551 << DIA->getParent() << DIA->getCond()->getSourceRange();7552 } else {7553 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(7554 DIA->getWarningGroup());7555 assert(DiagGroup);7556 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(7557 {ToSeverity(DIA->getDefaultSeverity()), "%0",7558 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});7559 S.Diag(Loc, DiagID) << DIA->getMessage();7560 }7561 }7562 7563 return false;7564}7565 7566bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,7567 const Expr *ThisArg,7568 ArrayRef<const Expr *> Args,7569 SourceLocation Loc) {7570 return diagnoseDiagnoseIfAttrsWith(7571 *this, Function, /*ArgDependent=*/true, Loc,7572 [&](const DiagnoseIfAttr *DIA) {7573 APValue Result;7574 // It's sane to use the same Args for any redecl of this function, since7575 // EvaluateWithSubstitution only cares about the position of each7576 // argument in the arg list, not the ParmVarDecl* it maps to.7577 if (!DIA->getCond()->EvaluateWithSubstitution(7578 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))7579 return false;7580 return Result.isInt() && Result.getInt().getBoolValue();7581 });7582}7583 7584bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,7585 SourceLocation Loc) {7586 return diagnoseDiagnoseIfAttrsWith(7587 *this, ND, /*ArgDependent=*/false, Loc,7588 [&](const DiagnoseIfAttr *DIA) {7589 bool Result;7590 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&7591 Result;7592 });7593}7594 7595void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,7596 ArrayRef<Expr *> Args,7597 OverloadCandidateSet &CandidateSet,7598 TemplateArgumentListInfo *ExplicitTemplateArgs,7599 bool SuppressUserConversions,7600 bool PartialOverloading,7601 bool FirstArgumentIsBase) {7602 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {7603 NamedDecl *D = F.getDecl()->getUnderlyingDecl();7604 ArrayRef<Expr *> FunctionArgs = Args;7605 7606 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);7607 FunctionDecl *FD =7608 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);7609 7610 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {7611 QualType ObjectType;7612 Expr::Classification ObjectClassification;7613 if (Args.size() > 0) {7614 if (Expr *E = Args[0]) {7615 // Use the explicit base to restrict the lookup:7616 ObjectType = E->getType();7617 // Pointers in the object arguments are implicitly dereferenced, so we7618 // always classify them as l-values.7619 if (!ObjectType.isNull() && ObjectType->isPointerType())7620 ObjectClassification = Expr::Classification::makeSimpleLValue();7621 else7622 ObjectClassification = E->Classify(Context);7623 } // .. else there is an implicit base.7624 FunctionArgs = Args.slice(1);7625 }7626 if (FunTmpl) {7627 AddMethodTemplateCandidate(7628 FunTmpl, F.getPair(),7629 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),7630 ExplicitTemplateArgs, ObjectType, ObjectClassification,7631 FunctionArgs, CandidateSet, SuppressUserConversions,7632 PartialOverloading);7633 } else {7634 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),7635 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,7636 ObjectClassification, FunctionArgs, CandidateSet,7637 SuppressUserConversions, PartialOverloading);7638 }7639 } else {7640 // This branch handles both standalone functions and static methods.7641 7642 // Slice the first argument (which is the base) when we access7643 // static method as non-static.7644 if (Args.size() > 0 &&7645 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&7646 !isa<CXXConstructorDecl>(FD)))) {7647 assert(cast<CXXMethodDecl>(FD)->isStatic());7648 FunctionArgs = Args.slice(1);7649 }7650 if (FunTmpl) {7651 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),7652 ExplicitTemplateArgs, FunctionArgs,7653 CandidateSet, SuppressUserConversions,7654 PartialOverloading);7655 } else {7656 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,7657 SuppressUserConversions, PartialOverloading);7658 }7659 }7660 }7661}7662 7663void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,7664 Expr::Classification ObjectClassification,7665 ArrayRef<Expr *> Args,7666 OverloadCandidateSet &CandidateSet,7667 bool SuppressUserConversions,7668 OverloadCandidateParamOrder PO) {7669 NamedDecl *Decl = FoundDecl.getDecl();7670 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());7671 7672 if (isa<UsingShadowDecl>(Decl))7673 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();7674 7675 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {7676 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&7677 "Expected a member function template");7678 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,7679 /*ExplicitArgs*/ nullptr, ObjectType,7680 ObjectClassification, Args, CandidateSet,7681 SuppressUserConversions, false, PO);7682 } else {7683 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,7684 ObjectType, ObjectClassification, Args, CandidateSet,7685 SuppressUserConversions, false, {}, PO);7686 }7687}7688 7689void Sema::AddMethodCandidate(7690 CXXMethodDecl *Method, DeclAccessPair FoundDecl,7691 CXXRecordDecl *ActingContext, QualType ObjectType,7692 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,7693 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,7694 bool PartialOverloading, ConversionSequenceList EarlyConversions,7695 OverloadCandidateParamOrder PO, bool StrictPackMatch) {7696 const FunctionProtoType *Proto7697 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());7698 assert(Proto && "Methods without a prototype cannot be overloaded");7699 assert(!isa<CXXConstructorDecl>(Method) &&7700 "Use AddOverloadCandidate for constructors");7701 7702 if (!CandidateSet.isNewCandidate(Method, PO))7703 return;7704 7705 // C++11 [class.copy]p23: [DR1402]7706 // A defaulted move assignment operator that is defined as deleted is7707 // ignored by overload resolution.7708 if (Method->isDefaulted() && Method->isDeleted() &&7709 Method->isMoveAssignmentOperator())7710 return;7711 7712 // Overload resolution is always an unevaluated context.7713 EnterExpressionEvaluationContext Unevaluated(7714 *this, Sema::ExpressionEvaluationContext::Unevaluated);7715 7716 bool IgnoreExplicitObject =7717 (Method->isExplicitObjectMemberFunction() &&7718 CandidateSet.getKind() ==7719 OverloadCandidateSet::CSK_AddressOfOverloadSet);7720 bool ImplicitObjectMethodTreatedAsStatic =7721 CandidateSet.getKind() ==7722 OverloadCandidateSet::CSK_AddressOfOverloadSet &&7723 Method->isImplicitObjectMemberFunction();7724 7725 unsigned ExplicitOffset =7726 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;7727 7728 unsigned NumParams = Method->getNumParams() - ExplicitOffset +7729 int(ImplicitObjectMethodTreatedAsStatic);7730 7731 unsigned ExtraArgs =7732 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet7733 ? 07734 : 1;7735 7736 // Add this candidate7737 OverloadCandidate &Candidate =7738 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);7739 Candidate.FoundDecl = FoundDecl;7740 Candidate.Function = Method;7741 Candidate.RewriteKind =7742 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);7743 Candidate.TookAddressOfOverload =7744 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;7745 Candidate.ExplicitCallArguments = Args.size();7746 Candidate.StrictPackMatch = StrictPackMatch;7747 7748 // (C++ 13.3.2p2): A candidate function having fewer than m7749 // parameters is viable only if it has an ellipsis in its parameter7750 // list (8.3.5).7751 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&7752 !Proto->isVariadic() &&7753 shouldEnforceArgLimit(PartialOverloading, Method)) {7754 Candidate.Viable = false;7755 Candidate.FailureKind = ovl_fail_too_many_arguments;7756 return;7757 }7758 7759 // (C++ 13.3.2p2): A candidate function having more than m parameters7760 // is viable only if the (m+1)st parameter has a default argument7761 // (8.3.6). For the purposes of overload resolution, the7762 // parameter list is truncated on the right, so that there are7763 // exactly m parameters.7764 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -7765 ExplicitOffset +7766 int(ImplicitObjectMethodTreatedAsStatic);7767 7768 if (Args.size() < MinRequiredArgs && !PartialOverloading) {7769 // Not enough arguments.7770 Candidate.Viable = false;7771 Candidate.FailureKind = ovl_fail_too_few_arguments;7772 return;7773 }7774 7775 Candidate.Viable = true;7776 7777 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;7778 if (!IgnoreExplicitObject) {7779 if (ObjectType.isNull())7780 Candidate.IgnoreObjectArgument = true;7781 else if (Method->isStatic()) {7782 // [over.best.ics.general]p87783 // When the parameter is the implicit object parameter of a static member7784 // function, the implicit conversion sequence is a standard conversion7785 // sequence that is neither better nor worse than any other standard7786 // conversion sequence.7787 //7788 // This is a rule that was introduced in C++23 to support static lambdas.7789 // We apply it retroactively because we want to support static lambdas as7790 // an extension and it doesn't hurt previous code.7791 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();7792 } else {7793 // Determine the implicit conversion sequence for the object7794 // parameter.7795 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(7796 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,7797 Method, ActingContext, /*InOverloadResolution=*/true);7798 if (Candidate.Conversions[FirstConvIdx].isBad()) {7799 Candidate.Viable = false;7800 Candidate.FailureKind = ovl_fail_bad_conversion;7801 return;7802 }7803 }7804 }7805 7806 // (CUDA B.1): Check for invalid calls between targets.7807 if (getLangOpts().CUDA)7808 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),7809 Method)) {7810 Candidate.Viable = false;7811 Candidate.FailureKind = ovl_fail_bad_target;7812 return;7813 }7814 7815 if (Method->getTrailingRequiresClause()) {7816 ConstraintSatisfaction Satisfaction;7817 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},7818 /*ForOverloadResolution*/ true) ||7819 !Satisfaction.IsSatisfied) {7820 Candidate.Viable = false;7821 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;7822 return;7823 }7824 }7825 7826 // Determine the implicit conversion sequences for each of the7827 // arguments.7828 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {7829 unsigned ConvIdx =7830 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);7831 if (Candidate.Conversions[ConvIdx].isInitialized()) {7832 // We already formed a conversion sequence for this parameter during7833 // template argument deduction.7834 } else if (ArgIdx < NumParams) {7835 // (C++ 13.3.2p3): for F to be a viable function, there shall7836 // exist for each argument an implicit conversion sequence7837 // (13.3.3.1) that converts that argument to the corresponding7838 // parameter of F.7839 QualType ParamType;7840 if (ImplicitObjectMethodTreatedAsStatic) {7841 ParamType = ArgIdx == 07842 ? Method->getFunctionObjectParameterReferenceType()7843 : Proto->getParamType(ArgIdx - 1);7844 } else {7845 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);7846 }7847 Candidate.Conversions[ConvIdx]7848 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,7849 SuppressUserConversions,7850 /*InOverloadResolution=*/true,7851 /*AllowObjCWritebackConversion=*/7852 getLangOpts().ObjCAutoRefCount);7853 if (Candidate.Conversions[ConvIdx].isBad()) {7854 Candidate.Viable = false;7855 Candidate.FailureKind = ovl_fail_bad_conversion;7856 return;7857 }7858 } else {7859 // (C++ 13.3.2p2): For the purposes of overload resolution, any7860 // argument for which there is no corresponding parameter is7861 // considered to "match the ellipsis" (C+ 13.3.3.1.3).7862 Candidate.Conversions[ConvIdx].setEllipsis();7863 }7864 }7865 7866 if (EnableIfAttr *FailedAttr =7867 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {7868 Candidate.Viable = false;7869 Candidate.FailureKind = ovl_fail_enable_if;7870 Candidate.DeductionFailure.Data = FailedAttr;7871 return;7872 }7873 7874 if (isNonViableMultiVersionOverload(Method)) {7875 Candidate.Viable = false;7876 Candidate.FailureKind = ovl_non_default_multiversion_function;7877 }7878}7879 7880static void AddMethodTemplateCandidateImmediately(7881 Sema &S, OverloadCandidateSet &CandidateSet,7882 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,7883 CXXRecordDecl *ActingContext,7884 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,7885 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,7886 bool SuppressUserConversions, bool PartialOverloading,7887 OverloadCandidateParamOrder PO) {7888 7889 // C++ [over.match.funcs]p7:7890 // In each case where a candidate is a function template, candidate7891 // function template specializations are generated using template argument7892 // deduction (14.8.3, 14.8.2). Those candidates are then handled as7893 // candidate functions in the usual way.113) A given name can refer to one7894 // or more function templates and also to a set of overloaded non-template7895 // functions. In such a case, the candidate functions generated from each7896 // function template are combined with the set of non-template candidate7897 // functions.7898 TemplateDeductionInfo Info(CandidateSet.getLocation());7899 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());7900 FunctionDecl *Specialization = nullptr;7901 ConversionSequenceList Conversions;7902 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(7903 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,7904 PartialOverloading, /*AggregateDeductionCandidate=*/false,7905 /*PartialOrdering=*/false, ObjectType, ObjectClassification,7906 CandidateSet.getKind() ==7907 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,7908 [&](ArrayRef<QualType> ParamTypes,7909 bool OnlyInitializeNonUserDefinedConversions) {7910 return S.CheckNonDependentConversions(7911 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,7912 Sema::CheckNonDependentConversionsFlag(7913 SuppressUserConversions,7914 OnlyInitializeNonUserDefinedConversions),7915 ActingContext, ObjectType, ObjectClassification, PO);7916 });7917 Result != TemplateDeductionResult::Success) {7918 OverloadCandidate &Candidate =7919 CandidateSet.addCandidate(Conversions.size(), Conversions);7920 Candidate.FoundDecl = FoundDecl;7921 Candidate.Function = Method;7922 Candidate.Viable = false;7923 Candidate.RewriteKind =7924 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);7925 Candidate.IsSurrogate = false;7926 Candidate.TookAddressOfOverload =7927 CandidateSet.getKind() ==7928 OverloadCandidateSet::CSK_AddressOfOverloadSet;7929 7930 Candidate.IgnoreObjectArgument =7931 Method->isStatic() ||7932 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());7933 Candidate.ExplicitCallArguments = Args.size();7934 if (Result == TemplateDeductionResult::NonDependentConversionFailure)7935 Candidate.FailureKind = ovl_fail_bad_conversion;7936 else {7937 Candidate.FailureKind = ovl_fail_bad_deduction;7938 Candidate.DeductionFailure =7939 MakeDeductionFailureInfo(S.Context, Result, Info);7940 }7941 return;7942 }7943 7944 // Add the function template specialization produced by template argument7945 // deduction as a candidate.7946 assert(Specialization && "Missing member function template specialization?");7947 assert(isa<CXXMethodDecl>(Specialization) &&7948 "Specialization is not a member function?");7949 S.AddMethodCandidate(7950 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,7951 ObjectClassification, Args, CandidateSet, SuppressUserConversions,7952 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());7953}7954 7955void Sema::AddMethodTemplateCandidate(7956 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,7957 CXXRecordDecl *ActingContext,7958 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,7959 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,7960 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,7961 bool PartialOverloading, OverloadCandidateParamOrder PO) {7962 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))7963 return;7964 7965 if (ExplicitTemplateArgs ||7966 !CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts())) {7967 AddMethodTemplateCandidateImmediately(7968 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,7969 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,7970 SuppressUserConversions, PartialOverloading, PO);7971 return;7972 }7973 7974 CandidateSet.AddDeferredMethodTemplateCandidate(7975 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,7976 Args, SuppressUserConversions, PartialOverloading, PO);7977}7978 7979/// Determine whether a given function template has a simple explicit specifier7980/// or a non-value-dependent explicit-specification that evaluates to true.7981static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {7982 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();7983}7984 7985static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {7986 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).getKind() ==7987 ExplicitSpecKind::Unresolved;7988}7989 7990static void AddTemplateOverloadCandidateImmediately(7991 Sema &S, OverloadCandidateSet &CandidateSet,7992 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,7993 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,7994 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,7995 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,7996 bool AggregateCandidateDeduction) {7997 7998 // If the function template has a non-dependent explicit specification,7999 // exclude it now if appropriate; we are not permitted to perform deduction8000 // and substitution in this case.8001 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {8002 OverloadCandidate &Candidate = CandidateSet.addCandidate();8003 Candidate.FoundDecl = FoundDecl;8004 Candidate.Function = FunctionTemplate->getTemplatedDecl();8005 Candidate.Viable = false;8006 Candidate.FailureKind = ovl_fail_explicit;8007 return;8008 }8009 8010 // C++ [over.match.funcs]p7:8011 // In each case where a candidate is a function template, candidate8012 // function template specializations are generated using template argument8013 // deduction (14.8.3, 14.8.2). Those candidates are then handled as8014 // candidate functions in the usual way.113) A given name can refer to one8015 // or more function templates and also to a set of overloaded non-template8016 // functions. In such a case, the candidate functions generated from each8017 // function template are combined with the set of non-template candidate8018 // functions.8019 TemplateDeductionInfo Info(CandidateSet.getLocation(),8020 FunctionTemplate->getTemplateDepth());8021 FunctionDecl *Specialization = nullptr;8022 ConversionSequenceList Conversions;8023 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(8024 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,8025 PartialOverloading, AggregateCandidateDeduction,8026 /*PartialOrdering=*/false,8027 /*ObjectType=*/QualType(),8028 /*ObjectClassification=*/Expr::Classification(),8029 CandidateSet.getKind() ==8030 OverloadCandidateSet::CSK_AddressOfOverloadSet,8031 [&](ArrayRef<QualType> ParamTypes,8032 bool OnlyInitializeNonUserDefinedConversions) {8033 return S.CheckNonDependentConversions(8034 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,8035 Sema::CheckNonDependentConversionsFlag(8036 SuppressUserConversions,8037 OnlyInitializeNonUserDefinedConversions),8038 nullptr, QualType(), {}, PO);8039 });8040 Result != TemplateDeductionResult::Success) {8041 OverloadCandidate &Candidate =8042 CandidateSet.addCandidate(Conversions.size(), Conversions);8043 Candidate.FoundDecl = FoundDecl;8044 Candidate.Function = FunctionTemplate->getTemplatedDecl();8045 Candidate.Viable = false;8046 Candidate.RewriteKind =8047 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);8048 Candidate.IsSurrogate = false;8049 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);8050 // Ignore the object argument if there is one, since we don't have an object8051 // type.8052 Candidate.TookAddressOfOverload =8053 CandidateSet.getKind() ==8054 OverloadCandidateSet::CSK_AddressOfOverloadSet;8055 8056 Candidate.IgnoreObjectArgument =8057 isa<CXXMethodDecl>(Candidate.Function) &&8058 !cast<CXXMethodDecl>(Candidate.Function)8059 ->isExplicitObjectMemberFunction() &&8060 !isa<CXXConstructorDecl>(Candidate.Function);8061 8062 Candidate.ExplicitCallArguments = Args.size();8063 if (Result == TemplateDeductionResult::NonDependentConversionFailure)8064 Candidate.FailureKind = ovl_fail_bad_conversion;8065 else {8066 Candidate.FailureKind = ovl_fail_bad_deduction;8067 Candidate.DeductionFailure =8068 MakeDeductionFailureInfo(S.Context, Result, Info);8069 }8070 return;8071 }8072 8073 // Add the function template specialization produced by template argument8074 // deduction as a candidate.8075 assert(Specialization && "Missing function template specialization?");8076 S.AddOverloadCandidate(8077 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,8078 PartialOverloading, AllowExplicit,8079 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,8080 Info.AggregateDeductionCandidateHasMismatchedArity,8081 Info.hasStrictPackMatch());8082}8083 8084void Sema::AddTemplateOverloadCandidate(8085 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,8086 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,8087 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,8088 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,8089 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {8090 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))8091 return;8092 8093 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);8094 8095 if (ExplicitTemplateArgs ||8096 !CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts()) ||8097 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&8098 DependentExplicitSpecifier)) {8099 8100 AddTemplateOverloadCandidateImmediately(8101 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,8102 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,8103 IsADLCandidate, PO, AggregateCandidateDeduction);8104 8105 if (DependentExplicitSpecifier)8106 CandidateSet.DisableResolutionByPerfectCandidate();8107 return;8108 }8109 8110 CandidateSet.AddDeferredTemplateCandidate(8111 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,8112 PartialOverloading, AllowExplicit, IsADLCandidate, PO,8113 AggregateCandidateDeduction);8114}8115 8116bool Sema::CheckNonDependentConversions(8117 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,8118 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,8119 ConversionSequenceList &Conversions,8120 CheckNonDependentConversionsFlag UserConversionFlag,8121 CXXRecordDecl *ActingContext, QualType ObjectType,8122 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {8123 // FIXME: The cases in which we allow explicit conversions for constructor8124 // arguments never consider calling a constructor template. It's not clear8125 // that is correct.8126 const bool AllowExplicit = false;8127 8128 bool ForOverloadSetAddressResolution =8129 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;8130 auto *FD = FunctionTemplate->getTemplatedDecl();8131 auto *Method = dyn_cast<CXXMethodDecl>(FD);8132 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&8133 !isa<CXXConstructorDecl>(Method);8134 unsigned ThisConversions = HasThisConversion ? 1 : 0;8135 8136 if (Conversions.empty())8137 Conversions =8138 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());8139 8140 // Overload resolution is always an unevaluated context.8141 EnterExpressionEvaluationContext Unevaluated(8142 *this, Sema::ExpressionEvaluationContext::Unevaluated);8143 8144 // For a method call, check the 'this' conversion here too. DR1391 doesn't8145 // require that, but this check should never result in a hard error, and8146 // overload resolution is permitted to sidestep instantiations.8147 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&8148 !ObjectType.isNull()) {8149 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;8150 if (!FD->hasCXXExplicitFunctionObjectParameter() ||8151 !ParamTypes[0]->isDependentType()) {8152 Conversions[ConvIdx] = TryObjectArgumentInitialization(8153 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,8154 Method, ActingContext, /*InOverloadResolution=*/true,8155 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]8156 : QualType());8157 if (Conversions[ConvIdx].isBad())8158 return true;8159 }8160 }8161 8162 // A speculative workaround for self-dependent constraint bugs that manifest8163 // after CWG2369.8164 // FIXME: Add references to the standard once P3606 is adopted.8165 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,8166 QualType ArgType) {8167 ParamType = ParamType.getNonReferenceType();8168 ArgType = ArgType.getNonReferenceType();8169 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();8170 if (PointerConv) {8171 ParamType = ParamType->getPointeeType();8172 ArgType = ArgType->getPointeeType();8173 }8174 8175 if (auto *RD = ParamType->getAsCXXRecordDecl();8176 RD && RD->hasDefinition() &&8177 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {8178 auto Info = getConstructorInfo(ND);8179 if (!Info)8180 return false;8181 CXXConstructorDecl *Ctor = Info.Constructor;8182 /// isConvertingConstructor takes copy/move constructors into8183 /// account!8184 return !Ctor->isCopyOrMoveConstructor() &&8185 Ctor->isConvertingConstructor(8186 /*AllowExplicit=*/true);8187 }))8188 return true;8189 if (auto *RD = ArgType->getAsCXXRecordDecl();8190 RD && RD->hasDefinition() &&8191 !RD->getVisibleConversionFunctions().empty())8192 return true;8193 8194 return false;8195 };8196 8197 unsigned Offset =8198 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 18199 : 0;8200 8201 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());8202 I != N; ++I) {8203 QualType ParamType = ParamTypes[I + Offset];8204 if (!ParamType->isDependentType()) {8205 unsigned ConvIdx;8206 if (PO == OverloadCandidateParamOrder::Reversed) {8207 ConvIdx = Args.size() - 1 - I;8208 assert(Args.size() + ThisConversions == 2 &&8209 "number of args (including 'this') must be exactly 2 for "8210 "reversed order");8211 // For members, there would be only one arg 'Args[0]' whose ConvIdx8212 // would also be 0. 'this' got ConvIdx = 1 previously.8213 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));8214 } else {8215 // For members, 'this' got ConvIdx = 0 previously.8216 ConvIdx = ThisConversions + I;8217 }8218 if (Conversions[ConvIdx].isInitialized())8219 continue;8220 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&8221 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))8222 continue;8223 Conversions[ConvIdx] = TryCopyInitialization(8224 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,8225 /*InOverloadResolution=*/true,8226 /*AllowObjCWritebackConversion=*/8227 getLangOpts().ObjCAutoRefCount, AllowExplicit);8228 if (Conversions[ConvIdx].isBad())8229 return true;8230 }8231 }8232 8233 return false;8234}8235 8236/// Determine whether this is an allowable conversion from the result8237/// of an explicit conversion operator to the expected type, per C++8238/// [over.match.conv]p1 and [over.match.ref]p1.8239///8240/// \param ConvType The return type of the conversion function.8241///8242/// \param ToType The type we are converting to.8243///8244/// \param AllowObjCPointerConversion Allow a conversion from one8245/// Objective-C pointer to another.8246///8247/// \returns true if the conversion is allowable, false otherwise.8248static bool isAllowableExplicitConversion(Sema &S,8249 QualType ConvType, QualType ToType,8250 bool AllowObjCPointerConversion) {8251 QualType ToNonRefType = ToType.getNonReferenceType();8252 8253 // Easy case: the types are the same.8254 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))8255 return true;8256 8257 // Allow qualification conversions.8258 bool ObjCLifetimeConversion;8259 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,8260 ObjCLifetimeConversion))8261 return true;8262 8263 // If we're not allowed to consider Objective-C pointer conversions,8264 // we're done.8265 if (!AllowObjCPointerConversion)8266 return false;8267 8268 // Is this an Objective-C pointer conversion?8269 bool IncompatibleObjC = false;8270 QualType ConvertedType;8271 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,8272 IncompatibleObjC);8273}8274 8275void Sema::AddConversionCandidate(8276 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,8277 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,8278 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,8279 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {8280 assert(!Conversion->getDescribedFunctionTemplate() &&8281 "Conversion function templates use AddTemplateConversionCandidate");8282 QualType ConvType = Conversion->getConversionType().getNonReferenceType();8283 if (!CandidateSet.isNewCandidate(Conversion))8284 return;8285 8286 // If the conversion function has an undeduced return type, trigger its8287 // deduction now.8288 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {8289 if (DeduceReturnType(Conversion, From->getExprLoc()))8290 return;8291 ConvType = Conversion->getConversionType().getNonReferenceType();8292 }8293 8294 // If we don't allow any conversion of the result type, ignore conversion8295 // functions that don't convert to exactly (possibly cv-qualified) T.8296 if (!AllowResultConversion &&8297 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))8298 return;8299 8300 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion8301 // operator is only a candidate if its return type is the target type or8302 // can be converted to the target type with a qualification conversion.8303 //8304 // FIXME: Include such functions in the candidate list and explain why we8305 // can't select them.8306 if (Conversion->isExplicit() &&8307 !isAllowableExplicitConversion(*this, ConvType, ToType,8308 AllowObjCConversionOnExplicit))8309 return;8310 8311 // Overload resolution is always an unevaluated context.8312 EnterExpressionEvaluationContext Unevaluated(8313 *this, Sema::ExpressionEvaluationContext::Unevaluated);8314 8315 // Add this candidate8316 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);8317 Candidate.FoundDecl = FoundDecl;8318 Candidate.Function = Conversion;8319 Candidate.FinalConversion.setAsIdentityConversion();8320 Candidate.FinalConversion.setFromType(ConvType);8321 Candidate.FinalConversion.setAllToTypes(ToType);8322 Candidate.HasFinalConversion = true;8323 Candidate.Viable = true;8324 Candidate.ExplicitCallArguments = 1;8325 Candidate.StrictPackMatch = StrictPackMatch;8326 8327 // Explicit functions are not actually candidates at all if we're not8328 // allowing them in this context, but keep them around so we can point8329 // to them in diagnostics.8330 if (!AllowExplicit && Conversion->isExplicit()) {8331 Candidate.Viable = false;8332 Candidate.FailureKind = ovl_fail_explicit;8333 return;8334 }8335 8336 // C++ [over.match.funcs]p4:8337 // For conversion functions, the function is considered to be a member of8338 // the class of the implicit implied object argument for the purpose of8339 // defining the type of the implicit object parameter.8340 //8341 // Determine the implicit conversion sequence for the implicit8342 // object parameter.8343 QualType ObjectType = From->getType();8344 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())8345 ObjectType = FromPtrType->getPointeeType();8346 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();8347 // C++23 [over.best.ics.general]8348 // However, if the target is [...]8349 // - the object parameter of a user-defined conversion function8350 // [...] user-defined conversion sequences are not considered.8351 Candidate.Conversions[0] = TryObjectArgumentInitialization(8352 *this, CandidateSet.getLocation(), From->getType(),8353 From->Classify(Context), Conversion, ConversionContext,8354 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),8355 /*SuppressUserConversion*/ true);8356 8357 if (Candidate.Conversions[0].isBad()) {8358 Candidate.Viable = false;8359 Candidate.FailureKind = ovl_fail_bad_conversion;8360 return;8361 }8362 8363 if (Conversion->getTrailingRequiresClause()) {8364 ConstraintSatisfaction Satisfaction;8365 if (CheckFunctionConstraints(Conversion, Satisfaction) ||8366 !Satisfaction.IsSatisfied) {8367 Candidate.Viable = false;8368 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;8369 return;8370 }8371 }8372 8373 // We won't go through a user-defined type conversion function to convert a8374 // derived to base as such conversions are given Conversion Rank. They only8375 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]8376 QualType FromCanon8377 = Context.getCanonicalType(From->getType().getUnqualifiedType());8378 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();8379 if (FromCanon == ToCanon ||8380 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {8381 Candidate.Viable = false;8382 Candidate.FailureKind = ovl_fail_trivial_conversion;8383 return;8384 }8385 8386 // To determine what the conversion from the result of calling the8387 // conversion function to the type we're eventually trying to8388 // convert to (ToType), we need to synthesize a call to the8389 // conversion function and attempt copy initialization from it. This8390 // makes sure that we get the right semantics with respect to8391 // lvalues/rvalues and the type. Fortunately, we can allocate this8392 // call on the stack and we don't need its arguments to be8393 // well-formed.8394 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),8395 VK_LValue, From->getBeginLoc());8396 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,8397 Context.getPointerType(Conversion->getType()),8398 CK_FunctionToPointerDecay, &ConversionRef,8399 VK_PRValue, FPOptionsOverride());8400 8401 QualType ConversionType = Conversion->getConversionType();8402 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {8403 Candidate.Viable = false;8404 Candidate.FailureKind = ovl_fail_bad_final_conversion;8405 return;8406 }8407 8408 ExprValueKind VK = Expr::getValueKindForType(ConversionType);8409 8410 QualType CallResultType = ConversionType.getNonLValueExprType(Context);8411 8412 // Introduce a temporary expression with the right type and value category8413 // that we can use for deduction purposes.8414 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);8415 8416 ImplicitConversionSequence ICS =8417 TryCopyInitialization(*this, &FakeCall, ToType,8418 /*SuppressUserConversions=*/true,8419 /*InOverloadResolution=*/false,8420 /*AllowObjCWritebackConversion=*/false);8421 8422 switch (ICS.getKind()) {8423 case ImplicitConversionSequence::StandardConversion:8424 Candidate.FinalConversion = ICS.Standard;8425 Candidate.HasFinalConversion = true;8426 8427 // C++ [over.ics.user]p3:8428 // If the user-defined conversion is specified by a specialization of a8429 // conversion function template, the second standard conversion sequence8430 // shall have exact match rank.8431 if (Conversion->getPrimaryTemplate() &&8432 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {8433 Candidate.Viable = false;8434 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;8435 return;8436 }8437 8438 // C++0x [dcl.init.ref]p5:8439 // In the second case, if the reference is an rvalue reference and8440 // the second standard conversion sequence of the user-defined8441 // conversion sequence includes an lvalue-to-rvalue conversion, the8442 // program is ill-formed.8443 if (ToType->isRValueReferenceType() &&8444 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {8445 Candidate.Viable = false;8446 Candidate.FailureKind = ovl_fail_bad_final_conversion;8447 return;8448 }8449 break;8450 8451 case ImplicitConversionSequence::BadConversion:8452 Candidate.Viable = false;8453 Candidate.FailureKind = ovl_fail_bad_final_conversion;8454 return;8455 8456 default:8457 llvm_unreachable(8458 "Can only end up with a standard conversion sequence or failure");8459 }8460 8461 if (EnableIfAttr *FailedAttr =8462 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {8463 Candidate.Viable = false;8464 Candidate.FailureKind = ovl_fail_enable_if;8465 Candidate.DeductionFailure.Data = FailedAttr;8466 return;8467 }8468 8469 if (isNonViableMultiVersionOverload(Conversion)) {8470 Candidate.Viable = false;8471 Candidate.FailureKind = ovl_non_default_multiversion_function;8472 }8473}8474 8475static void AddTemplateConversionCandidateImmediately(8476 Sema &S, OverloadCandidateSet &CandidateSet,8477 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,8478 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,8479 bool AllowObjCConversionOnExplicit, bool AllowExplicit,8480 bool AllowResultConversion) {8481 8482 // If the function template has a non-dependent explicit specification,8483 // exclude it now if appropriate; we are not permitted to perform deduction8484 // and substitution in this case.8485 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {8486 OverloadCandidate &Candidate = CandidateSet.addCandidate();8487 Candidate.FoundDecl = FoundDecl;8488 Candidate.Function = FunctionTemplate->getTemplatedDecl();8489 Candidate.Viable = false;8490 Candidate.FailureKind = ovl_fail_explicit;8491 return;8492 }8493 8494 QualType ObjectType = From->getType();8495 Expr::Classification ObjectClassification = From->Classify(S.Context);8496 8497 TemplateDeductionInfo Info(CandidateSet.getLocation());8498 CXXConversionDecl *Specialization = nullptr;8499 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(8500 FunctionTemplate, ObjectType, ObjectClassification, ToType,8501 Specialization, Info);8502 Result != TemplateDeductionResult::Success) {8503 OverloadCandidate &Candidate = CandidateSet.addCandidate();8504 Candidate.FoundDecl = FoundDecl;8505 Candidate.Function = FunctionTemplate->getTemplatedDecl();8506 Candidate.Viable = false;8507 Candidate.FailureKind = ovl_fail_bad_deduction;8508 Candidate.ExplicitCallArguments = 1;8509 Candidate.DeductionFailure =8510 MakeDeductionFailureInfo(S.Context, Result, Info);8511 return;8512 }8513 8514 // Add the conversion function template specialization produced by8515 // template argument deduction as a candidate.8516 assert(Specialization && "Missing function template specialization?");8517 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,8518 ToType, CandidateSet, AllowObjCConversionOnExplicit,8519 AllowExplicit, AllowResultConversion,8520 Info.hasStrictPackMatch());8521}8522 8523void Sema::AddTemplateConversionCandidate(8524 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,8525 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,8526 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,8527 bool AllowExplicit, bool AllowResultConversion) {8528 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&8529 "Only conversion function templates permitted here");8530 8531 if (!CandidateSet.isNewCandidate(FunctionTemplate))8532 return;8533 8534 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts()) ||8535 CandidateSet.getKind() ==8536 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||8537 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {8538 AddTemplateConversionCandidateImmediately(8539 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,8540 ToType, AllowObjCConversionOnExplicit, AllowExplicit,8541 AllowResultConversion);8542 8543 CandidateSet.DisableResolutionByPerfectCandidate();8544 return;8545 }8546 8547 CandidateSet.AddDeferredConversionTemplateCandidate(8548 FunctionTemplate, FoundDecl, ActingDC, From, ToType,8549 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);8550}8551 8552void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,8553 DeclAccessPair FoundDecl,8554 CXXRecordDecl *ActingContext,8555 const FunctionProtoType *Proto,8556 Expr *Object,8557 ArrayRef<Expr *> Args,8558 OverloadCandidateSet& CandidateSet) {8559 if (!CandidateSet.isNewCandidate(Conversion))8560 return;8561 8562 // Overload resolution is always an unevaluated context.8563 EnterExpressionEvaluationContext Unevaluated(8564 *this, Sema::ExpressionEvaluationContext::Unevaluated);8565 8566 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);8567 Candidate.FoundDecl = FoundDecl;8568 Candidate.Function = nullptr;8569 Candidate.Surrogate = Conversion;8570 Candidate.IsSurrogate = true;8571 Candidate.Viable = true;8572 Candidate.ExplicitCallArguments = Args.size();8573 8574 // Determine the implicit conversion sequence for the implicit8575 // object parameter.8576 ImplicitConversionSequence ObjectInit;8577 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {8578 ObjectInit = TryCopyInitialization(*this, Object,8579 Conversion->getParamDecl(0)->getType(),8580 /*SuppressUserConversions=*/false,8581 /*InOverloadResolution=*/true, false);8582 } else {8583 ObjectInit = TryObjectArgumentInitialization(8584 *this, CandidateSet.getLocation(), Object->getType(),8585 Object->Classify(Context), Conversion, ActingContext);8586 }8587 8588 if (ObjectInit.isBad()) {8589 Candidate.Viable = false;8590 Candidate.FailureKind = ovl_fail_bad_conversion;8591 Candidate.Conversions[0] = ObjectInit;8592 return;8593 }8594 8595 // The first conversion is actually a user-defined conversion whose8596 // first conversion is ObjectInit's standard conversion (which is8597 // effectively a reference binding). Record it as such.8598 Candidate.Conversions[0].setUserDefined();8599 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;8600 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;8601 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;8602 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;8603 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;8604 Candidate.Conversions[0].UserDefined.After8605 = Candidate.Conversions[0].UserDefined.Before;8606 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();8607 8608 // Find the8609 unsigned NumParams = Proto->getNumParams();8610 8611 // (C++ 13.3.2p2): A candidate function having fewer than m8612 // parameters is viable only if it has an ellipsis in its parameter8613 // list (8.3.5).8614 if (Args.size() > NumParams && !Proto->isVariadic()) {8615 Candidate.Viable = false;8616 Candidate.FailureKind = ovl_fail_too_many_arguments;8617 return;8618 }8619 8620 // Function types don't have any default arguments, so just check if8621 // we have enough arguments.8622 if (Args.size() < NumParams) {8623 // Not enough arguments.8624 Candidate.Viable = false;8625 Candidate.FailureKind = ovl_fail_too_few_arguments;8626 return;8627 }8628 8629 // Determine the implicit conversion sequences for each of the8630 // arguments.8631 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {8632 if (ArgIdx < NumParams) {8633 // (C++ 13.3.2p3): for F to be a viable function, there shall8634 // exist for each argument an implicit conversion sequence8635 // (13.3.3.1) that converts that argument to the corresponding8636 // parameter of F.8637 QualType ParamType = Proto->getParamType(ArgIdx);8638 Candidate.Conversions[ArgIdx + 1]8639 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,8640 /*SuppressUserConversions=*/false,8641 /*InOverloadResolution=*/false,8642 /*AllowObjCWritebackConversion=*/8643 getLangOpts().ObjCAutoRefCount);8644 if (Candidate.Conversions[ArgIdx + 1].isBad()) {8645 Candidate.Viable = false;8646 Candidate.FailureKind = ovl_fail_bad_conversion;8647 return;8648 }8649 } else {8650 // (C++ 13.3.2p2): For the purposes of overload resolution, any8651 // argument for which there is no corresponding parameter is8652 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).8653 Candidate.Conversions[ArgIdx + 1].setEllipsis();8654 }8655 }8656 8657 if (Conversion->getTrailingRequiresClause()) {8658 ConstraintSatisfaction Satisfaction;8659 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},8660 /*ForOverloadResolution*/ true) ||8661 !Satisfaction.IsSatisfied) {8662 Candidate.Viable = false;8663 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;8664 return;8665 }8666 }8667 8668 if (EnableIfAttr *FailedAttr =8669 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {8670 Candidate.Viable = false;8671 Candidate.FailureKind = ovl_fail_enable_if;8672 Candidate.DeductionFailure.Data = FailedAttr;8673 return;8674 }8675}8676 8677void Sema::AddNonMemberOperatorCandidates(8678 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,8679 OverloadCandidateSet &CandidateSet,8680 TemplateArgumentListInfo *ExplicitTemplateArgs) {8681 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {8682 NamedDecl *D = F.getDecl()->getUnderlyingDecl();8683 ArrayRef<Expr *> FunctionArgs = Args;8684 8685 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);8686 FunctionDecl *FD =8687 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);8688 8689 // Don't consider rewritten functions if we're not rewriting.8690 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))8691 continue;8692 8693 assert(!isa<CXXMethodDecl>(FD) &&8694 "unqualified operator lookup found a member function");8695 8696 if (FunTmpl) {8697 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,8698 FunctionArgs, CandidateSet);8699 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {8700 8701 // As template candidates are not deduced immediately,8702 // persist the array in the overload set.8703 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(8704 FunctionArgs[1], FunctionArgs[0]);8705 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,8706 Reversed, CandidateSet, false, false, true,8707 ADLCallKind::NotADL,8708 OverloadCandidateParamOrder::Reversed);8709 }8710 } else {8711 if (ExplicitTemplateArgs)8712 continue;8713 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);8714 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))8715 AddOverloadCandidate(FD, F.getPair(),8716 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,8717 false, false, true, false, ADLCallKind::NotADL, {},8718 OverloadCandidateParamOrder::Reversed);8719 }8720 }8721}8722 8723void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,8724 SourceLocation OpLoc,8725 ArrayRef<Expr *> Args,8726 OverloadCandidateSet &CandidateSet,8727 OverloadCandidateParamOrder PO) {8728 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);8729 8730 // C++ [over.match.oper]p3:8731 // For a unary operator @ with an operand of a type whose8732 // cv-unqualified version is T1, and for a binary operator @ with8733 // a left operand of a type whose cv-unqualified version is T1 and8734 // a right operand of a type whose cv-unqualified version is T2,8735 // three sets of candidate functions, designated member8736 // candidates, non-member candidates and built-in candidates, are8737 // constructed as follows:8738 QualType T1 = Args[0]->getType();8739 8740 // -- If T1 is a complete class type or a class currently being8741 // defined, the set of member candidates is the result of the8742 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,8743 // the set of member candidates is empty.8744 if (T1->isRecordType()) {8745 bool IsComplete = isCompleteType(OpLoc, T1);8746 auto *T1RD = T1->getAsCXXRecordDecl();8747 // Complete the type if it can be completed.8748 // If the type is neither complete nor being defined, bail out now.8749 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))8750 return;8751 8752 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);8753 LookupQualifiedName(Operators, T1RD);8754 Operators.suppressAccessDiagnostics();8755 8756 for (LookupResult::iterator Oper = Operators.begin(),8757 OperEnd = Operators.end();8758 Oper != OperEnd; ++Oper) {8759 if (Oper->getAsFunction() &&8760 PO == OverloadCandidateParamOrder::Reversed &&8761 !CandidateSet.getRewriteInfo().shouldAddReversed(8762 *this, {Args[1], Args[0]}, Oper->getAsFunction()))8763 continue;8764 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),8765 Args[0]->Classify(Context), Args.slice(1),8766 CandidateSet, /*SuppressUserConversion=*/false, PO);8767 }8768 }8769}8770 8771void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,8772 OverloadCandidateSet& CandidateSet,8773 bool IsAssignmentOperator,8774 unsigned NumContextualBoolArguments) {8775 // Overload resolution is always an unevaluated context.8776 EnterExpressionEvaluationContext Unevaluated(8777 *this, Sema::ExpressionEvaluationContext::Unevaluated);8778 8779 // Add this candidate8780 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());8781 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);8782 Candidate.Function = nullptr;8783 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);8784 8785 // Determine the implicit conversion sequences for each of the8786 // arguments.8787 Candidate.Viable = true;8788 Candidate.ExplicitCallArguments = Args.size();8789 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {8790 // C++ [over.match.oper]p4:8791 // For the built-in assignment operators, conversions of the8792 // left operand are restricted as follows:8793 // -- no temporaries are introduced to hold the left operand, and8794 // -- no user-defined conversions are applied to the left8795 // operand to achieve a type match with the left-most8796 // parameter of a built-in candidate.8797 //8798 // We block these conversions by turning off user-defined8799 // conversions, since that is the only way that initialization of8800 // a reference to a non-class type can occur from something that8801 // is not of the same type.8802 if (ArgIdx < NumContextualBoolArguments) {8803 assert(ParamTys[ArgIdx] == Context.BoolTy &&8804 "Contextual conversion to bool requires bool type");8805 Candidate.Conversions[ArgIdx]8806 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);8807 } else {8808 Candidate.Conversions[ArgIdx]8809 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],8810 ArgIdx == 0 && IsAssignmentOperator,8811 /*InOverloadResolution=*/false,8812 /*AllowObjCWritebackConversion=*/8813 getLangOpts().ObjCAutoRefCount);8814 }8815 if (Candidate.Conversions[ArgIdx].isBad()) {8816 Candidate.Viable = false;8817 Candidate.FailureKind = ovl_fail_bad_conversion;8818 break;8819 }8820 }8821}8822 8823namespace {8824 8825/// BuiltinCandidateTypeSet - A set of types that will be used for the8826/// candidate operator functions for built-in operators (C++8827/// [over.built]). The types are separated into pointer types and8828/// enumeration types.8829class BuiltinCandidateTypeSet {8830 /// TypeSet - A set of types.8831 typedef llvm::SmallSetVector<QualType, 8> TypeSet;8832 8833 /// PointerTypes - The set of pointer types that will be used in the8834 /// built-in candidates.8835 TypeSet PointerTypes;8836 8837 /// MemberPointerTypes - The set of member pointer types that will be8838 /// used in the built-in candidates.8839 TypeSet MemberPointerTypes;8840 8841 /// EnumerationTypes - The set of enumeration types that will be8842 /// used in the built-in candidates.8843 TypeSet EnumerationTypes;8844 8845 /// The set of vector types that will be used in the built-in8846 /// candidates.8847 TypeSet VectorTypes;8848 8849 /// The set of matrix types that will be used in the built-in8850 /// candidates.8851 TypeSet MatrixTypes;8852 8853 /// The set of _BitInt types that will be used in the built-in candidates.8854 TypeSet BitIntTypes;8855 8856 /// A flag indicating non-record types are viable candidates8857 bool HasNonRecordTypes;8858 8859 /// A flag indicating whether either arithmetic or enumeration types8860 /// were present in the candidate set.8861 bool HasArithmeticOrEnumeralTypes;8862 8863 /// A flag indicating whether the nullptr type was present in the8864 /// candidate set.8865 bool HasNullPtrType;8866 8867 /// Sema - The semantic analysis instance where we are building the8868 /// candidate type set.8869 Sema &SemaRef;8870 8871 /// Context - The AST context in which we will build the type sets.8872 ASTContext &Context;8873 8874 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,8875 const Qualifiers &VisibleQuals);8876 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);8877 8878public:8879 /// iterator - Iterates through the types that are part of the set.8880 typedef TypeSet::iterator iterator;8881 8882 BuiltinCandidateTypeSet(Sema &SemaRef)8883 : HasNonRecordTypes(false),8884 HasArithmeticOrEnumeralTypes(false),8885 HasNullPtrType(false),8886 SemaRef(SemaRef),8887 Context(SemaRef.Context) { }8888 8889 void AddTypesConvertedFrom(QualType Ty,8890 SourceLocation Loc,8891 bool AllowUserConversions,8892 bool AllowExplicitConversions,8893 const Qualifiers &VisibleTypeConversionsQuals);8894 8895 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }8896 llvm::iterator_range<iterator> member_pointer_types() {8897 return MemberPointerTypes;8898 }8899 llvm::iterator_range<iterator> enumeration_types() {8900 return EnumerationTypes;8901 }8902 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }8903 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }8904 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }8905 8906 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }8907 bool hasNonRecordTypes() { return HasNonRecordTypes; }8908 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }8909 bool hasNullPtrType() const { return HasNullPtrType; }8910};8911 8912} // end anonymous namespace8913 8914/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to8915/// the set of pointer types along with any more-qualified variants of8916/// that type. For example, if @p Ty is "int const *", this routine8917/// will add "int const *", "int const volatile *", "int const8918/// restrict *", and "int const volatile restrict *" to the set of8919/// pointer types. Returns true if the add of @p Ty itself succeeded,8920/// false otherwise.8921///8922/// FIXME: what to do about extended qualifiers?8923bool8924BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,8925 const Qualifiers &VisibleQuals) {8926 8927 // Insert this type.8928 if (!PointerTypes.insert(Ty))8929 return false;8930 8931 QualType PointeeTy;8932 const PointerType *PointerTy = Ty->getAs<PointerType>();8933 bool buildObjCPtr = false;8934 if (!PointerTy) {8935 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();8936 PointeeTy = PTy->getPointeeType();8937 buildObjCPtr = true;8938 } else {8939 PointeeTy = PointerTy->getPointeeType();8940 }8941 8942 // Don't add qualified variants of arrays. For one, they're not allowed8943 // (the qualifier would sink to the element type), and for another, the8944 // only overload situation where it matters is subscript or pointer +- int,8945 // and those shouldn't have qualifier variants anyway.8946 if (PointeeTy->isArrayType())8947 return true;8948 8949 unsigned BaseCVR = PointeeTy.getCVRQualifiers();8950 bool hasVolatile = VisibleQuals.hasVolatile();8951 bool hasRestrict = VisibleQuals.hasRestrict();8952 8953 // Iterate through all strict supersets of BaseCVR.8954 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {8955 if ((CVR | BaseCVR) != CVR) continue;8956 // Skip over volatile if no volatile found anywhere in the types.8957 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;8958 8959 // Skip over restrict if no restrict found anywhere in the types, or if8960 // the type cannot be restrict-qualified.8961 if ((CVR & Qualifiers::Restrict) &&8962 (!hasRestrict ||8963 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))8964 continue;8965 8966 // Build qualified pointee type.8967 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);8968 8969 // Build qualified pointer type.8970 QualType QPointerTy;8971 if (!buildObjCPtr)8972 QPointerTy = Context.getPointerType(QPointeeTy);8973 else8974 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);8975 8976 // Insert qualified pointer type.8977 PointerTypes.insert(QPointerTy);8978 }8979 8980 return true;8981}8982 8983/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty8984/// to the set of pointer types along with any more-qualified variants of8985/// that type. For example, if @p Ty is "int const *", this routine8986/// will add "int const *", "int const volatile *", "int const8987/// restrict *", and "int const volatile restrict *" to the set of8988/// pointer types. Returns true if the add of @p Ty itself succeeded,8989/// false otherwise.8990///8991/// FIXME: what to do about extended qualifiers?8992bool8993BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(8994 QualType Ty) {8995 // Insert this type.8996 if (!MemberPointerTypes.insert(Ty))8997 return false;8998 8999 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();9000 assert(PointerTy && "type was not a member pointer type!");9001 9002 QualType PointeeTy = PointerTy->getPointeeType();9003 // Don't add qualified variants of arrays. For one, they're not allowed9004 // (the qualifier would sink to the element type), and for another, the9005 // only overload situation where it matters is subscript or pointer +- int,9006 // and those shouldn't have qualifier variants anyway.9007 if (PointeeTy->isArrayType())9008 return true;9009 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();9010 9011 // Iterate through all strict supersets of the pointee type's CVR9012 // qualifiers.9013 unsigned BaseCVR = PointeeTy.getCVRQualifiers();9014 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {9015 if ((CVR | BaseCVR) != CVR) continue;9016 9017 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);9018 MemberPointerTypes.insert(Context.getMemberPointerType(9019 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));9020 }9021 9022 return true;9023}9024 9025/// AddTypesConvertedFrom - Add each of the types to which the type @p9026/// Ty can be implicit converted to the given set of @p Types. We're9027/// primarily interested in pointer types and enumeration types. We also9028/// take member pointer types, for the conditional operator.9029/// AllowUserConversions is true if we should look at the conversion9030/// functions of a class type, and AllowExplicitConversions if we9031/// should also include the explicit conversion functions of a class9032/// type.9033void9034BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,9035 SourceLocation Loc,9036 bool AllowUserConversions,9037 bool AllowExplicitConversions,9038 const Qualifiers &VisibleQuals) {9039 // Only deal with canonical types.9040 Ty = Context.getCanonicalType(Ty);9041 9042 // Look through reference types; they aren't part of the type of an9043 // expression for the purposes of conversions.9044 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())9045 Ty = RefTy->getPointeeType();9046 9047 // If we're dealing with an array type, decay to the pointer.9048 if (Ty->isArrayType())9049 Ty = SemaRef.Context.getArrayDecayedType(Ty);9050 9051 // Otherwise, we don't care about qualifiers on the type.9052 Ty = Ty.getLocalUnqualifiedType();9053 9054 // Flag if we ever add a non-record type.9055 bool TyIsRec = Ty->isRecordType();9056 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;9057 9058 // Flag if we encounter an arithmetic type.9059 HasArithmeticOrEnumeralTypes =9060 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();9061 9062 if (Ty->isObjCIdType() || Ty->isObjCClassType())9063 PointerTypes.insert(Ty);9064 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {9065 // Insert our type, and its more-qualified variants, into the set9066 // of types.9067 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))9068 return;9069 } else if (Ty->isMemberPointerType()) {9070 // Member pointers are far easier, since the pointee can't be converted.9071 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))9072 return;9073 } else if (Ty->isEnumeralType()) {9074 HasArithmeticOrEnumeralTypes = true;9075 EnumerationTypes.insert(Ty);9076 } else if (Ty->isBitIntType()) {9077 HasArithmeticOrEnumeralTypes = true;9078 BitIntTypes.insert(Ty);9079 } else if (Ty->isVectorType()) {9080 // We treat vector types as arithmetic types in many contexts as an9081 // extension.9082 HasArithmeticOrEnumeralTypes = true;9083 VectorTypes.insert(Ty);9084 } else if (Ty->isMatrixType()) {9085 // Similar to vector types, we treat vector types as arithmetic types in9086 // many contexts as an extension.9087 HasArithmeticOrEnumeralTypes = true;9088 MatrixTypes.insert(Ty);9089 } else if (Ty->isNullPtrType()) {9090 HasNullPtrType = true;9091 } else if (AllowUserConversions && TyIsRec) {9092 // No conversion functions in incomplete types.9093 if (!SemaRef.isCompleteType(Loc, Ty))9094 return;9095 9096 auto *ClassDecl = Ty->castAsCXXRecordDecl();9097 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {9098 if (isa<UsingShadowDecl>(D))9099 D = cast<UsingShadowDecl>(D)->getTargetDecl();9100 9101 // Skip conversion function templates; they don't tell us anything9102 // about which builtin types we can convert to.9103 if (isa<FunctionTemplateDecl>(D))9104 continue;9105 9106 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);9107 if (AllowExplicitConversions || !Conv->isExplicit()) {9108 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,9109 VisibleQuals);9110 }9111 }9112 }9113}9114/// Helper function for adjusting address spaces for the pointer or reference9115/// operands of builtin operators depending on the argument.9116static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,9117 Expr *Arg) {9118 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());9119}9120 9121/// Helper function for AddBuiltinOperatorCandidates() that adds9122/// the volatile- and non-volatile-qualified assignment operators for the9123/// given type to the candidate set.9124static void AddBuiltinAssignmentOperatorCandidates(Sema &S,9125 QualType T,9126 ArrayRef<Expr *> Args,9127 OverloadCandidateSet &CandidateSet) {9128 QualType ParamTypes[2];9129 9130 // T& operator=(T&, T)9131 ParamTypes[0] = S.Context.getLValueReferenceType(9132 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));9133 ParamTypes[1] = T;9134 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9135 /*IsAssignmentOperator=*/true);9136 9137 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {9138 // volatile T& operator=(volatile T&, T)9139 ParamTypes[0] = S.Context.getLValueReferenceType(9140 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),9141 Args[0]));9142 ParamTypes[1] = T;9143 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9144 /*IsAssignmentOperator=*/true);9145 }9146}9147 9148/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,9149/// if any, found in visible type conversion functions found in ArgExpr's type.9150static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {9151 Qualifiers VRQuals;9152 CXXRecordDecl *ClassDecl;9153 if (const MemberPointerType *RHSMPType =9154 ArgExpr->getType()->getAs<MemberPointerType>())9155 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();9156 else9157 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();9158 if (!ClassDecl) {9159 // Just to be safe, assume the worst case.9160 VRQuals.addVolatile();9161 VRQuals.addRestrict();9162 return VRQuals;9163 }9164 if (!ClassDecl->hasDefinition())9165 return VRQuals;9166 9167 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {9168 if (isa<UsingShadowDecl>(D))9169 D = cast<UsingShadowDecl>(D)->getTargetDecl();9170 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {9171 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());9172 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())9173 CanTy = ResTypeRef->getPointeeType();9174 // Need to go down the pointer/mempointer chain and add qualifiers9175 // as see them.9176 bool done = false;9177 while (!done) {9178 if (CanTy.isRestrictQualified())9179 VRQuals.addRestrict();9180 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())9181 CanTy = ResTypePtr->getPointeeType();9182 else if (const MemberPointerType *ResTypeMPtr =9183 CanTy->getAs<MemberPointerType>())9184 CanTy = ResTypeMPtr->getPointeeType();9185 else9186 done = true;9187 if (CanTy.isVolatileQualified())9188 VRQuals.addVolatile();9189 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())9190 return VRQuals;9191 }9192 }9193 }9194 return VRQuals;9195}9196 9197// Note: We're currently only handling qualifiers that are meaningful for the9198// LHS of compound assignment overloading.9199static void forAllQualifierCombinationsImpl(9200 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,9201 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {9202 // _Atomic9203 if (Available.hasAtomic()) {9204 Available.removeAtomic();9205 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);9206 forAllQualifierCombinationsImpl(Available, Applied, Callback);9207 return;9208 }9209 9210 // volatile9211 if (Available.hasVolatile()) {9212 Available.removeVolatile();9213 assert(!Applied.hasVolatile());9214 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),9215 Callback);9216 forAllQualifierCombinationsImpl(Available, Applied, Callback);9217 return;9218 }9219 9220 Callback(Applied);9221}9222 9223static void forAllQualifierCombinations(9224 QualifiersAndAtomic Quals,9225 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {9226 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),9227 Callback);9228}9229 9230static QualType makeQualifiedLValueReferenceType(QualType Base,9231 QualifiersAndAtomic Quals,9232 Sema &S) {9233 if (Quals.hasAtomic())9234 Base = S.Context.getAtomicType(Base);9235 if (Quals.hasVolatile())9236 Base = S.Context.getVolatileType(Base);9237 return S.Context.getLValueReferenceType(Base);9238}9239 9240namespace {9241 9242/// Helper class to manage the addition of builtin operator overload9243/// candidates. It provides shared state and utility methods used throughout9244/// the process, as well as a helper method to add each group of builtin9245/// operator overloads from the standard to a candidate set.9246class BuiltinOperatorOverloadBuilder {9247 // Common instance state available to all overload candidate addition methods.9248 Sema &S;9249 ArrayRef<Expr *> Args;9250 QualifiersAndAtomic VisibleTypeConversionsQuals;9251 bool HasArithmeticOrEnumeralCandidateType;9252 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;9253 OverloadCandidateSet &CandidateSet;9254 9255 static constexpr int ArithmeticTypesCap = 26;9256 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;9257 9258 // Define some indices used to iterate over the arithmetic types in9259 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic9260 // types are that preserved by promotion (C++ [over.built]p2).9261 unsigned FirstIntegralType,9262 LastIntegralType;9263 unsigned FirstPromotedIntegralType,9264 LastPromotedIntegralType;9265 unsigned FirstPromotedArithmeticType,9266 LastPromotedArithmeticType;9267 unsigned NumArithmeticTypes;9268 9269 void InitArithmeticTypes() {9270 // Start of promoted types.9271 FirstPromotedArithmeticType = 0;9272 ArithmeticTypes.push_back(S.Context.FloatTy);9273 ArithmeticTypes.push_back(S.Context.DoubleTy);9274 ArithmeticTypes.push_back(S.Context.LongDoubleTy);9275 if (S.Context.getTargetInfo().hasFloat128Type())9276 ArithmeticTypes.push_back(S.Context.Float128Ty);9277 if (S.Context.getTargetInfo().hasIbm128Type())9278 ArithmeticTypes.push_back(S.Context.Ibm128Ty);9279 9280 // Start of integral types.9281 FirstIntegralType = ArithmeticTypes.size();9282 FirstPromotedIntegralType = ArithmeticTypes.size();9283 ArithmeticTypes.push_back(S.Context.IntTy);9284 ArithmeticTypes.push_back(S.Context.LongTy);9285 ArithmeticTypes.push_back(S.Context.LongLongTy);9286 if (S.Context.getTargetInfo().hasInt128Type() ||9287 (S.Context.getAuxTargetInfo() &&9288 S.Context.getAuxTargetInfo()->hasInt128Type()))9289 ArithmeticTypes.push_back(S.Context.Int128Ty);9290 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);9291 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);9292 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);9293 if (S.Context.getTargetInfo().hasInt128Type() ||9294 (S.Context.getAuxTargetInfo() &&9295 S.Context.getAuxTargetInfo()->hasInt128Type()))9296 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);9297 9298 /// We add candidates for the unique, unqualified _BitInt types present in9299 /// the candidate type set. The candidate set already handled ensuring the9300 /// type is unqualified and canonical, but because we're adding from N9301 /// different sets, we need to do some extra work to unique things. Insert9302 /// the candidates into a unique set, then move from that set into the list9303 /// of arithmetic types.9304 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;9305 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {9306 for (QualType BitTy : Candidate.bitint_types())9307 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));9308 }9309 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));9310 LastPromotedIntegralType = ArithmeticTypes.size();9311 LastPromotedArithmeticType = ArithmeticTypes.size();9312 // End of promoted types.9313 9314 ArithmeticTypes.push_back(S.Context.BoolTy);9315 ArithmeticTypes.push_back(S.Context.CharTy);9316 ArithmeticTypes.push_back(S.Context.WCharTy);9317 if (S.Context.getLangOpts().Char8)9318 ArithmeticTypes.push_back(S.Context.Char8Ty);9319 ArithmeticTypes.push_back(S.Context.Char16Ty);9320 ArithmeticTypes.push_back(S.Context.Char32Ty);9321 ArithmeticTypes.push_back(S.Context.SignedCharTy);9322 ArithmeticTypes.push_back(S.Context.ShortTy);9323 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);9324 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);9325 LastIntegralType = ArithmeticTypes.size();9326 NumArithmeticTypes = ArithmeticTypes.size();9327 // End of integral types.9328 // FIXME: What about complex? What about half?9329 9330 // We don't know for sure how many bit-precise candidates were involved, so9331 // we subtract those from the total when testing whether we're under the9332 // cap or not.9333 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=9334 ArithmeticTypesCap &&9335 "Enough inline storage for all arithmetic types.");9336 }9337 9338 /// Helper method to factor out the common pattern of adding overloads9339 /// for '++' and '--' builtin operators.9340 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,9341 bool HasVolatile,9342 bool HasRestrict) {9343 QualType ParamTypes[2] = {9344 S.Context.getLValueReferenceType(CandidateTy),9345 S.Context.IntTy9346 };9347 9348 // Non-volatile version.9349 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9350 9351 // Use a heuristic to reduce number of builtin candidates in the set:9352 // add volatile version only if there are conversions to a volatile type.9353 if (HasVolatile) {9354 ParamTypes[0] =9355 S.Context.getLValueReferenceType(9356 S.Context.getVolatileType(CandidateTy));9357 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9358 }9359 9360 // Add restrict version only if there are conversions to a restrict type9361 // and our candidate type is a non-restrict-qualified pointer.9362 if (HasRestrict && CandidateTy->isAnyPointerType() &&9363 !CandidateTy.isRestrictQualified()) {9364 ParamTypes[0]9365 = S.Context.getLValueReferenceType(9366 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));9367 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9368 9369 if (HasVolatile) {9370 ParamTypes[0]9371 = S.Context.getLValueReferenceType(9372 S.Context.getCVRQualifiedType(CandidateTy,9373 (Qualifiers::Volatile |9374 Qualifiers::Restrict)));9375 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9376 }9377 }9378 9379 }9380 9381 /// Helper to add an overload candidate for a binary builtin with types \p L9382 /// and \p R.9383 void AddCandidate(QualType L, QualType R) {9384 QualType LandR[2] = {L, R};9385 S.AddBuiltinCandidate(LandR, Args, CandidateSet);9386 }9387 9388public:9389 BuiltinOperatorOverloadBuilder(9390 Sema &S, ArrayRef<Expr *> Args,9391 QualifiersAndAtomic VisibleTypeConversionsQuals,9392 bool HasArithmeticOrEnumeralCandidateType,9393 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,9394 OverloadCandidateSet &CandidateSet)9395 : S(S), Args(Args),9396 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),9397 HasArithmeticOrEnumeralCandidateType(9398 HasArithmeticOrEnumeralCandidateType),9399 CandidateTypes(CandidateTypes),9400 CandidateSet(CandidateSet) {9401 9402 InitArithmeticTypes();9403 }9404 9405 // Increment is deprecated for bool since C++17.9406 //9407 // C++ [over.built]p3:9408 //9409 // For every pair (T, VQ), where T is an arithmetic type other9410 // than bool, and VQ is either volatile or empty, there exist9411 // candidate operator functions of the form9412 //9413 // VQ T& operator++(VQ T&);9414 // T operator++(VQ T&, int);9415 //9416 // C++ [over.built]p4:9417 //9418 // For every pair (T, VQ), where T is an arithmetic type other9419 // than bool, and VQ is either volatile or empty, there exist9420 // candidate operator functions of the form9421 //9422 // VQ T& operator--(VQ T&);9423 // T operator--(VQ T&, int);9424 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {9425 if (!HasArithmeticOrEnumeralCandidateType)9426 return;9427 9428 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {9429 const auto TypeOfT = ArithmeticTypes[Arith];9430 if (TypeOfT == S.Context.BoolTy) {9431 if (Op == OO_MinusMinus)9432 continue;9433 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)9434 continue;9435 }9436 addPlusPlusMinusMinusStyleOverloads(9437 TypeOfT,9438 VisibleTypeConversionsQuals.hasVolatile(),9439 VisibleTypeConversionsQuals.hasRestrict());9440 }9441 }9442 9443 // C++ [over.built]p5:9444 //9445 // For every pair (T, VQ), where T is a cv-qualified or9446 // cv-unqualified object type, and VQ is either volatile or9447 // empty, there exist candidate operator functions of the form9448 //9449 // T*VQ& operator++(T*VQ&);9450 // T*VQ& operator--(T*VQ&);9451 // T* operator++(T*VQ&, int);9452 // T* operator--(T*VQ&, int);9453 void addPlusPlusMinusMinusPointerOverloads() {9454 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {9455 // Skip pointer types that aren't pointers to object types.9456 if (!PtrTy->getPointeeType()->isObjectType())9457 continue;9458 9459 addPlusPlusMinusMinusStyleOverloads(9460 PtrTy,9461 (!PtrTy.isVolatileQualified() &&9462 VisibleTypeConversionsQuals.hasVolatile()),9463 (!PtrTy.isRestrictQualified() &&9464 VisibleTypeConversionsQuals.hasRestrict()));9465 }9466 }9467 9468 // C++ [over.built]p6:9469 // For every cv-qualified or cv-unqualified object type T, there9470 // exist candidate operator functions of the form9471 //9472 // T& operator*(T*);9473 //9474 // C++ [over.built]p7:9475 // For every function type T that does not have cv-qualifiers or a9476 // ref-qualifier, there exist candidate operator functions of the form9477 // T& operator*(T*);9478 void addUnaryStarPointerOverloads() {9479 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {9480 QualType PointeeTy = ParamTy->getPointeeType();9481 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())9482 continue;9483 9484 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())9485 if (Proto->getMethodQuals() || Proto->getRefQualifier())9486 continue;9487 9488 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);9489 }9490 }9491 9492 // C++ [over.built]p9:9493 // For every promoted arithmetic type T, there exist candidate9494 // operator functions of the form9495 //9496 // T operator+(T);9497 // T operator-(T);9498 void addUnaryPlusOrMinusArithmeticOverloads() {9499 if (!HasArithmeticOrEnumeralCandidateType)9500 return;9501 9502 for (unsigned Arith = FirstPromotedArithmeticType;9503 Arith < LastPromotedArithmeticType; ++Arith) {9504 QualType ArithTy = ArithmeticTypes[Arith];9505 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);9506 }9507 9508 // Extension: We also add these operators for vector types.9509 for (QualType VecTy : CandidateTypes[0].vector_types())9510 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);9511 }9512 9513 // C++ [over.built]p8:9514 // For every type T, there exist candidate operator functions of9515 // the form9516 //9517 // T* operator+(T*);9518 void addUnaryPlusPointerOverloads() {9519 for (QualType ParamTy : CandidateTypes[0].pointer_types())9520 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);9521 }9522 9523 // C++ [over.built]p10:9524 // For every promoted integral type T, there exist candidate9525 // operator functions of the form9526 //9527 // T operator~(T);9528 void addUnaryTildePromotedIntegralOverloads() {9529 if (!HasArithmeticOrEnumeralCandidateType)9530 return;9531 9532 for (unsigned Int = FirstPromotedIntegralType;9533 Int < LastPromotedIntegralType; ++Int) {9534 QualType IntTy = ArithmeticTypes[Int];9535 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);9536 }9537 9538 // Extension: We also add this operator for vector types.9539 for (QualType VecTy : CandidateTypes[0].vector_types())9540 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);9541 }9542 9543 // C++ [over.match.oper]p16:9544 // For every pointer to member type T or type std::nullptr_t, there9545 // exist candidate operator functions of the form9546 //9547 // bool operator==(T,T);9548 // bool operator!=(T,T);9549 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {9550 /// Set of (canonical) types that we've already handled.9551 llvm::SmallPtrSet<QualType, 8> AddedTypes;9552 9553 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {9554 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {9555 // Don't add the same builtin candidate twice.9556 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)9557 continue;9558 9559 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};9560 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9561 }9562 9563 if (CandidateTypes[ArgIdx].hasNullPtrType()) {9564 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);9565 if (AddedTypes.insert(NullPtrTy).second) {9566 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };9567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9568 }9569 }9570 }9571 }9572 9573 // C++ [over.built]p15:9574 //9575 // For every T, where T is an enumeration type or a pointer type,9576 // there exist candidate operator functions of the form9577 //9578 // bool operator<(T, T);9579 // bool operator>(T, T);9580 // bool operator<=(T, T);9581 // bool operator>=(T, T);9582 // bool operator==(T, T);9583 // bool operator!=(T, T);9584 // R operator<=>(T, T)9585 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {9586 // C++ [over.match.oper]p3:9587 // [...]the built-in candidates include all of the candidate operator9588 // functions defined in 13.6 that, compared to the given operator, [...]9589 // do not have the same parameter-type-list as any non-template non-member9590 // candidate.9591 //9592 // Note that in practice, this only affects enumeration types because there9593 // aren't any built-in candidates of record type, and a user-defined operator9594 // must have an operand of record or enumeration type. Also, the only other9595 // overloaded operator with enumeration arguments, operator=,9596 // cannot be overloaded for enumeration types, so this is the only place9597 // where we must suppress candidates like this.9598 llvm::DenseSet<std::pair<CanQualType, CanQualType> >9599 UserDefinedBinaryOperators;9600 9601 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {9602 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {9603 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),9604 CEnd = CandidateSet.end();9605 C != CEnd; ++C) {9606 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)9607 continue;9608 9609 if (C->Function->isFunctionTemplateSpecialization())9610 continue;9611 9612 // We interpret "same parameter-type-list" as applying to the9613 // "synthesized candidate, with the order of the two parameters9614 // reversed", not to the original function.9615 bool Reversed = C->isReversed();9616 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)9617 ->getType()9618 .getUnqualifiedType();9619 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)9620 ->getType()9621 .getUnqualifiedType();9622 9623 // Skip if either parameter isn't of enumeral type.9624 if (!FirstParamType->isEnumeralType() ||9625 !SecondParamType->isEnumeralType())9626 continue;9627 9628 // Add this operator to the set of known user-defined operators.9629 UserDefinedBinaryOperators.insert(9630 std::make_pair(S.Context.getCanonicalType(FirstParamType),9631 S.Context.getCanonicalType(SecondParamType)));9632 }9633 }9634 }9635 9636 /// Set of (canonical) types that we've already handled.9637 llvm::SmallPtrSet<QualType, 8> AddedTypes;9638 9639 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {9640 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {9641 // Don't add the same builtin candidate twice.9642 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)9643 continue;9644 if (IsSpaceship && PtrTy->isFunctionPointerType())9645 continue;9646 9647 QualType ParamTypes[2] = {PtrTy, PtrTy};9648 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9649 }9650 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {9651 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);9652 9653 // Don't add the same builtin candidate twice, or if a user defined9654 // candidate exists.9655 if (!AddedTypes.insert(CanonType).second ||9656 UserDefinedBinaryOperators.count(std::make_pair(CanonType,9657 CanonType)))9658 continue;9659 QualType ParamTypes[2] = {EnumTy, EnumTy};9660 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9661 }9662 }9663 }9664 9665 // C++ [over.built]p13:9666 //9667 // For every cv-qualified or cv-unqualified object type T9668 // there exist candidate operator functions of the form9669 //9670 // T* operator+(T*, ptrdiff_t);9671 // T& operator[](T*, ptrdiff_t); [BELOW]9672 // T* operator-(T*, ptrdiff_t);9673 // T* operator+(ptrdiff_t, T*);9674 // T& operator[](ptrdiff_t, T*); [BELOW]9675 //9676 // C++ [over.built]p14:9677 //9678 // For every T, where T is a pointer to object type, there9679 // exist candidate operator functions of the form9680 //9681 // ptrdiff_t operator-(T, T);9682 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {9683 /// Set of (canonical) types that we've already handled.9684 llvm::SmallPtrSet<QualType, 8> AddedTypes;9685 9686 for (int Arg = 0; Arg < 2; ++Arg) {9687 QualType AsymmetricParamTypes[2] = {9688 S.Context.getPointerDiffType(),9689 S.Context.getPointerDiffType(),9690 };9691 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {9692 QualType PointeeTy = PtrTy->getPointeeType();9693 if (!PointeeTy->isObjectType())9694 continue;9695 9696 AsymmetricParamTypes[Arg] = PtrTy;9697 if (Arg == 0 || Op == OO_Plus) {9698 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)9699 // T* operator+(ptrdiff_t, T*);9700 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);9701 }9702 if (Op == OO_Minus) {9703 // ptrdiff_t operator-(T, T);9704 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)9705 continue;9706 9707 QualType ParamTypes[2] = {PtrTy, PtrTy};9708 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);9709 }9710 }9711 }9712 }9713 9714 // C++ [over.built]p12:9715 //9716 // For every pair of promoted arithmetic types L and R, there9717 // exist candidate operator functions of the form9718 //9719 // LR operator*(L, R);9720 // LR operator/(L, R);9721 // LR operator+(L, R);9722 // LR operator-(L, R);9723 // bool operator<(L, R);9724 // bool operator>(L, R);9725 // bool operator<=(L, R);9726 // bool operator>=(L, R);9727 // bool operator==(L, R);9728 // bool operator!=(L, R);9729 //9730 // where LR is the result of the usual arithmetic conversions9731 // between types L and R.9732 //9733 // C++ [over.built]p24:9734 //9735 // For every pair of promoted arithmetic types L and R, there exist9736 // candidate operator functions of the form9737 //9738 // LR operator?(bool, L, R);9739 //9740 // where LR is the result of the usual arithmetic conversions9741 // between types L and R.9742 // Our candidates ignore the first parameter.9743 void addGenericBinaryArithmeticOverloads() {9744 if (!HasArithmeticOrEnumeralCandidateType)9745 return;9746 9747 for (unsigned Left = FirstPromotedArithmeticType;9748 Left < LastPromotedArithmeticType; ++Left) {9749 for (unsigned Right = FirstPromotedArithmeticType;9750 Right < LastPromotedArithmeticType; ++Right) {9751 QualType LandR[2] = { ArithmeticTypes[Left],9752 ArithmeticTypes[Right] };9753 S.AddBuiltinCandidate(LandR, Args, CandidateSet);9754 }9755 }9756 9757 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the9758 // conditional operator for vector types.9759 for (QualType Vec1Ty : CandidateTypes[0].vector_types())9760 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {9761 QualType LandR[2] = {Vec1Ty, Vec2Ty};9762 S.AddBuiltinCandidate(LandR, Args, CandidateSet);9763 }9764 }9765 9766 /// Add binary operator overloads for each candidate matrix type M1, M2:9767 /// * (M1, M1) -> M19768 /// * (M1, M1.getElementType()) -> M19769 /// * (M2.getElementType(), M2) -> M29770 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].9771 void addMatrixBinaryArithmeticOverloads() {9772 if (!HasArithmeticOrEnumeralCandidateType)9773 return;9774 9775 for (QualType M1 : CandidateTypes[0].matrix_types()) {9776 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());9777 AddCandidate(M1, M1);9778 }9779 9780 for (QualType M2 : CandidateTypes[1].matrix_types()) {9781 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);9782 if (!CandidateTypes[0].containsMatrixType(M2))9783 AddCandidate(M2, M2);9784 }9785 }9786 9787 // C++2a [over.built]p14:9788 //9789 // For every integral type T there exists a candidate operator function9790 // of the form9791 //9792 // std::strong_ordering operator<=>(T, T)9793 //9794 // C++2a [over.built]p15:9795 //9796 // For every pair of floating-point types L and R, there exists a candidate9797 // operator function of the form9798 //9799 // std::partial_ordering operator<=>(L, R);9800 //9801 // FIXME: The current specification for integral types doesn't play nice with9802 // the direction of p0946r0, which allows mixed integral and unscoped-enum9803 // comparisons. Under the current spec this can lead to ambiguity during9804 // overload resolution. For example:9805 //9806 // enum A : int {a};9807 // auto x = (a <=> (long)42);9808 //9809 // error: call is ambiguous for arguments 'A' and 'long'.9810 // note: candidate operator<=>(int, int)9811 // note: candidate operator<=>(long, long)9812 //9813 // To avoid this error, this function deviates from the specification and adds9814 // the mixed overloads `operator<=>(L, R)` where L and R are promoted9815 // arithmetic types (the same as the generic relational overloads).9816 //9817 // For now this function acts as a placeholder.9818 void addThreeWayArithmeticOverloads() {9819 addGenericBinaryArithmeticOverloads();9820 }9821 9822 // C++ [over.built]p17:9823 //9824 // For every pair of promoted integral types L and R, there9825 // exist candidate operator functions of the form9826 //9827 // LR operator%(L, R);9828 // LR operator&(L, R);9829 // LR operator^(L, R);9830 // LR operator|(L, R);9831 // L operator<<(L, R);9832 // L operator>>(L, R);9833 //9834 // where LR is the result of the usual arithmetic conversions9835 // between types L and R.9836 void addBinaryBitwiseArithmeticOverloads() {9837 if (!HasArithmeticOrEnumeralCandidateType)9838 return;9839 9840 for (unsigned Left = FirstPromotedIntegralType;9841 Left < LastPromotedIntegralType; ++Left) {9842 for (unsigned Right = FirstPromotedIntegralType;9843 Right < LastPromotedIntegralType; ++Right) {9844 QualType LandR[2] = { ArithmeticTypes[Left],9845 ArithmeticTypes[Right] };9846 S.AddBuiltinCandidate(LandR, Args, CandidateSet);9847 }9848 }9849 }9850 9851 // C++ [over.built]p20:9852 //9853 // For every pair (T, VQ), where T is an enumeration or9854 // pointer to member type and VQ is either volatile or9855 // empty, there exist candidate operator functions of the form9856 //9857 // VQ T& operator=(VQ T&, T);9858 void addAssignmentMemberPointerOrEnumeralOverloads() {9859 /// Set of (canonical) types that we've already handled.9860 llvm::SmallPtrSet<QualType, 8> AddedTypes;9861 9862 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {9863 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {9864 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)9865 continue;9866 9867 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);9868 }9869 9870 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {9871 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)9872 continue;9873 9874 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);9875 }9876 }9877 }9878 9879 // C++ [over.built]p19:9880 //9881 // For every pair (T, VQ), where T is any type and VQ is either9882 // volatile or empty, there exist candidate operator functions9883 // of the form9884 //9885 // T*VQ& operator=(T*VQ&, T*);9886 //9887 // C++ [over.built]p21:9888 //9889 // For every pair (T, VQ), where T is a cv-qualified or9890 // cv-unqualified object type and VQ is either volatile or9891 // empty, there exist candidate operator functions of the form9892 //9893 // T*VQ& operator+=(T*VQ&, ptrdiff_t);9894 // T*VQ& operator-=(T*VQ&, ptrdiff_t);9895 void addAssignmentPointerOverloads(bool isEqualOp) {9896 /// Set of (canonical) types that we've already handled.9897 llvm::SmallPtrSet<QualType, 8> AddedTypes;9898 9899 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {9900 // If this is operator=, keep track of the builtin candidates we added.9901 if (isEqualOp)9902 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));9903 else if (!PtrTy->getPointeeType()->isObjectType())9904 continue;9905 9906 // non-volatile version9907 QualType ParamTypes[2] = {9908 S.Context.getLValueReferenceType(PtrTy),9909 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),9910 };9911 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9912 /*IsAssignmentOperator=*/ isEqualOp);9913 9914 bool NeedVolatile = !PtrTy.isVolatileQualified() &&9915 VisibleTypeConversionsQuals.hasVolatile();9916 if (NeedVolatile) {9917 // volatile version9918 ParamTypes[0] =9919 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));9920 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9921 /*IsAssignmentOperator=*/isEqualOp);9922 }9923 9924 if (!PtrTy.isRestrictQualified() &&9925 VisibleTypeConversionsQuals.hasRestrict()) {9926 // restrict version9927 ParamTypes[0] =9928 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));9929 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9930 /*IsAssignmentOperator=*/isEqualOp);9931 9932 if (NeedVolatile) {9933 // volatile restrict version9934 ParamTypes[0] =9935 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(9936 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));9937 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9938 /*IsAssignmentOperator=*/isEqualOp);9939 }9940 }9941 }9942 9943 if (isEqualOp) {9944 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {9945 // Make sure we don't add the same candidate twice.9946 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)9947 continue;9948 9949 QualType ParamTypes[2] = {9950 S.Context.getLValueReferenceType(PtrTy),9951 PtrTy,9952 };9953 9954 // non-volatile version9955 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9956 /*IsAssignmentOperator=*/true);9957 9958 bool NeedVolatile = !PtrTy.isVolatileQualified() &&9959 VisibleTypeConversionsQuals.hasVolatile();9960 if (NeedVolatile) {9961 // volatile version9962 ParamTypes[0] = S.Context.getLValueReferenceType(9963 S.Context.getVolatileType(PtrTy));9964 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9965 /*IsAssignmentOperator=*/true);9966 }9967 9968 if (!PtrTy.isRestrictQualified() &&9969 VisibleTypeConversionsQuals.hasRestrict()) {9970 // restrict version9971 ParamTypes[0] = S.Context.getLValueReferenceType(9972 S.Context.getRestrictType(PtrTy));9973 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9974 /*IsAssignmentOperator=*/true);9975 9976 if (NeedVolatile) {9977 // volatile restrict version9978 ParamTypes[0] =9979 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(9980 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));9981 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,9982 /*IsAssignmentOperator=*/true);9983 }9984 }9985 }9986 }9987 }9988 9989 // C++ [over.built]p18:9990 //9991 // For every triple (L, VQ, R), where L is an arithmetic type,9992 // VQ is either volatile or empty, and R is a promoted9993 // arithmetic type, there exist candidate operator functions of9994 // the form9995 //9996 // VQ L& operator=(VQ L&, R);9997 // VQ L& operator*=(VQ L&, R);9998 // VQ L& operator/=(VQ L&, R);9999 // VQ L& operator+=(VQ L&, R);10000 // VQ L& operator-=(VQ L&, R);10001 void addAssignmentArithmeticOverloads(bool isEqualOp) {10002 if (!HasArithmeticOrEnumeralCandidateType)10003 return;10004 10005 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {10006 for (unsigned Right = FirstPromotedArithmeticType;10007 Right < LastPromotedArithmeticType; ++Right) {10008 QualType ParamTypes[2];10009 ParamTypes[1] = ArithmeticTypes[Right];10010 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(10011 S, ArithmeticTypes[Left], Args[0]);10012 10013 forAllQualifierCombinations(10014 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {10015 ParamTypes[0] =10016 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);10017 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,10018 /*IsAssignmentOperator=*/isEqualOp);10019 });10020 }10021 }10022 10023 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.10024 for (QualType Vec1Ty : CandidateTypes[0].vector_types())10025 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {10026 QualType ParamTypes[2];10027 ParamTypes[1] = Vec2Ty;10028 // Add this built-in operator as a candidate (VQ is empty).10029 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);10030 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,10031 /*IsAssignmentOperator=*/isEqualOp);10032 10033 // Add this built-in operator as a candidate (VQ is 'volatile').10034 if (VisibleTypeConversionsQuals.hasVolatile()) {10035 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);10036 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);10037 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,10038 /*IsAssignmentOperator=*/isEqualOp);10039 }10040 }10041 }10042 10043 // C++ [over.built]p22:10044 //10045 // For every triple (L, VQ, R), where L is an integral type, VQ10046 // is either volatile or empty, and R is a promoted integral10047 // type, there exist candidate operator functions of the form10048 //10049 // VQ L& operator%=(VQ L&, R);10050 // VQ L& operator<<=(VQ L&, R);10051 // VQ L& operator>>=(VQ L&, R);10052 // VQ L& operator&=(VQ L&, R);10053 // VQ L& operator^=(VQ L&, R);10054 // VQ L& operator|=(VQ L&, R);10055 void addAssignmentIntegralOverloads() {10056 if (!HasArithmeticOrEnumeralCandidateType)10057 return;10058 10059 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {10060 for (unsigned Right = FirstPromotedIntegralType;10061 Right < LastPromotedIntegralType; ++Right) {10062 QualType ParamTypes[2];10063 ParamTypes[1] = ArithmeticTypes[Right];10064 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(10065 S, ArithmeticTypes[Left], Args[0]);10066 10067 forAllQualifierCombinations(10068 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {10069 ParamTypes[0] =10070 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);10071 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);10072 });10073 }10074 }10075 }10076 10077 // C++ [over.operator]p23:10078 //10079 // There also exist candidate operator functions of the form10080 //10081 // bool operator!(bool);10082 // bool operator&&(bool, bool);10083 // bool operator||(bool, bool);10084 void addExclaimOverload() {10085 QualType ParamTy = S.Context.BoolTy;10086 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,10087 /*IsAssignmentOperator=*/false,10088 /*NumContextualBoolArguments=*/1);10089 }10090 void addAmpAmpOrPipePipeOverload() {10091 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };10092 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,10093 /*IsAssignmentOperator=*/false,10094 /*NumContextualBoolArguments=*/2);10095 }10096 10097 // C++ [over.built]p13:10098 //10099 // For every cv-qualified or cv-unqualified object type T there10100 // exist candidate operator functions of the form10101 //10102 // T* operator+(T*, ptrdiff_t); [ABOVE]10103 // T& operator[](T*, ptrdiff_t);10104 // T* operator-(T*, ptrdiff_t); [ABOVE]10105 // T* operator+(ptrdiff_t, T*); [ABOVE]10106 // T& operator[](ptrdiff_t, T*);10107 void addSubscriptOverloads() {10108 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {10109 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};10110 QualType PointeeType = PtrTy->getPointeeType();10111 if (!PointeeType->isObjectType())10112 continue;10113 10114 // T& operator[](T*, ptrdiff_t)10115 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);10116 }10117 10118 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {10119 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};10120 QualType PointeeType = PtrTy->getPointeeType();10121 if (!PointeeType->isObjectType())10122 continue;10123 10124 // T& operator[](ptrdiff_t, T*)10125 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);10126 }10127 }10128 10129 // C++ [over.built]p11:10130 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,10131 // C1 is the same type as C2 or is a derived class of C2, T is an object10132 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,10133 // there exist candidate operator functions of the form10134 //10135 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);10136 //10137 // where CV12 is the union of CV1 and CV2.10138 void addArrowStarOverloads() {10139 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {10140 QualType C1Ty = PtrTy;10141 QualType C1;10142 QualifierCollector Q1;10143 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);10144 if (!isa<RecordType>(C1))10145 continue;10146 // heuristic to reduce number of builtin candidates in the set.10147 // Add volatile/restrict version only if there are conversions to a10148 // volatile/restrict type.10149 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())10150 continue;10151 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())10152 continue;10153 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {10154 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);10155 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),10156 *D2 = mptr->getMostRecentCXXRecordDecl();10157 if (!declaresSameEntity(D1, D2) &&10158 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))10159 break;10160 QualType ParamTypes[2] = {PtrTy, MemPtrTy};10161 // build CV12 T&10162 QualType T = mptr->getPointeeType();10163 if (!VisibleTypeConversionsQuals.hasVolatile() &&10164 T.isVolatileQualified())10165 continue;10166 if (!VisibleTypeConversionsQuals.hasRestrict() &&10167 T.isRestrictQualified())10168 continue;10169 T = Q1.apply(S.Context, T);10170 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);10171 }10172 }10173 }10174 10175 // Note that we don't consider the first argument, since it has been10176 // contextually converted to bool long ago. The candidates below are10177 // therefore added as binary.10178 //10179 // C++ [over.built]p25:10180 // For every type T, where T is a pointer, pointer-to-member, or scoped10181 // enumeration type, there exist candidate operator functions of the form10182 //10183 // T operator?(bool, T, T);10184 //10185 void addConditionalOperatorOverloads() {10186 /// Set of (canonical) types that we've already handled.10187 llvm::SmallPtrSet<QualType, 8> AddedTypes;10188 10189 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {10190 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {10191 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)10192 continue;10193 10194 QualType ParamTypes[2] = {PtrTy, PtrTy};10195 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);10196 }10197 10198 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {10199 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)10200 continue;10201 10202 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};10203 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);10204 }10205 10206 if (S.getLangOpts().CPlusPlus11) {10207 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {10208 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())10209 continue;10210 10211 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)10212 continue;10213 10214 QualType ParamTypes[2] = {EnumTy, EnumTy};10215 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);10216 }10217 }10218 }10219 }10220};10221 10222} // end anonymous namespace10223 10224void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,10225 SourceLocation OpLoc,10226 ArrayRef<Expr *> Args,10227 OverloadCandidateSet &CandidateSet) {10228 // Find all of the types that the arguments can convert to, but only10229 // if the operator we're looking at has built-in operator candidates10230 // that make use of these types. Also record whether we encounter non-record10231 // candidate types or either arithmetic or enumeral candidate types.10232 QualifiersAndAtomic VisibleTypeConversionsQuals;10233 VisibleTypeConversionsQuals.addConst();10234 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {10235 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);10236 if (Args[ArgIdx]->getType()->isAtomicType())10237 VisibleTypeConversionsQuals.addAtomic();10238 }10239 10240 bool HasNonRecordCandidateType = false;10241 bool HasArithmeticOrEnumeralCandidateType = false;10242 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;10243 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {10244 CandidateTypes.emplace_back(*this);10245 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),10246 OpLoc,10247 true,10248 (Op == OO_Exclaim ||10249 Op == OO_AmpAmp ||10250 Op == OO_PipePipe),10251 VisibleTypeConversionsQuals);10252 HasNonRecordCandidateType = HasNonRecordCandidateType ||10253 CandidateTypes[ArgIdx].hasNonRecordTypes();10254 HasArithmeticOrEnumeralCandidateType =10255 HasArithmeticOrEnumeralCandidateType ||10256 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();10257 }10258 10259 // Exit early when no non-record types have been added to the candidate set10260 // for any of the arguments to the operator.10261 //10262 // We can't exit early for !, ||, or &&, since there we have always have10263 // 'bool' overloads.10264 if (!HasNonRecordCandidateType &&10265 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))10266 return;10267 10268 // Setup an object to manage the common state for building overloads.10269 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,10270 VisibleTypeConversionsQuals,10271 HasArithmeticOrEnumeralCandidateType,10272 CandidateTypes, CandidateSet);10273 10274 // Dispatch over the operation to add in only those overloads which apply.10275 switch (Op) {10276 case OO_None:10277 case NUM_OVERLOADED_OPERATORS:10278 llvm_unreachable("Expected an overloaded operator");10279 10280 case OO_New:10281 case OO_Delete:10282 case OO_Array_New:10283 case OO_Array_Delete:10284 case OO_Call:10285 llvm_unreachable(10286 "Special operators don't use AddBuiltinOperatorCandidates");10287 10288 case OO_Comma:10289 case OO_Arrow:10290 case OO_Coawait:10291 // C++ [over.match.oper]p3:10292 // -- For the operator ',', the unary operator '&', the10293 // operator '->', or the operator 'co_await', the10294 // built-in candidates set is empty.10295 break;10296 10297 case OO_Plus: // '+' is either unary or binary10298 if (Args.size() == 1)10299 OpBuilder.addUnaryPlusPointerOverloads();10300 [[fallthrough]];10301 10302 case OO_Minus: // '-' is either unary or binary10303 if (Args.size() == 1) {10304 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();10305 } else {10306 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);10307 OpBuilder.addGenericBinaryArithmeticOverloads();10308 OpBuilder.addMatrixBinaryArithmeticOverloads();10309 }10310 break;10311 10312 case OO_Star: // '*' is either unary or binary10313 if (Args.size() == 1)10314 OpBuilder.addUnaryStarPointerOverloads();10315 else {10316 OpBuilder.addGenericBinaryArithmeticOverloads();10317 OpBuilder.addMatrixBinaryArithmeticOverloads();10318 }10319 break;10320 10321 case OO_Slash:10322 OpBuilder.addGenericBinaryArithmeticOverloads();10323 break;10324 10325 case OO_PlusPlus:10326 case OO_MinusMinus:10327 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);10328 OpBuilder.addPlusPlusMinusMinusPointerOverloads();10329 break;10330 10331 case OO_EqualEqual:10332 case OO_ExclaimEqual:10333 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();10334 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);10335 OpBuilder.addGenericBinaryArithmeticOverloads();10336 break;10337 10338 case OO_Less:10339 case OO_Greater:10340 case OO_LessEqual:10341 case OO_GreaterEqual:10342 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);10343 OpBuilder.addGenericBinaryArithmeticOverloads();10344 break;10345 10346 case OO_Spaceship:10347 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);10348 OpBuilder.addThreeWayArithmeticOverloads();10349 break;10350 10351 case OO_Percent:10352 case OO_Caret:10353 case OO_Pipe:10354 case OO_LessLess:10355 case OO_GreaterGreater:10356 OpBuilder.addBinaryBitwiseArithmeticOverloads();10357 break;10358 10359 case OO_Amp: // '&' is either unary or binary10360 if (Args.size() == 1)10361 // C++ [over.match.oper]p3:10362 // -- For the operator ',', the unary operator '&', or the10363 // operator '->', the built-in candidates set is empty.10364 break;10365 10366 OpBuilder.addBinaryBitwiseArithmeticOverloads();10367 break;10368 10369 case OO_Tilde:10370 OpBuilder.addUnaryTildePromotedIntegralOverloads();10371 break;10372 10373 case OO_Equal:10374 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();10375 [[fallthrough]];10376 10377 case OO_PlusEqual:10378 case OO_MinusEqual:10379 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);10380 [[fallthrough]];10381 10382 case OO_StarEqual:10383 case OO_SlashEqual:10384 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);10385 break;10386 10387 case OO_PercentEqual:10388 case OO_LessLessEqual:10389 case OO_GreaterGreaterEqual:10390 case OO_AmpEqual:10391 case OO_CaretEqual:10392 case OO_PipeEqual:10393 OpBuilder.addAssignmentIntegralOverloads();10394 break;10395 10396 case OO_Exclaim:10397 OpBuilder.addExclaimOverload();10398 break;10399 10400 case OO_AmpAmp:10401 case OO_PipePipe:10402 OpBuilder.addAmpAmpOrPipePipeOverload();10403 break;10404 10405 case OO_Subscript:10406 if (Args.size() == 2)10407 OpBuilder.addSubscriptOverloads();10408 break;10409 10410 case OO_ArrowStar:10411 OpBuilder.addArrowStarOverloads();10412 break;10413 10414 case OO_Conditional:10415 OpBuilder.addConditionalOperatorOverloads();10416 OpBuilder.addGenericBinaryArithmeticOverloads();10417 break;10418 }10419}10420 10421void10422Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,10423 SourceLocation Loc,10424 ArrayRef<Expr *> Args,10425 TemplateArgumentListInfo *ExplicitTemplateArgs,10426 OverloadCandidateSet& CandidateSet,10427 bool PartialOverloading) {10428 ADLResult Fns;10429 10430 // FIXME: This approach for uniquing ADL results (and removing10431 // redundant candidates from the set) relies on pointer-equality,10432 // which means we need to key off the canonical decl. However,10433 // always going back to the canonical decl might not get us the10434 // right set of default arguments. What default arguments are10435 // we supposed to consider on ADL candidates, anyway?10436 10437 // FIXME: Pass in the explicit template arguments?10438 ArgumentDependentLookup(Name, Loc, Args, Fns);10439 10440 ArrayRef<Expr *> ReversedArgs;10441 10442 // Erase all of the candidates we already knew about.10443 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),10444 CandEnd = CandidateSet.end();10445 Cand != CandEnd; ++Cand)10446 if (Cand->Function) {10447 FunctionDecl *Fn = Cand->Function;10448 Fns.erase(Fn);10449 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())10450 Fns.erase(FunTmpl);10451 }10452 10453 // For each of the ADL candidates we found, add it to the overload10454 // set.10455 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {10456 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);10457 10458 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {10459 if (ExplicitTemplateArgs)10460 continue;10461 10462 AddOverloadCandidate(10463 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,10464 PartialOverloading, /*AllowExplicit=*/true,10465 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);10466 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {10467 AddOverloadCandidate(10468 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,10469 /*SuppressUserConversions=*/false, PartialOverloading,10470 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,10471 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);10472 }10473 } else {10474 auto *FTD = cast<FunctionTemplateDecl>(*I);10475 AddTemplateOverloadCandidate(10476 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,10477 /*SuppressUserConversions=*/false, PartialOverloading,10478 /*AllowExplicit=*/true, ADLCallKind::UsesADL);10479 if (CandidateSet.getRewriteInfo().shouldAddReversed(10480 *this, Args, FTD->getTemplatedDecl())) {10481 10482 // As template candidates are not deduced immediately,10483 // persist the array in the overload set.10484 if (ReversedArgs.empty())10485 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);10486 10487 AddTemplateOverloadCandidate(10488 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,10489 /*SuppressUserConversions=*/false, PartialOverloading,10490 /*AllowExplicit=*/true, ADLCallKind::UsesADL,10491 OverloadCandidateParamOrder::Reversed);10492 }10493 }10494 }10495}10496 10497namespace {10498enum class Comparison { Equal, Better, Worse };10499}10500 10501/// Compares the enable_if attributes of two FunctionDecls, for the purposes of10502/// overload resolution.10503///10504/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff10505/// Cand1's first N enable_if attributes have precisely the same conditions as10506/// Cand2's first N enable_if attributes (where N = the number of enable_if10507/// attributes on Cand2), and Cand1 has more than N enable_if attributes.10508///10509/// Note that you can have a pair of candidates such that Cand1's enable_if10510/// attributes are worse than Cand2's, and Cand2's enable_if attributes are10511/// worse than Cand1's.10512static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,10513 const FunctionDecl *Cand2) {10514 // Common case: One (or both) decls don't have enable_if attrs.10515 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();10516 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();10517 if (!Cand1Attr || !Cand2Attr) {10518 if (Cand1Attr == Cand2Attr)10519 return Comparison::Equal;10520 return Cand1Attr ? Comparison::Better : Comparison::Worse;10521 }10522 10523 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();10524 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();10525 10526 llvm::FoldingSetNodeID Cand1ID, Cand2ID;10527 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {10528 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);10529 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);10530 10531 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand110532 // has fewer enable_if attributes than Cand2, and vice versa.10533 if (!Cand1A)10534 return Comparison::Worse;10535 if (!Cand2A)10536 return Comparison::Better;10537 10538 Cand1ID.clear();10539 Cand2ID.clear();10540 10541 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);10542 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);10543 if (Cand1ID != Cand2ID)10544 return Comparison::Worse;10545 }10546 10547 return Comparison::Equal;10548}10549 10550static Comparison10551isBetterMultiversionCandidate(const OverloadCandidate &Cand1,10552 const OverloadCandidate &Cand2) {10553 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||10554 !Cand2.Function->isMultiVersion())10555 return Comparison::Equal;10556 10557 // If both are invalid, they are equal. If one of them is invalid, the other10558 // is better.10559 if (Cand1.Function->isInvalidDecl()) {10560 if (Cand2.Function->isInvalidDecl())10561 return Comparison::Equal;10562 return Comparison::Worse;10563 }10564 if (Cand2.Function->isInvalidDecl())10565 return Comparison::Better;10566 10567 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer10568 // cpu_dispatch, else arbitrarily based on the identifiers.10569 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();10570 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();10571 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();10572 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();10573 10574 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)10575 return Comparison::Equal;10576 10577 if (Cand1CPUDisp && !Cand2CPUDisp)10578 return Comparison::Better;10579 if (Cand2CPUDisp && !Cand1CPUDisp)10580 return Comparison::Worse;10581 10582 if (Cand1CPUSpec && Cand2CPUSpec) {10583 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())10584 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()10585 ? Comparison::Better10586 : Comparison::Worse;10587 10588 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>10589 FirstDiff = std::mismatch(10590 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),10591 Cand2CPUSpec->cpus_begin(),10592 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {10593 return LHS->getName() == RHS->getName();10594 });10595 10596 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&10597 "Two different cpu-specific versions should not have the same "10598 "identifier list, otherwise they'd be the same decl!");10599 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()10600 ? Comparison::Better10601 : Comparison::Worse;10602 }10603 llvm_unreachable("No way to get here unless both had cpu_dispatch");10604}10605 10606/// Compute the type of the implicit object parameter for the given function,10607/// if any. Returns std::nullopt if there is no implicit object parameter, and a10608/// null QualType if there is a 'matches anything' implicit object parameter.10609static std::optional<QualType>10610getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {10611 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))10612 return std::nullopt;10613 10614 auto *M = cast<CXXMethodDecl>(F);10615 // Static member functions' object parameters match all types.10616 if (M->isStatic())10617 return QualType();10618 return M->getFunctionObjectParameterReferenceType();10619}10620 10621// As a Clang extension, allow ambiguity among F1 and F2 if they represent10622// represent the same entity.10623static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,10624 const FunctionDecl *F2) {10625 if (declaresSameEntity(F1, F2))10626 return true;10627 auto PT1 = F1->getPrimaryTemplate();10628 auto PT2 = F2->getPrimaryTemplate();10629 if (PT1 && PT2) {10630 if (declaresSameEntity(PT1, PT2) ||10631 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),10632 PT2->getInstantiatedFromMemberTemplate()))10633 return true;10634 }10635 // TODO: It is not clear whether comparing parameters is necessary (i.e.10636 // different functions with same params). Consider removing this (as no test10637 // fail w/o it).10638 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {10639 if (First) {10640 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))10641 return *T;10642 }10643 assert(I < F->getNumParams());10644 return F->getParamDecl(I++)->getType();10645 };10646 10647 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);10648 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);10649 10650 if (F1NumParams != F2NumParams)10651 return false;10652 10653 unsigned I1 = 0, I2 = 0;10654 for (unsigned I = 0; I != F1NumParams; ++I) {10655 QualType T1 = NextParam(F1, I1, I == 0);10656 QualType T2 = NextParam(F2, I2, I == 0);10657 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");10658 if (!Context.hasSameUnqualifiedType(T1, T2))10659 return false;10660 }10661 return true;10662}10663 10664/// We're allowed to use constraints partial ordering only if the candidates10665/// have the same parameter types:10666/// [over.match.best.general]p2.610667/// F1 and F2 are non-template functions with the same10668/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]10669static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,10670 FunctionDecl *Fn2,10671 bool IsFn1Reversed,10672 bool IsFn2Reversed) {10673 assert(Fn1 && Fn2);10674 if (Fn1->isVariadic() != Fn2->isVariadic())10675 return false;10676 10677 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,10678 IsFn1Reversed ^ IsFn2Reversed))10679 return false;10680 10681 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);10682 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);10683 if (Mem1 && Mem2) {10684 // if they are member functions, both are direct members of the same class,10685 // and10686 if (Mem1->getParent() != Mem2->getParent())10687 return false;10688 // if both are non-static member functions, they have the same types for10689 // their object parameters10690 if (Mem1->isInstance() && Mem2->isInstance() &&10691 !S.getASTContext().hasSameType(10692 Mem1->getFunctionObjectParameterReferenceType(),10693 Mem1->getFunctionObjectParameterReferenceType()))10694 return false;10695 }10696 return true;10697}10698 10699static FunctionDecl *10700getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,10701 bool IsFn1Reversed, bool IsFn2Reversed) {10702 if (!Fn1 || !Fn2)10703 return nullptr;10704 10705 // C++ [temp.constr.order]:10706 // A non-template function F1 is more partial-ordering-constrained than a10707 // non-template function F2 if:10708 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();10709 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();10710 10711 if (Cand1IsSpecialization || Cand2IsSpecialization)10712 return nullptr;10713 10714 // - they have the same non-object-parameter-type-lists, and [...]10715 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,10716 IsFn2Reversed))10717 return nullptr;10718 10719 // - the declaration of F1 is more constrained than the declaration of F2.10720 return S.getMoreConstrainedFunction(Fn1, Fn2);10721}10722 10723/// isBetterOverloadCandidate - Determines whether the first overload10724/// candidate is a better candidate than the second (C++ 13.3.3p1).10725bool clang::isBetterOverloadCandidate(10726 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,10727 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,10728 bool PartialOverloading) {10729 // Define viable functions to be better candidates than non-viable10730 // functions.10731 if (!Cand2.Viable)10732 return Cand1.Viable;10733 else if (!Cand1.Viable)10734 return false;10735 10736 // [CUDA] A function with 'never' preference is marked not viable, therefore10737 // is never shown up here. The worst preference shown up here is 'wrong side',10738 // e.g. an H function called by a HD function in device compilation. This is10739 // valid AST as long as the HD function is not emitted, e.g. it is an inline10740 // function which is called only by an H function. A deferred diagnostic will10741 // be triggered if it is emitted. However a wrong-sided function is still10742 // a viable candidate here.10743 //10744 // If Cand1 can be emitted and Cand2 cannot be emitted in the current10745 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand210746 // can be emitted, Cand1 is not better than Cand2. This rule should have10747 // precedence over other rules.10748 //10749 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then10750 // other rules should be used to determine which is better. This is because10751 // host/device based overloading resolution is mostly for determining10752 // viability of a function. If two functions are both viable, other factors10753 // should take precedence in preference, e.g. the standard-defined preferences10754 // like argument conversion ranks or enable_if partial-ordering. The10755 // preference for pass-object-size parameters is probably most similar to a10756 // type-based-overloading decision and so should take priority.10757 //10758 // If other rules cannot determine which is better, CUDA preference will be10759 // used again to determine which is better.10760 //10761 // TODO: Currently IdentifyPreference does not return correct values10762 // for functions called in global variable initializers due to missing10763 // correct context about device/host. Therefore we can only enforce this10764 // rule when there is a caller. We should enforce this rule for functions10765 // in global variable initializers once proper context is added.10766 //10767 // TODO: We can only enable the hostness based overloading resolution when10768 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring10769 // overloading resolution diagnostics.10770 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&10771 S.getLangOpts().GPUExcludeWrongSideOverloads) {10772 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {10773 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);10774 bool IsCand1ImplicitHD =10775 SemaCUDA::isImplicitHostDeviceFunction(Cand1.Function);10776 bool IsCand2ImplicitHD =10777 SemaCUDA::isImplicitHostDeviceFunction(Cand2.Function);10778 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);10779 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);10780 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);10781 // The implicit HD function may be a function in a system header which10782 // is forced by pragma. In device compilation, if we prefer HD candidates10783 // over wrong-sided candidates, overloading resolution may change, which10784 // may result in non-deferrable diagnostics. As a workaround, we let10785 // implicit HD candidates take equal preference as wrong-sided candidates.10786 // This will preserve the overloading resolution.10787 // TODO: We still need special handling of implicit HD functions since10788 // they may incur other diagnostics to be deferred. We should make all10789 // host/device related diagnostics deferrable and remove special handling10790 // of implicit HD functions.10791 auto EmitThreshold =10792 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&10793 (IsCand1ImplicitHD || IsCand2ImplicitHD))10794 ? SemaCUDA::CFP_Never10795 : SemaCUDA::CFP_WrongSide;10796 auto Cand1Emittable = P1 > EmitThreshold;10797 auto Cand2Emittable = P2 > EmitThreshold;10798 if (Cand1Emittable && !Cand2Emittable)10799 return true;10800 if (!Cand1Emittable && Cand2Emittable)10801 return false;10802 }10803 }10804 10805 // C++ [over.match.best]p1: (Changed in C++23)10806 //10807 // -- if F is a static member function, ICS1(F) is defined such10808 // that ICS1(F) is neither better nor worse than ICS1(G) for10809 // any function G, and, symmetrically, ICS1(G) is neither10810 // better nor worse than ICS1(F).10811 unsigned StartArg = 0;10812 if (!Cand1.TookAddressOfOverload &&10813 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))10814 StartArg = 1;10815 10816 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {10817 // We don't allow incompatible pointer conversions in C++.10818 if (!S.getLangOpts().CPlusPlus)10819 return ICS.isStandard() &&10820 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;10821 10822 // The only ill-formed conversion we allow in C++ is the string literal to10823 // char* conversion, which is only considered ill-formed after C++11.10824 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&10825 hasDeprecatedStringLiteralToCharPtrConversion(ICS);10826 };10827 10828 // Define functions that don't require ill-formed conversions for a given10829 // argument to be better candidates than functions that do.10830 unsigned NumArgs = Cand1.Conversions.size();10831 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");10832 bool HasBetterConversion = false;10833 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {10834 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);10835 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);10836 if (Cand1Bad != Cand2Bad) {10837 if (Cand1Bad)10838 return false;10839 HasBetterConversion = true;10840 }10841 }10842 10843 if (HasBetterConversion)10844 return true;10845 10846 // C++ [over.match.best]p1:10847 // A viable function F1 is defined to be a better function than another10848 // viable function F2 if for all arguments i, ICSi(F1) is not a worse10849 // conversion sequence than ICSi(F2), and then...10850 bool HasWorseConversion = false;10851 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {10852 switch (CompareImplicitConversionSequences(S, Loc,10853 Cand1.Conversions[ArgIdx],10854 Cand2.Conversions[ArgIdx])) {10855 case ImplicitConversionSequence::Better:10856 // Cand1 has a better conversion sequence.10857 HasBetterConversion = true;10858 break;10859 10860 case ImplicitConversionSequence::Worse:10861 if (Cand1.Function && Cand2.Function &&10862 Cand1.isReversed() != Cand2.isReversed() &&10863 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {10864 // Work around large-scale breakage caused by considering reversed10865 // forms of operator== in C++20:10866 //10867 // When comparing a function against a reversed function, if we have a10868 // better conversion for one argument and a worse conversion for the10869 // other, the implicit conversion sequences are treated as being equally10870 // good.10871 //10872 // This prevents a comparison function from being considered ambiguous10873 // with a reversed form that is written in the same way.10874 //10875 // We diagnose this as an extension from CreateOverloadedBinOp.10876 HasWorseConversion = true;10877 break;10878 }10879 10880 // Cand1 can't be better than Cand2.10881 return false;10882 10883 case ImplicitConversionSequence::Indistinguishable:10884 // Do nothing.10885 break;10886 }10887 }10888 10889 // -- for some argument j, ICSj(F1) is a better conversion sequence than10890 // ICSj(F2), or, if not that,10891 if (HasBetterConversion && !HasWorseConversion)10892 return true;10893 10894 // -- the context is an initialization by user-defined conversion10895 // (see 8.5, 13.3.1.5) and the standard conversion sequence10896 // from the return type of F1 to the destination type (i.e.,10897 // the type of the entity being initialized) is a better10898 // conversion sequence than the standard conversion sequence10899 // from the return type of F2 to the destination type.10900 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&10901 Cand1.Function && Cand2.Function &&10902 isa<CXXConversionDecl>(Cand1.Function) &&10903 isa<CXXConversionDecl>(Cand2.Function)) {10904 10905 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);10906 // First check whether we prefer one of the conversion functions over the10907 // other. This only distinguishes the results in non-standard, extension10908 // cases such as the conversion from a lambda closure type to a function10909 // pointer or block.10910 ImplicitConversionSequence::CompareKind Result =10911 compareConversionFunctions(S, Cand1.Function, Cand2.Function);10912 if (Result == ImplicitConversionSequence::Indistinguishable)10913 Result = CompareStandardConversionSequences(S, Loc,10914 Cand1.FinalConversion,10915 Cand2.FinalConversion);10916 10917 if (Result != ImplicitConversionSequence::Indistinguishable)10918 return Result == ImplicitConversionSequence::Better;10919 10920 // FIXME: Compare kind of reference binding if conversion functions10921 // convert to a reference type used in direct reference binding, per10922 // C++14 [over.match.best]p1 section 2 bullet 3.10923 }10924 10925 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,10926 // as combined with the resolution to CWG issue 243.10927 //10928 // When the context is initialization by constructor ([over.match.ctor] or10929 // either phase of [over.match.list]), a constructor is preferred over10930 // a conversion function.10931 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&10932 Cand1.Function && Cand2.Function &&10933 isa<CXXConstructorDecl>(Cand1.Function) !=10934 isa<CXXConstructorDecl>(Cand2.Function))10935 return isa<CXXConstructorDecl>(Cand1.Function);10936 10937 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)10938 return Cand2.StrictPackMatch;10939 10940 // -- F1 is a non-template function and F2 is a function template10941 // specialization, or, if not that,10942 bool Cand1IsSpecialization = Cand1.Function &&10943 Cand1.Function->getPrimaryTemplate();10944 bool Cand2IsSpecialization = Cand2.Function &&10945 Cand2.Function->getPrimaryTemplate();10946 if (Cand1IsSpecialization != Cand2IsSpecialization)10947 return Cand2IsSpecialization;10948 10949 // -- F1 and F2 are function template specializations, and the function10950 // template for F1 is more specialized than the template for F210951 // according to the partial ordering rules described in 14.5.5.2, or,10952 // if not that,10953 if (Cand1IsSpecialization && Cand2IsSpecialization) {10954 const auto *Obj1Context =10955 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());10956 const auto *Obj2Context =10957 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());10958 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(10959 Cand1.Function->getPrimaryTemplate(),10960 Cand2.Function->getPrimaryTemplate(), Loc,10961 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion10962 : TPOC_Call,10963 Cand1.ExplicitCallArguments,10964 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)10965 : QualType{},10966 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)10967 : QualType{},10968 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {10969 return BetterTemplate == Cand1.Function->getPrimaryTemplate();10970 }10971 }10972 10973 // -— F1 and F2 are non-template functions and F1 is more10974 // partial-ordering-constrained than F2 [...],10975 if (FunctionDecl *F = getMorePartialOrderingConstrained(10976 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),10977 Cand2.isReversed());10978 F && F == Cand1.Function)10979 return true;10980 10981 // -- F1 is a constructor for a class D, F2 is a constructor for a base10982 // class B of D, and for all arguments the corresponding parameters of10983 // F1 and F2 have the same type.10984 // FIXME: Implement the "all parameters have the same type" check.10985 bool Cand1IsInherited =10986 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());10987 bool Cand2IsInherited =10988 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());10989 if (Cand1IsInherited != Cand2IsInherited)10990 return Cand2IsInherited;10991 else if (Cand1IsInherited) {10992 assert(Cand2IsInherited);10993 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());10994 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());10995 if (Cand1Class->isDerivedFrom(Cand2Class))10996 return true;10997 if (Cand2Class->isDerivedFrom(Cand1Class))10998 return false;10999 // Inherited from sibling base classes: still ambiguous.11000 }11001 11002 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not11003 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate11004 // with reversed order of parameters and F1 is not11005 //11006 // We rank reversed + different operator as worse than just reversed, but11007 // that comparison can never happen, because we only consider reversing for11008 // the maximally-rewritten operator (== or <=>).11009 if (Cand1.RewriteKind != Cand2.RewriteKind)11010 return Cand1.RewriteKind < Cand2.RewriteKind;11011 11012 // Check C++17 tie-breakers for deduction guides.11013 {11014 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);11015 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);11016 if (Guide1 && Guide2) {11017 // -- F1 is generated from a deduction-guide and F2 is not11018 if (Guide1->isImplicit() != Guide2->isImplicit())11019 return Guide2->isImplicit();11020 11021 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not11022 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)11023 return true;11024 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)11025 return false;11026 11027 // --F1 is generated from a non-template constructor and F2 is generated11028 // from a constructor template11029 const auto *Constructor1 = Guide1->getCorrespondingConstructor();11030 const auto *Constructor2 = Guide2->getCorrespondingConstructor();11031 if (Constructor1 && Constructor2) {11032 bool isC1Templated = Constructor1->getTemplatedKind() !=11033 FunctionDecl::TemplatedKind::TK_NonTemplate;11034 bool isC2Templated = Constructor2->getTemplatedKind() !=11035 FunctionDecl::TemplatedKind::TK_NonTemplate;11036 if (isC1Templated != isC2Templated)11037 return isC2Templated;11038 }11039 }11040 }11041 11042 // Check for enable_if value-based overload resolution.11043 if (Cand1.Function && Cand2.Function) {11044 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);11045 if (Cmp != Comparison::Equal)11046 return Cmp == Comparison::Better;11047 }11048 11049 bool HasPS1 = Cand1.Function != nullptr &&11050 functionHasPassObjectSizeParams(Cand1.Function);11051 bool HasPS2 = Cand2.Function != nullptr &&11052 functionHasPassObjectSizeParams(Cand2.Function);11053 if (HasPS1 != HasPS2 && HasPS1)11054 return true;11055 11056 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);11057 if (MV == Comparison::Better)11058 return true;11059 if (MV == Comparison::Worse)11060 return false;11061 11062 // If other rules cannot determine which is better, CUDA preference is used11063 // to determine which is better.11064 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {11065 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);11066 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >11067 S.CUDA().IdentifyPreference(Caller, Cand2.Function);11068 }11069 11070 // General member function overloading is handled above, so this only handles11071 // constructors with address spaces.11072 // This only handles address spaces since C++ has no other11073 // qualifier that can be used with constructors.11074 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);11075 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);11076 if (CD1 && CD2) {11077 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();11078 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();11079 if (AS1 != AS2) {11080 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1, S.getASTContext()))11081 return true;11082 if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2, S.getASTContext()))11083 return false;11084 }11085 }11086 11087 return false;11088}11089 11090/// Determine whether two declarations are "equivalent" for the purposes of11091/// name lookup and overload resolution. This applies when the same internal/no11092/// linkage entity is defined by two modules (probably by textually including11093/// the same header). In such a case, we don't consider the declarations to11094/// declare the same entity, but we also don't want lookups with both11095/// declarations visible to be ambiguous in some cases (this happens when using11096/// a modularized libstdc++).11097bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,11098 const NamedDecl *B) {11099 auto *VA = dyn_cast_or_null<ValueDecl>(A);11100 auto *VB = dyn_cast_or_null<ValueDecl>(B);11101 if (!VA || !VB)11102 return false;11103 11104 // The declarations must be declaring the same name as an internal linkage11105 // entity in different modules.11106 if (!VA->getDeclContext()->getRedeclContext()->Equals(11107 VB->getDeclContext()->getRedeclContext()) ||11108 getOwningModule(VA) == getOwningModule(VB) ||11109 VA->isExternallyVisible() || VB->isExternallyVisible())11110 return false;11111 11112 // Check that the declarations appear to be equivalent.11113 //11114 // FIXME: Checking the type isn't really enough to resolve the ambiguity.11115 // For constants and functions, we should check the initializer or body is11116 // the same. For non-constant variables, we shouldn't allow it at all.11117 if (Context.hasSameType(VA->getType(), VB->getType()))11118 return true;11119 11120 // Enum constants within unnamed enumerations will have different types, but11121 // may still be similar enough to be interchangeable for our purposes.11122 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {11123 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {11124 // Only handle anonymous enums. If the enumerations were named and11125 // equivalent, they would have been merged to the same type.11126 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());11127 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());11128 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||11129 !Context.hasSameType(EnumA->getIntegerType(),11130 EnumB->getIntegerType()))11131 return false;11132 // Allow this only if the value is the same for both enumerators.11133 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());11134 }11135 }11136 11137 // Nothing else is sufficiently similar.11138 return false;11139}11140 11141void Sema::diagnoseEquivalentInternalLinkageDeclarations(11142 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {11143 assert(D && "Unknown declaration");11144 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;11145 11146 Module *M = getOwningModule(D);11147 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)11148 << !M << (M ? M->getFullModuleName() : "");11149 11150 for (auto *E : Equiv) {11151 Module *M = getOwningModule(E);11152 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)11153 << !M << (M ? M->getFullModuleName() : "");11154 }11155}11156 11157bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {11158 return FailureKind == ovl_fail_bad_deduction &&11159 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==11160 TemplateDeductionResult::ConstraintsNotSatisfied &&11161 static_cast<CNSInfo *>(DeductionFailure.Data)11162 ->Satisfaction.ContainsErrors;11163}11164 11165void OverloadCandidateSet::AddDeferredTemplateCandidate(11166 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,11167 ArrayRef<Expr *> Args, bool SuppressUserConversions,11168 bool PartialOverloading, bool AllowExplicit,11169 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,11170 bool AggregateCandidateDeduction) {11171 11172 auto *C =11173 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();11174 11175 C = new (C) DeferredFunctionTemplateOverloadCandidate{11176 {nullptr, DeferredFunctionTemplateOverloadCandidate::Function,11177 /*AllowObjCConversionOnExplicit=*/false,11178 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,11179 PartialOverloading, AggregateCandidateDeduction},11180 FunctionTemplate,11181 FoundDecl,11182 Args,11183 IsADLCandidate,11184 PO};11185 11186 HasDeferredTemplateConstructors |=11187 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());11188}11189 11190void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(11191 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,11192 CXXRecordDecl *ActingContext, QualType ObjectType,11193 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,11194 bool SuppressUserConversions, bool PartialOverloading,11195 OverloadCandidateParamOrder PO) {11196 11197 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));11198 11199 auto *C =11200 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();11201 11202 C = new (C) DeferredMethodTemplateOverloadCandidate{11203 {nullptr, DeferredFunctionTemplateOverloadCandidate::Method,11204 /*AllowObjCConversionOnExplicit=*/false,11205 /*AllowResultConversion=*/false,11206 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,11207 /*AggregateCandidateDeduction=*/false},11208 MethodTmpl,11209 FoundDecl,11210 Args,11211 ActingContext,11212 ObjectClassification,11213 ObjectType,11214 PO};11215}11216 11217void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(11218 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,11219 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,11220 bool AllowObjCConversionOnExplicit, bool AllowExplicit,11221 bool AllowResultConversion) {11222 11223 auto *C =11224 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();11225 11226 C = new (C) DeferredConversionTemplateOverloadCandidate{11227 {nullptr, DeferredFunctionTemplateOverloadCandidate::Conversion,11228 AllowObjCConversionOnExplicit, AllowResultConversion,11229 /*AllowExplicit=*/false,11230 /*SuppressUserConversions=*/false,11231 /*PartialOverloading*/ false,11232 /*AggregateCandidateDeduction=*/false},11233 FunctionTemplate,11234 FoundDecl,11235 ActingContext,11236 From,11237 ToType};11238}11239 11240static void11241AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,11242 DeferredMethodTemplateOverloadCandidate &C) {11243 11244 AddMethodTemplateCandidateImmediately(11245 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,11246 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,11247 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);11248}11249 11250static void11251AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,11252 DeferredFunctionTemplateOverloadCandidate &C) {11253 AddTemplateOverloadCandidateImmediately(11254 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,11255 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,11256 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,11257 C.AggregateCandidateDeduction);11258}11259 11260static void11261AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,11262 DeferredConversionTemplateOverloadCandidate &C) {11263 return AddTemplateConversionCandidateImmediately(11264 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,11265 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,11266 C.AllowResultConversion);11267}11268 11269void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {11270 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);11271 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;11272 while (Cand) {11273 switch (Cand->Kind) {11274 case DeferredTemplateOverloadCandidate::Function:11275 AddTemplateOverloadCandidate(11276 S, *this,11277 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));11278 break;11279 case DeferredTemplateOverloadCandidate::Method:11280 AddTemplateOverloadCandidate(11281 S, *this,11282 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));11283 break;11284 case DeferredTemplateOverloadCandidate::Conversion:11285 AddTemplateOverloadCandidate(11286 S, *this,11287 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));11288 break;11289 }11290 Cand = Cand->Next;11291 }11292 FirstDeferredCandidate = nullptr;11293 DeferredCandidatesCount = 0;11294}11295 11296OverloadingResult11297OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {11298 Best->Best = true;11299 if (Best->Function && Best->Function->isDeleted())11300 return OR_Deleted;11301 return OR_Success;11302}11303 11304void OverloadCandidateSet::CudaExcludeWrongSideCandidates(11305 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {11306 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but11307 // are accepted by both clang and NVCC. However, during a particular11308 // compilation mode only one call variant is viable. We need to11309 // exclude non-viable overload candidates from consideration based11310 // only on their host/device attributes. Specifically, if one11311 // candidate call is WrongSide and the other is SameSide, we ignore11312 // the WrongSide candidate.11313 // We only need to remove wrong-sided candidates here if11314 // -fgpu-exclude-wrong-side-overloads is off. When11315 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared11316 // uniformly in isBetterOverloadCandidate.11317 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)11318 return;11319 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);11320 11321 bool ContainsSameSideCandidate =11322 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {11323 // Check viable function only.11324 return Cand->Viable && Cand->Function &&11325 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==11326 SemaCUDA::CFP_SameSide;11327 });11328 11329 if (!ContainsSameSideCandidate)11330 return;11331 11332 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {11333 // Check viable function only to avoid unnecessary data copying/moving.11334 return Cand->Viable && Cand->Function &&11335 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==11336 SemaCUDA::CFP_WrongSide;11337 };11338 llvm::erase_if(Candidates, IsWrongSideCandidate);11339}11340 11341/// Computes the best viable function (C++ 13.3.3)11342/// within an overload candidate set.11343///11344/// \param Loc The location of the function name (or operator symbol) for11345/// which overload resolution occurs.11346///11347/// \param Best If overload resolution was successful or found a deleted11348/// function, \p Best points to the candidate function found.11349///11350/// \returns The result of overload resolution.11351OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,11352 SourceLocation Loc,11353 iterator &Best) {11354 11355 assert((shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||11356 DeferredCandidatesCount == 0) &&11357 "Unexpected deferred template candidates");11358 11359 bool TwoPhaseResolution =11360 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;11361 11362 if (TwoPhaseResolution) {11363 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);11364 if (Best != end() && Best->isPerfectMatch(S.Context)) {11365 if (!(HasDeferredTemplateConstructors &&11366 isa_and_nonnull<CXXConversionDecl>(Best->Function)))11367 return Res;11368 }11369 }11370 11371 InjectNonDeducedTemplateCandidates(S);11372 return BestViableFunctionImpl(S, Loc, Best);11373}11374 11375OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(11376 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {11377 11378 llvm::SmallVector<OverloadCandidate *, 16> Candidates;11379 Candidates.reserve(this->Candidates.size());11380 std::transform(this->Candidates.begin(), this->Candidates.end(),11381 std::back_inserter(Candidates),11382 [](OverloadCandidate &Cand) { return &Cand; });11383 11384 if (S.getLangOpts().CUDA)11385 CudaExcludeWrongSideCandidates(S, Candidates);11386 11387 Best = end();11388 for (auto *Cand : Candidates) {11389 Cand->Best = false;11390 if (Cand->Viable) {11391 if (Best == end() ||11392 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))11393 Best = Cand;11394 } else if (Cand->NotValidBecauseConstraintExprHasError()) {11395 // This candidate has constraint that we were unable to evaluate because11396 // it referenced an expression that contained an error. Rather than fall11397 // back onto a potentially unintended candidate (made worse by11398 // subsuming constraints), treat this as 'no viable candidate'.11399 Best = end();11400 return OR_No_Viable_Function;11401 }11402 }11403 11404 // If we didn't find any viable functions, abort.11405 if (Best == end())11406 return OR_No_Viable_Function;11407 11408 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;11409 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;11410 PendingBest.push_back(&*Best);11411 Best->Best = true;11412 11413 // Make sure that this function is better than every other viable11414 // function. If not, we have an ambiguity.11415 while (!PendingBest.empty()) {11416 auto *Curr = PendingBest.pop_back_val();11417 for (auto *Cand : Candidates) {11418 if (Cand->Viable && !Cand->Best &&11419 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {11420 PendingBest.push_back(Cand);11421 Cand->Best = true;11422 11423 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,11424 Curr->Function))11425 EquivalentCands.push_back(Cand->Function);11426 else11427 Best = end();11428 }11429 }11430 }11431 11432 if (Best == end())11433 return OR_Ambiguous;11434 11435 OverloadingResult R = ResultForBestCandidate(Best);11436 11437 if (!EquivalentCands.empty())11438 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,11439 EquivalentCands);11440 return R;11441}11442 11443namespace {11444 11445enum OverloadCandidateKind {11446 oc_function,11447 oc_method,11448 oc_reversed_binary_operator,11449 oc_constructor,11450 oc_implicit_default_constructor,11451 oc_implicit_copy_constructor,11452 oc_implicit_move_constructor,11453 oc_implicit_copy_assignment,11454 oc_implicit_move_assignment,11455 oc_implicit_equality_comparison,11456 oc_inherited_constructor11457};11458 11459enum OverloadCandidateSelect {11460 ocs_non_template,11461 ocs_template,11462 ocs_described_template,11463};11464 11465static std::pair<OverloadCandidateKind, OverloadCandidateSelect>11466ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,11467 const FunctionDecl *Fn,11468 OverloadCandidateRewriteKind CRK,11469 std::string &Description) {11470 11471 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();11472 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {11473 isTemplate = true;11474 Description = S.getTemplateArgumentBindingsText(11475 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());11476 }11477 11478 OverloadCandidateSelect Select = [&]() {11479 if (!Description.empty())11480 return ocs_described_template;11481 return isTemplate ? ocs_template : ocs_non_template;11482 }();11483 11484 OverloadCandidateKind Kind = [&]() {11485 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)11486 return oc_implicit_equality_comparison;11487 11488 if (CRK & CRK_Reversed)11489 return oc_reversed_binary_operator;11490 11491 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {11492 if (!Ctor->isImplicit()) {11493 if (isa<ConstructorUsingShadowDecl>(Found))11494 return oc_inherited_constructor;11495 else11496 return oc_constructor;11497 }11498 11499 if (Ctor->isDefaultConstructor())11500 return oc_implicit_default_constructor;11501 11502 if (Ctor->isMoveConstructor())11503 return oc_implicit_move_constructor;11504 11505 assert(Ctor->isCopyConstructor() &&11506 "unexpected sort of implicit constructor");11507 return oc_implicit_copy_constructor;11508 }11509 11510 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {11511 // This actually gets spelled 'candidate function' for now, but11512 // it doesn't hurt to split it out.11513 if (!Meth->isImplicit())11514 return oc_method;11515 11516 if (Meth->isMoveAssignmentOperator())11517 return oc_implicit_move_assignment;11518 11519 if (Meth->isCopyAssignmentOperator())11520 return oc_implicit_copy_assignment;11521 11522 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");11523 return oc_method;11524 }11525 11526 return oc_function;11527 }();11528 11529 return std::make_pair(Kind, Select);11530}11531 11532void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {11533 // FIXME: It'd be nice to only emit a note once per using-decl per overload11534 // set.11535 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))11536 S.Diag(FoundDecl->getLocation(),11537 diag::note_ovl_candidate_inherited_constructor)11538 << Shadow->getNominatedBaseClass();11539}11540 11541} // end anonymous namespace11542 11543static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,11544 const FunctionDecl *FD) {11545 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {11546 bool AlwaysTrue;11547 if (EnableIf->getCond()->isValueDependent() ||11548 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))11549 return false;11550 if (!AlwaysTrue)11551 return false;11552 }11553 return true;11554}11555 11556/// Returns true if we can take the address of the function.11557///11558/// \param Complain - If true, we'll emit a diagnostic11559/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are11560/// we in overload resolution?11561/// \param Loc - The location of the statement we're complaining about. Ignored11562/// if we're not complaining, or if we're in overload resolution.11563static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,11564 bool Complain,11565 bool InOverloadResolution,11566 SourceLocation Loc) {11567 if (!isFunctionAlwaysEnabled(S.Context, FD)) {11568 if (Complain) {11569 if (InOverloadResolution)11570 S.Diag(FD->getBeginLoc(),11571 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);11572 else11573 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;11574 }11575 return false;11576 }11577 11578 if (FD->getTrailingRequiresClause()) {11579 ConstraintSatisfaction Satisfaction;11580 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))11581 return false;11582 if (!Satisfaction.IsSatisfied) {11583 if (Complain) {11584 if (InOverloadResolution) {11585 SmallString<128> TemplateArgString;11586 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {11587 TemplateArgString += " ";11588 TemplateArgString += S.getTemplateArgumentBindingsText(11589 FunTmpl->getTemplateParameters(),11590 *FD->getTemplateSpecializationArgs());11591 }11592 11593 S.Diag(FD->getBeginLoc(),11594 diag::note_ovl_candidate_unsatisfied_constraints)11595 << TemplateArgString;11596 } else11597 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)11598 << FD;11599 S.DiagnoseUnsatisfiedConstraint(Satisfaction);11600 }11601 return false;11602 }11603 }11604 11605 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {11606 return P->hasAttr<PassObjectSizeAttr>();11607 });11608 if (I == FD->param_end())11609 return true;11610 11611 if (Complain) {11612 // Add one to ParamNo because it's user-facing11613 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;11614 if (InOverloadResolution)11615 S.Diag(FD->getLocation(),11616 diag::note_ovl_candidate_has_pass_object_size_params)11617 << ParamNo;11618 else11619 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)11620 << FD << ParamNo;11621 }11622 return false;11623}11624 11625static bool checkAddressOfCandidateIsAvailable(Sema &S,11626 const FunctionDecl *FD) {11627 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,11628 /*InOverloadResolution=*/true,11629 /*Loc=*/SourceLocation());11630}11631 11632bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,11633 bool Complain,11634 SourceLocation Loc) {11635 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,11636 /*InOverloadResolution=*/false,11637 Loc);11638}11639 11640// Don't print candidates other than the one that matches the calling11641// convention of the call operator, since that is guaranteed to exist.11642static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {11643 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);11644 11645 if (!ConvD)11646 return false;11647 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());11648 if (!RD->isLambda())11649 return false;11650 11651 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();11652 CallingConv CallOpCC =11653 CallOp->getType()->castAs<FunctionType>()->getCallConv();11654 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();11655 CallingConv ConvToCC =11656 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();11657 11658 return ConvToCC != CallOpCC;11659}11660 11661// Notes the location of an overload candidate.11662void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,11663 OverloadCandidateRewriteKind RewriteKind,11664 QualType DestType, bool TakingAddress) {11665 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))11666 return;11667 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&11668 !Fn->getAttr<TargetAttr>()->isDefaultVersion())11669 return;11670 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&11671 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())11672 return;11673 if (shouldSkipNotingLambdaConversionDecl(Fn))11674 return;11675 11676 std::string FnDesc;11677 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =11678 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);11679 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)11680 << (unsigned)KSPair.first << (unsigned)KSPair.second11681 << Fn << FnDesc;11682 11683 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);11684 Diag(Fn->getLocation(), PD);11685 MaybeEmitInheritedConstructorNote(*this, Found);11686}11687 11688static void11689MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {11690 // Perhaps the ambiguity was caused by two atomic constraints that are11691 // 'identical' but not equivalent:11692 //11693 // void foo() requires (sizeof(T) > 4) { } // #111694 // void foo() requires (sizeof(T) > 4) && T::value { } // #211695 //11696 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause11697 // #2 to subsume #1, but these constraint are not considered equivalent11698 // according to the subsumption rules because they are not the same11699 // source-level construct. This behavior is quite confusing and we should try11700 // to help the user figure out what happened.11701 11702 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;11703 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;11704 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {11705 if (!I->Function)11706 continue;11707 SmallVector<AssociatedConstraint, 3> AC;11708 if (auto *Template = I->Function->getPrimaryTemplate())11709 Template->getAssociatedConstraints(AC);11710 else11711 I->Function->getAssociatedConstraints(AC);11712 if (AC.empty())11713 continue;11714 if (FirstCand == nullptr) {11715 FirstCand = I->Function;11716 FirstAC = AC;11717 } else if (SecondCand == nullptr) {11718 SecondCand = I->Function;11719 SecondAC = AC;11720 } else {11721 // We have more than one pair of constrained functions - this check is11722 // expensive and we'd rather not try to diagnose it.11723 return;11724 }11725 }11726 if (!SecondCand)11727 return;11728 // The diagnostic can only happen if there are associated constraints on11729 // both sides (there needs to be some identical atomic constraint).11730 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,11731 SecondCand, SecondAC))11732 // Just show the user one diagnostic, they'll probably figure it out11733 // from here.11734 return;11735}11736 11737// Notes the location of all overload candidates designated through11738// OverloadedExpr11739void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,11740 bool TakingAddress) {11741 assert(OverloadedExpr->getType() == Context.OverloadTy);11742 11743 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);11744 OverloadExpr *OvlExpr = Ovl.Expression;11745 11746 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),11747 IEnd = OvlExpr->decls_end();11748 I != IEnd; ++I) {11749 if (FunctionTemplateDecl *FunTmpl =11750 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {11751 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,11752 TakingAddress);11753 } else if (FunctionDecl *Fun11754 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {11755 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);11756 }11757 }11758}11759 11760/// Diagnoses an ambiguous conversion. The partial diagnostic is the11761/// "lead" diagnostic; it will be given two arguments, the source and11762/// target types of the conversion.11763void ImplicitConversionSequence::DiagnoseAmbiguousConversion(11764 Sema &S,11765 SourceLocation CaretLoc,11766 const PartialDiagnostic &PDiag) const {11767 S.Diag(CaretLoc, PDiag)11768 << Ambiguous.getFromType() << Ambiguous.getToType();11769 unsigned CandsShown = 0;11770 AmbiguousConversionSequence::const_iterator I, E;11771 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {11772 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())11773 break;11774 ++CandsShown;11775 S.NoteOverloadCandidate(I->first, I->second);11776 }11777 S.Diags.overloadCandidatesShown(CandsShown);11778 if (I != E)11779 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);11780}11781 11782static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,11783 unsigned I, bool TakingCandidateAddress) {11784 const ImplicitConversionSequence &Conv = Cand->Conversions[I];11785 assert(Conv.isBad());11786 assert(Cand->Function && "for now, candidate must be a function");11787 FunctionDecl *Fn = Cand->Function;11788 11789 // There's a conversion slot for the object argument if this is a11790 // non-constructor method. Note that 'I' corresponds the11791 // conversion-slot index.11792 bool isObjectArgument = false;11793 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&11794 !isa<CXXConstructorDecl>(Fn)) {11795 if (I == 0)11796 isObjectArgument = true;11797 else if (!Fn->hasCXXExplicitFunctionObjectParameter())11798 I--;11799 }11800 11801 std::string FnDesc;11802 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =11803 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),11804 FnDesc);11805 11806 Expr *FromExpr = Conv.Bad.FromExpr;11807 QualType FromTy = Conv.Bad.getFromType();11808 QualType ToTy = Conv.Bad.getToType();11809 SourceRange ToParamRange;11810 11811 // FIXME: In presence of parameter packs we can't determine parameter range11812 // reliably, as we don't have access to instantiation.11813 bool HasParamPack =11814 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {11815 return Parm->isParameterPack();11816 });11817 if (!isObjectArgument && !HasParamPack)11818 ToParamRange = Fn->getParamDecl(I)->getSourceRange();11819 11820 if (FromTy == S.Context.OverloadTy) {11821 assert(FromExpr && "overload set argument came from implicit argument?");11822 Expr *E = FromExpr->IgnoreParens();11823 if (isa<UnaryOperator>(E))11824 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();11825 DeclarationName Name = cast<OverloadExpr>(E)->getName();11826 11827 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)11828 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11829 << ToParamRange << ToTy << Name << I + 1;11830 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11831 return;11832 }11833 11834 // Do some hand-waving analysis to see if the non-viability is due11835 // to a qualifier mismatch.11836 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);11837 CanQualType CToTy = S.Context.getCanonicalType(ToTy);11838 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())11839 CToTy = RT->getPointeeType();11840 else {11841 // TODO: detect and diagnose the full richness of const mismatches.11842 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())11843 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {11844 CFromTy = FromPT->getPointeeType();11845 CToTy = ToPT->getPointeeType();11846 }11847 }11848 11849 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&11850 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {11851 Qualifiers FromQs = CFromTy.getQualifiers();11852 Qualifiers ToQs = CToTy.getQualifiers();11853 11854 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {11855 if (isObjectArgument)11856 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)11857 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second11858 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();11859 else11860 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)11861 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second11862 << FnDesc << ToParamRange << FromQs.getAddressSpace()11863 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;11864 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11865 return;11866 }11867 11868 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {11869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)11870 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11871 << ToParamRange << FromTy << FromQs.getObjCLifetime()11872 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;11873 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11874 return;11875 }11876 11877 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {11878 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)11879 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11880 << ToParamRange << FromTy << FromQs.getObjCGCAttr()11881 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;11882 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11883 return;11884 }11885 11886 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {11887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)11888 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11889 << FromTy << !!FromQs.getPointerAuth()11890 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()11891 << ToQs.getPointerAuth().getAsString() << I + 111892 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());11893 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11894 return;11895 }11896 11897 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();11898 assert(CVR && "expected qualifiers mismatch");11899 11900 if (isObjectArgument) {11901 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)11902 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11903 << FromTy << (CVR - 1);11904 } else {11905 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)11906 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11907 << ToParamRange << FromTy << (CVR - 1) << I + 1;11908 }11909 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11910 return;11911 }11912 11913 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||11914 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {11915 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)11916 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11917 << (unsigned)isObjectArgument << I + 111918 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)11919 << ToParamRange;11920 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11921 return;11922 }11923 11924 // Special diagnostic for failure to convert an initializer list, since11925 // telling the user that it has type void is not useful.11926 if (FromExpr && isa<InitListExpr>(FromExpr)) {11927 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)11928 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11929 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 111930 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 111931 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers11932 ? 211933 : 0);11934 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11935 return;11936 }11937 11938 // Diagnose references or pointers to incomplete types differently,11939 // since it's far from impossible that the incompleteness triggered11940 // the failure.11941 QualType TempFromTy = FromTy.getNonReferenceType();11942 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())11943 TempFromTy = PTy->getPointeeType();11944 if (TempFromTy->isIncompleteType()) {11945 // Emit the generic diagnostic and, optionally, add the hints to it.11946 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)11947 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11948 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 111949 << (unsigned)(Cand->Fix.Kind);11950 11951 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11952 return;11953 }11954 11955 // Diagnose base -> derived pointer conversions.11956 unsigned BaseToDerivedConversion = 0;11957 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {11958 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {11959 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(11960 FromPtrTy->getPointeeType(), S.getASTContext()) &&11961 !FromPtrTy->getPointeeType()->isIncompleteType() &&11962 !ToPtrTy->getPointeeType()->isIncompleteType() &&11963 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),11964 FromPtrTy->getPointeeType()))11965 BaseToDerivedConversion = 1;11966 }11967 } else if (const ObjCObjectPointerType *FromPtrTy11968 = FromTy->getAs<ObjCObjectPointerType>()) {11969 if (const ObjCObjectPointerType *ToPtrTy11970 = ToTy->getAs<ObjCObjectPointerType>())11971 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())11972 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())11973 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(11974 FromPtrTy->getPointeeType(), S.getASTContext()) &&11975 FromIface->isSuperClassOf(ToIface))11976 BaseToDerivedConversion = 2;11977 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {11978 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,11979 S.getASTContext()) &&11980 !FromTy->isIncompleteType() &&11981 !ToRefTy->getPointeeType()->isIncompleteType() &&11982 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {11983 BaseToDerivedConversion = 3;11984 }11985 }11986 11987 if (BaseToDerivedConversion) {11988 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)11989 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc11990 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy11991 << I + 1;11992 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);11993 return;11994 }11995 11996 if (isa<ObjCObjectPointerType>(CFromTy) &&11997 isa<PointerType>(CToTy)) {11998 Qualifiers FromQs = CFromTy.getQualifiers();11999 Qualifiers ToQs = CToTy.getQualifiers();12000 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {12001 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)12002 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc12003 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument12004 << I + 1;12005 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);12006 return;12007 }12008 }12009 12010 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))12011 return;12012 12013 // Emit the generic diagnostic and, optionally, add the hints to it.12014 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);12015 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc12016 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 112017 << (unsigned)(Cand->Fix.Kind);12018 12019 // Check that location of Fn is not in system header.12020 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {12021 // If we can fix the conversion, suggest the FixIts.12022 for (const FixItHint &HI : Cand->Fix.Hints)12023 FDiag << HI;12024 }12025 12026 S.Diag(Fn->getLocation(), FDiag);12027 12028 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);12029}12030 12031/// Additional arity mismatch diagnosis specific to a function overload12032/// candidates. This is not covered by the more general DiagnoseArityMismatch()12033/// over a candidate in any candidate set.12034static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,12035 unsigned NumArgs, bool IsAddressOf = false) {12036 assert(Cand->Function && "Candidate is required to be a function.");12037 FunctionDecl *Fn = Cand->Function;12038 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +12039 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);12040 12041 // With invalid overloaded operators, it's possible that we think we12042 // have an arity mismatch when in fact it looks like we have the12043 // right number of arguments, because only overloaded operators have12044 // the weird behavior of overloading member and non-member functions.12045 // Just don't report anything.12046 if (Fn->isInvalidDecl() &&12047 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)12048 return true;12049 12050 if (NumArgs < MinParams) {12051 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||12052 (Cand->FailureKind == ovl_fail_bad_deduction &&12053 Cand->DeductionFailure.getResult() ==12054 TemplateDeductionResult::TooFewArguments));12055 } else {12056 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||12057 (Cand->FailureKind == ovl_fail_bad_deduction &&12058 Cand->DeductionFailure.getResult() ==12059 TemplateDeductionResult::TooManyArguments));12060 }12061 12062 return false;12063}12064 12065/// General arity mismatch diagnosis over a candidate in a candidate set.12066static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,12067 unsigned NumFormalArgs,12068 bool IsAddressOf = false) {12069 assert(isa<FunctionDecl>(D) &&12070 "The templated declaration should at least be a function"12071 " when diagnosing bad template argument deduction due to too many"12072 " or too few arguments");12073 12074 FunctionDecl *Fn = cast<FunctionDecl>(D);12075 12076 // TODO: treat calls to a missing default constructor as a special case12077 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();12078 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +12079 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);12080 12081 // at least / at most / exactly12082 bool HasExplicitObjectParam =12083 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();12084 12085 unsigned ParamCount =12086 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);12087 unsigned mode, modeCount;12088 12089 if (NumFormalArgs < MinParams) {12090 if (MinParams != ParamCount || FnTy->isVariadic() ||12091 FnTy->isTemplateVariadic())12092 mode = 0; // "at least"12093 else12094 mode = 2; // "exactly"12095 modeCount = MinParams;12096 } else {12097 if (MinParams != ParamCount)12098 mode = 1; // "at most"12099 else12100 mode = 2; // "exactly"12101 modeCount = ParamCount;12102 }12103 12104 std::string Description;12105 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =12106 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);12107 12108 if (modeCount == 1 && !IsAddressOf &&12109 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())12110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)12111 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second12112 << Description << mode12113 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs12114 << HasExplicitObjectParam << Fn->getParametersSourceRange();12115 else12116 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)12117 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second12118 << Description << mode << modeCount << NumFormalArgs12119 << HasExplicitObjectParam << Fn->getParametersSourceRange();12120 12121 MaybeEmitInheritedConstructorNote(S, Found);12122}12123 12124/// Arity mismatch diagnosis specific to a function overload candidate.12125static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,12126 unsigned NumFormalArgs) {12127 assert(Cand->Function && "Candidate must be a function");12128 FunctionDecl *Fn = Cand->Function;12129 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))12130 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,12131 Cand->TookAddressOfOverload);12132}12133 12134static TemplateDecl *getDescribedTemplate(Decl *Templated) {12135 if (TemplateDecl *TD = Templated->getDescribedTemplate())12136 return TD;12137 llvm_unreachable("Unsupported: Getting the described template declaration"12138 " for bad deduction diagnosis");12139}12140 12141/// Diagnose a failed template-argument deduction.12142static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,12143 DeductionFailureInfo &DeductionFailure,12144 unsigned NumArgs,12145 bool TakingCandidateAddress) {12146 TemplateParameter Param = DeductionFailure.getTemplateParameter();12147 NamedDecl *ParamD;12148 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||12149 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||12150 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());12151 switch (DeductionFailure.getResult()) {12152 case TemplateDeductionResult::Success:12153 llvm_unreachable(12154 "TemplateDeductionResult::Success while diagnosing bad deduction");12155 case TemplateDeductionResult::NonDependentConversionFailure:12156 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "12157 "while diagnosing bad deduction");12158 case TemplateDeductionResult::Invalid:12159 case TemplateDeductionResult::AlreadyDiagnosed:12160 return;12161 12162 case TemplateDeductionResult::Incomplete: {12163 assert(ParamD && "no parameter found for incomplete deduction result");12164 S.Diag(Templated->getLocation(),12165 diag::note_ovl_candidate_incomplete_deduction)12166 << ParamD->getDeclName();12167 MaybeEmitInheritedConstructorNote(S, Found);12168 return;12169 }12170 12171 case TemplateDeductionResult::IncompletePack: {12172 assert(ParamD && "no parameter found for incomplete deduction result");12173 S.Diag(Templated->getLocation(),12174 diag::note_ovl_candidate_incomplete_deduction_pack)12175 << ParamD->getDeclName()12176 << (DeductionFailure.getFirstArg()->pack_size() + 1)12177 << *DeductionFailure.getFirstArg();12178 MaybeEmitInheritedConstructorNote(S, Found);12179 return;12180 }12181 12182 case TemplateDeductionResult::Underqualified: {12183 assert(ParamD && "no parameter found for bad qualifiers deduction result");12184 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);12185 12186 QualType Param = DeductionFailure.getFirstArg()->getAsType();12187 12188 // Param will have been canonicalized, but it should just be a12189 // qualified version of ParamD, so move the qualifiers to that.12190 QualifierCollector Qs;12191 Qs.strip(Param);12192 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());12193 assert(S.Context.hasSameType(Param, NonCanonParam));12194 12195 // Arg has also been canonicalized, but there's nothing we can do12196 // about that. It also doesn't matter as much, because it won't12197 // have any template parameters in it (because deduction isn't12198 // done on dependent types).12199 QualType Arg = DeductionFailure.getSecondArg()->getAsType();12200 12201 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)12202 << ParamD->getDeclName() << Arg << NonCanonParam;12203 MaybeEmitInheritedConstructorNote(S, Found);12204 return;12205 }12206 12207 case TemplateDeductionResult::Inconsistent: {12208 assert(ParamD && "no parameter found for inconsistent deduction result");12209 int which = 0;12210 if (isa<TemplateTypeParmDecl>(ParamD))12211 which = 0;12212 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {12213 // Deduction might have failed because we deduced arguments of two12214 // different types for a non-type template parameter.12215 // FIXME: Use a different TDK value for this.12216 QualType T1 =12217 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();12218 QualType T2 =12219 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();12220 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {12221 S.Diag(Templated->getLocation(),12222 diag::note_ovl_candidate_inconsistent_deduction_types)12223 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T112224 << *DeductionFailure.getSecondArg() << T2;12225 MaybeEmitInheritedConstructorNote(S, Found);12226 return;12227 }12228 12229 which = 1;12230 } else {12231 which = 2;12232 }12233 12234 // Tweak the diagnostic if the problem is that we deduced packs of12235 // different arities. We'll print the actual packs anyway in case that12236 // includes additional useful information.12237 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&12238 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&12239 DeductionFailure.getFirstArg()->pack_size() !=12240 DeductionFailure.getSecondArg()->pack_size()) {12241 which = 3;12242 }12243 12244 S.Diag(Templated->getLocation(),12245 diag::note_ovl_candidate_inconsistent_deduction)12246 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()12247 << *DeductionFailure.getSecondArg();12248 MaybeEmitInheritedConstructorNote(S, Found);12249 return;12250 }12251 12252 case TemplateDeductionResult::InvalidExplicitArguments:12253 assert(ParamD && "no parameter found for invalid explicit arguments");12254 if (ParamD->getDeclName())12255 S.Diag(Templated->getLocation(),12256 diag::note_ovl_candidate_explicit_arg_mismatch_named)12257 << ParamD->getDeclName();12258 else {12259 int index = 0;12260 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))12261 index = TTP->getIndex();12262 else if (NonTypeTemplateParmDecl *NTTP12263 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))12264 index = NTTP->getIndex();12265 else12266 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();12267 S.Diag(Templated->getLocation(),12268 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)12269 << (index + 1);12270 }12271 MaybeEmitInheritedConstructorNote(S, Found);12272 return;12273 12274 case TemplateDeductionResult::ConstraintsNotSatisfied: {12275 // Format the template argument list into the argument string.12276 SmallString<128> TemplateArgString;12277 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();12278 TemplateArgString = " ";12279 TemplateArgString += S.getTemplateArgumentBindingsText(12280 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);12281 if (TemplateArgString.size() == 1)12282 TemplateArgString.clear();12283 S.Diag(Templated->getLocation(),12284 diag::note_ovl_candidate_unsatisfied_constraints)12285 << TemplateArgString;12286 12287 S.DiagnoseUnsatisfiedConstraint(12288 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);12289 return;12290 }12291 case TemplateDeductionResult::TooManyArguments:12292 case TemplateDeductionResult::TooFewArguments:12293 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);12294 return;12295 12296 case TemplateDeductionResult::InstantiationDepth:12297 S.Diag(Templated->getLocation(),12298 diag::note_ovl_candidate_instantiation_depth);12299 MaybeEmitInheritedConstructorNote(S, Found);12300 return;12301 12302 case TemplateDeductionResult::SubstitutionFailure: {12303 // Format the template argument list into the argument string.12304 SmallString<128> TemplateArgString;12305 if (TemplateArgumentList *Args =12306 DeductionFailure.getTemplateArgumentList()) {12307 TemplateArgString = " ";12308 TemplateArgString += S.getTemplateArgumentBindingsText(12309 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);12310 if (TemplateArgString.size() == 1)12311 TemplateArgString.clear();12312 }12313 12314 // If this candidate was disabled by enable_if, say so.12315 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();12316 if (PDiag && PDiag->second.getDiagID() ==12317 diag::err_typename_nested_not_found_enable_if) {12318 // FIXME: Use the source range of the condition, and the fully-qualified12319 // name of the enable_if template. These are both present in PDiag.12320 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)12321 << "'enable_if'" << TemplateArgString;12322 return;12323 }12324 12325 // We found a specific requirement that disabled the enable_if.12326 if (PDiag && PDiag->second.getDiagID() ==12327 diag::err_typename_nested_not_found_requirement) {12328 S.Diag(Templated->getLocation(),12329 diag::note_ovl_candidate_disabled_by_requirement)12330 << PDiag->second.getStringArg(0) << TemplateArgString;12331 return;12332 }12333 12334 // Format the SFINAE diagnostic into the argument string.12335 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s12336 // formatted message in another diagnostic.12337 SmallString<128> SFINAEArgString;12338 SourceRange R;12339 if (PDiag) {12340 SFINAEArgString = ": ";12341 R = SourceRange(PDiag->first, PDiag->first);12342 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);12343 }12344 12345 S.Diag(Templated->getLocation(),12346 diag::note_ovl_candidate_substitution_failure)12347 << TemplateArgString << SFINAEArgString << R;12348 MaybeEmitInheritedConstructorNote(S, Found);12349 return;12350 }12351 12352 case TemplateDeductionResult::DeducedMismatch:12353 case TemplateDeductionResult::DeducedMismatchNested: {12354 // Format the template argument list into the argument string.12355 SmallString<128> TemplateArgString;12356 if (TemplateArgumentList *Args =12357 DeductionFailure.getTemplateArgumentList()) {12358 TemplateArgString = " ";12359 TemplateArgString += S.getTemplateArgumentBindingsText(12360 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);12361 if (TemplateArgString.size() == 1)12362 TemplateArgString.clear();12363 }12364 12365 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)12366 << (*DeductionFailure.getCallArgIndex() + 1)12367 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()12368 << TemplateArgString12369 << (DeductionFailure.getResult() ==12370 TemplateDeductionResult::DeducedMismatchNested);12371 break;12372 }12373 12374 case TemplateDeductionResult::NonDeducedMismatch: {12375 // FIXME: Provide a source location to indicate what we couldn't match.12376 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();12377 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();12378 if (FirstTA.getKind() == TemplateArgument::Template &&12379 SecondTA.getKind() == TemplateArgument::Template) {12380 TemplateName FirstTN = FirstTA.getAsTemplate();12381 TemplateName SecondTN = SecondTA.getAsTemplate();12382 if (FirstTN.getKind() == TemplateName::Template &&12383 SecondTN.getKind() == TemplateName::Template) {12384 if (FirstTN.getAsTemplateDecl()->getName() ==12385 SecondTN.getAsTemplateDecl()->getName()) {12386 // FIXME: This fixes a bad diagnostic where both templates are named12387 // the same. This particular case is a bit difficult since:12388 // 1) It is passed as a string to the diagnostic printer.12389 // 2) The diagnostic printer only attempts to find a better12390 // name for types, not decls.12391 // Ideally, this should folded into the diagnostic printer.12392 S.Diag(Templated->getLocation(),12393 diag::note_ovl_candidate_non_deduced_mismatch_qualified)12394 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();12395 return;12396 }12397 }12398 }12399 12400 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&12401 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))12402 return;12403 12404 // FIXME: For generic lambda parameters, check if the function is a lambda12405 // call operator, and if so, emit a prettier and more informative12406 // diagnostic that mentions 'auto' and lambda in addition to12407 // (or instead of?) the canonical template type parameters.12408 S.Diag(Templated->getLocation(),12409 diag::note_ovl_candidate_non_deduced_mismatch)12410 << FirstTA << SecondTA;12411 return;12412 }12413 // TODO: diagnose these individually, then kill off12414 // note_ovl_candidate_bad_deduction, which is uselessly vague.12415 case TemplateDeductionResult::MiscellaneousDeductionFailure:12416 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);12417 MaybeEmitInheritedConstructorNote(S, Found);12418 return;12419 case TemplateDeductionResult::CUDATargetMismatch:12420 S.Diag(Templated->getLocation(),12421 diag::note_cuda_ovl_candidate_target_mismatch);12422 return;12423 }12424}12425 12426/// Diagnose a failed template-argument deduction, for function calls.12427static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,12428 unsigned NumArgs,12429 bool TakingCandidateAddress) {12430 assert(Cand->Function && "Candidate must be a function");12431 FunctionDecl *Fn = Cand->Function;12432 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();12433 if (TDK == TemplateDeductionResult::TooFewArguments ||12434 TDK == TemplateDeductionResult::TooManyArguments) {12435 if (CheckArityMismatch(S, Cand, NumArgs))12436 return;12437 }12438 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern12439 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);12440}12441 12442/// CUDA: diagnose an invalid call across targets.12443static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {12444 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);12445 assert(Cand->Function && "Candidate must be a Function.");12446 FunctionDecl *Callee = Cand->Function;12447 12448 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),12449 CalleeTarget = S.CUDA().IdentifyTarget(Callee);12450 12451 std::string FnDesc;12452 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =12453 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,12454 Cand->getRewriteKind(), FnDesc);12455 12456 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)12457 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template12458 << FnDesc /* Ignored */12459 << CalleeTarget << CallerTarget;12460 12461 // This could be an implicit constructor for which we could not infer the12462 // target due to a collsion. Diagnose that case.12463 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);12464 if (Meth != nullptr && Meth->isImplicit()) {12465 CXXRecordDecl *ParentClass = Meth->getParent();12466 CXXSpecialMemberKind CSM;12467 12468 switch (FnKindPair.first) {12469 default:12470 return;12471 case oc_implicit_default_constructor:12472 CSM = CXXSpecialMemberKind::DefaultConstructor;12473 break;12474 case oc_implicit_copy_constructor:12475 CSM = CXXSpecialMemberKind::CopyConstructor;12476 break;12477 case oc_implicit_move_constructor:12478 CSM = CXXSpecialMemberKind::MoveConstructor;12479 break;12480 case oc_implicit_copy_assignment:12481 CSM = CXXSpecialMemberKind::CopyAssignment;12482 break;12483 case oc_implicit_move_assignment:12484 CSM = CXXSpecialMemberKind::MoveAssignment;12485 break;12486 };12487 12488 bool ConstRHS = false;12489 if (Meth->getNumParams()) {12490 if (const ReferenceType *RT =12491 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {12492 ConstRHS = RT->getPointeeType().isConstQualified();12493 }12494 }12495 12496 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,12497 /* ConstRHS */ ConstRHS,12498 /* Diagnose */ true);12499 }12500}12501 12502static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {12503 assert(Cand->Function && "Candidate must be a function");12504 FunctionDecl *Callee = Cand->Function;12505 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);12506 12507 S.Diag(Callee->getLocation(),12508 diag::note_ovl_candidate_disabled_by_function_cond_attr)12509 << Attr->getCond()->getSourceRange() << Attr->getMessage();12510}12511 12512static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {12513 assert(Cand->Function && "Candidate must be a function");12514 FunctionDecl *Fn = Cand->Function;12515 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Fn);12516 assert(ES.isExplicit() && "not an explicit candidate");12517 12518 unsigned Kind;12519 switch (Fn->getDeclKind()) {12520 case Decl::Kind::CXXConstructor:12521 Kind = 0;12522 break;12523 case Decl::Kind::CXXConversion:12524 Kind = 1;12525 break;12526 case Decl::Kind::CXXDeductionGuide:12527 Kind = Fn->isImplicit() ? 0 : 2;12528 break;12529 default:12530 llvm_unreachable("invalid Decl");12531 }12532 12533 // Note the location of the first (in-class) declaration; a redeclaration12534 // (particularly an out-of-class definition) will typically lack the12535 // 'explicit' specifier.12536 // FIXME: This is probably a good thing to do for all 'candidate' notes.12537 FunctionDecl *First = Fn->getFirstDecl();12538 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())12539 First = Pattern->getFirstDecl();12540 12541 S.Diag(First->getLocation(),12542 diag::note_ovl_candidate_explicit)12543 << Kind << (ES.getExpr() ? 1 : 0)12544 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());12545}12546 12547static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {12548 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);12549 if (!DG)12550 return;12551 TemplateDecl *OriginTemplate =12552 DG->getDeclName().getCXXDeductionGuideTemplate();12553 // We want to always print synthesized deduction guides for type aliases.12554 // They would retain the explicit bit of the corresponding constructor.12555 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))12556 return;12557 std::string FunctionProto;12558 llvm::raw_string_ostream OS(FunctionProto);12559 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();12560 if (!Template) {12561 // This also could be an instantiation. Find out the primary template.12562 FunctionDecl *Pattern =12563 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);12564 if (!Pattern) {12565 // The implicit deduction guide is built on an explicit non-template12566 // deduction guide. Currently, this might be the case only for type12567 // aliases.12568 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/9668612569 // gets merged.12570 assert(OriginTemplate->isTypeAlias() &&12571 "Non-template implicit deduction guides are only possible for "12572 "type aliases");12573 DG->print(OS);12574 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)12575 << FunctionProto;12576 return;12577 }12578 Template = Pattern->getDescribedFunctionTemplate();12579 assert(Template && "Cannot find the associated function template of "12580 "CXXDeductionGuideDecl?");12581 }12582 Template->print(OS);12583 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)12584 << FunctionProto;12585}12586 12587/// Generates a 'note' diagnostic for an overload candidate. We've12588/// already generated a primary error at the call site.12589///12590/// It really does need to be a single diagnostic with its caret12591/// pointed at the candidate declaration. Yes, this creates some12592/// major challenges of technical writing. Yes, this makes pointing12593/// out problems with specific arguments quite awkward. It's still12594/// better than generating twenty screens of text for every failed12595/// overload.12596///12597/// It would be great to be able to express per-candidate problems12598/// more richly for those diagnostic clients that cared, but we'd12599/// still have to be just as careful with the default diagnostics.12600/// \param CtorDestAS Addr space of object being constructed (for ctor12601/// candidates only).12602static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,12603 unsigned NumArgs,12604 bool TakingCandidateAddress,12605 LangAS CtorDestAS = LangAS::Default) {12606 assert(Cand->Function && "Candidate must be a function");12607 FunctionDecl *Fn = Cand->Function;12608 if (shouldSkipNotingLambdaConversionDecl(Fn))12609 return;12610 12611 // There is no physical candidate declaration to point to for OpenCL builtins.12612 // Except for failed conversions, the notes are identical for each candidate,12613 // so do not generate such notes.12614 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&12615 Cand->FailureKind != ovl_fail_bad_conversion)12616 return;12617 12618 // Skip implicit member functions when trying to resolve12619 // the address of a an overload set for a function pointer.12620 if (Cand->TookAddressOfOverload &&12621 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())12622 return;12623 12624 // Note deleted candidates, but only if they're viable.12625 if (Cand->Viable) {12626 if (Fn->isDeleted()) {12627 std::string FnDesc;12628 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =12629 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,12630 Cand->getRewriteKind(), FnDesc);12631 12632 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)12633 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc12634 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);12635 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);12636 return;12637 }12638 12639 // We don't really have anything else to say about viable candidates.12640 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());12641 return;12642 }12643 12644 // If this is a synthesized deduction guide we're deducing against, add a note12645 // for it. These deduction guides are not explicitly spelled in the source12646 // code, so simply printing a deduction failure note mentioning synthesized12647 // template parameters or pointing to the header of the surrounding RecordDecl12648 // would be confusing.12649 //12650 // We prefer adding such notes at the end of the deduction failure because12651 // duplicate code snippets appearing in the diagnostic would likely become12652 // noisy.12653 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });12654 12655 switch (Cand->FailureKind) {12656 case ovl_fail_too_many_arguments:12657 case ovl_fail_too_few_arguments:12658 return DiagnoseArityMismatch(S, Cand, NumArgs);12659 12660 case ovl_fail_bad_deduction:12661 return DiagnoseBadDeduction(S, Cand, NumArgs,12662 TakingCandidateAddress);12663 12664 case ovl_fail_illegal_constructor: {12665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)12666 << (Fn->getPrimaryTemplate() ? 1 : 0);12667 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);12668 return;12669 }12670 12671 case ovl_fail_object_addrspace_mismatch: {12672 Qualifiers QualsForPrinting;12673 QualsForPrinting.setAddressSpace(CtorDestAS);12674 S.Diag(Fn->getLocation(),12675 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)12676 << QualsForPrinting;12677 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);12678 return;12679 }12680 12681 case ovl_fail_trivial_conversion:12682 case ovl_fail_bad_final_conversion:12683 case ovl_fail_final_conversion_not_exact:12684 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());12685 12686 case ovl_fail_bad_conversion: {12687 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);12688 for (unsigned N = Cand->Conversions.size(); I != N; ++I)12689 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())12690 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);12691 12692 // FIXME: this currently happens when we're called from SemaInit12693 // when user-conversion overload fails. Figure out how to handle12694 // those conditions and diagnose them well.12695 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());12696 }12697 12698 case ovl_fail_bad_target:12699 return DiagnoseBadTarget(S, Cand);12700 12701 case ovl_fail_enable_if:12702 return DiagnoseFailedEnableIfAttr(S, Cand);12703 12704 case ovl_fail_explicit:12705 return DiagnoseFailedExplicitSpec(S, Cand);12706 12707 case ovl_fail_inhctor_slice:12708 // It's generally not interesting to note copy/move constructors here.12709 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())12710 return;12711 S.Diag(Fn->getLocation(),12712 diag::note_ovl_candidate_inherited_constructor_slice)12713 << (Fn->getPrimaryTemplate() ? 1 : 0)12714 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();12715 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);12716 return;12717 12718 case ovl_fail_addr_not_available: {12719 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);12720 (void)Available;12721 assert(!Available);12722 break;12723 }12724 case ovl_non_default_multiversion_function:12725 // Do nothing, these should simply be ignored.12726 break;12727 12728 case ovl_fail_constraints_not_satisfied: {12729 std::string FnDesc;12730 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =12731 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,12732 Cand->getRewriteKind(), FnDesc);12733 12734 S.Diag(Fn->getLocation(),12735 diag::note_ovl_candidate_constraints_not_satisfied)12736 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template12737 << FnDesc /* Ignored */;12738 ConstraintSatisfaction Satisfaction;12739 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),12740 /*ForOverloadResolution=*/true))12741 break;12742 S.DiagnoseUnsatisfiedConstraint(Satisfaction);12743 }12744 }12745}12746 12747static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {12748 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))12749 return;12750 12751 // Desugar the type of the surrogate down to a function type,12752 // retaining as many typedefs as possible while still showing12753 // the function type (and, therefore, its parameter types).12754 QualType FnType = Cand->Surrogate->getConversionType();12755 bool isLValueReference = false;12756 bool isRValueReference = false;12757 bool isPointer = false;12758 if (const LValueReferenceType *FnTypeRef =12759 FnType->getAs<LValueReferenceType>()) {12760 FnType = FnTypeRef->getPointeeType();12761 isLValueReference = true;12762 } else if (const RValueReferenceType *FnTypeRef =12763 FnType->getAs<RValueReferenceType>()) {12764 FnType = FnTypeRef->getPointeeType();12765 isRValueReference = true;12766 }12767 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {12768 FnType = FnTypePtr->getPointeeType();12769 isPointer = true;12770 }12771 // Desugar down to a function type.12772 FnType = QualType(FnType->getAs<FunctionType>(), 0);12773 // Reconstruct the pointer/reference as appropriate.12774 if (isPointer) FnType = S.Context.getPointerType(FnType);12775 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);12776 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);12777 12778 if (!Cand->Viable &&12779 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {12780 S.Diag(Cand->Surrogate->getLocation(),12781 diag::note_ovl_surrogate_constraints_not_satisfied)12782 << Cand->Surrogate;12783 ConstraintSatisfaction Satisfaction;12784 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))12785 S.DiagnoseUnsatisfiedConstraint(Satisfaction);12786 } else {12787 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)12788 << FnType;12789 }12790}12791 12792static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,12793 SourceLocation OpLoc,12794 OverloadCandidate *Cand) {12795 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");12796 std::string TypeStr("operator");12797 TypeStr += Opc;12798 TypeStr += "(";12799 TypeStr += Cand->BuiltinParamTypes[0].getAsString();12800 if (Cand->Conversions.size() == 1) {12801 TypeStr += ")";12802 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;12803 } else {12804 TypeStr += ", ";12805 TypeStr += Cand->BuiltinParamTypes[1].getAsString();12806 TypeStr += ")";12807 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;12808 }12809}12810 12811static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,12812 OverloadCandidate *Cand) {12813 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {12814 if (ICS.isBad()) break; // all meaningless after first invalid12815 if (!ICS.isAmbiguous()) continue;12816 12817 ICS.DiagnoseAmbiguousConversion(12818 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));12819 }12820}12821 12822static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {12823 if (Cand->Function)12824 return Cand->Function->getLocation();12825 if (Cand->IsSurrogate)12826 return Cand->Surrogate->getLocation();12827 return SourceLocation();12828}12829 12830static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {12831 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {12832 case TemplateDeductionResult::Success:12833 case TemplateDeductionResult::NonDependentConversionFailure:12834 case TemplateDeductionResult::AlreadyDiagnosed:12835 llvm_unreachable("non-deduction failure while diagnosing bad deduction");12836 12837 case TemplateDeductionResult::Invalid:12838 case TemplateDeductionResult::Incomplete:12839 case TemplateDeductionResult::IncompletePack:12840 return 1;12841 12842 case TemplateDeductionResult::Underqualified:12843 case TemplateDeductionResult::Inconsistent:12844 return 2;12845 12846 case TemplateDeductionResult::SubstitutionFailure:12847 case TemplateDeductionResult::DeducedMismatch:12848 case TemplateDeductionResult::ConstraintsNotSatisfied:12849 case TemplateDeductionResult::DeducedMismatchNested:12850 case TemplateDeductionResult::NonDeducedMismatch:12851 case TemplateDeductionResult::MiscellaneousDeductionFailure:12852 case TemplateDeductionResult::CUDATargetMismatch:12853 return 3;12854 12855 case TemplateDeductionResult::InstantiationDepth:12856 return 4;12857 12858 case TemplateDeductionResult::InvalidExplicitArguments:12859 return 5;12860 12861 case TemplateDeductionResult::TooManyArguments:12862 case TemplateDeductionResult::TooFewArguments:12863 return 6;12864 }12865 llvm_unreachable("Unhandled deduction result");12866}12867 12868namespace {12869 12870struct CompareOverloadCandidatesForDisplay {12871 Sema &S;12872 SourceLocation Loc;12873 size_t NumArgs;12874 OverloadCandidateSet::CandidateSetKind CSK;12875 12876 CompareOverloadCandidatesForDisplay(12877 Sema &S, SourceLocation Loc, size_t NArgs,12878 OverloadCandidateSet::CandidateSetKind CSK)12879 : S(S), NumArgs(NArgs), CSK(CSK) {}12880 12881 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {12882 // If there are too many or too few arguments, that's the high-order bit we12883 // want to sort by, even if the immediate failure kind was something else.12884 if (C->FailureKind == ovl_fail_too_many_arguments ||12885 C->FailureKind == ovl_fail_too_few_arguments)12886 return static_cast<OverloadFailureKind>(C->FailureKind);12887 12888 if (C->Function) {12889 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())12890 return ovl_fail_too_many_arguments;12891 if (NumArgs < C->Function->getMinRequiredArguments())12892 return ovl_fail_too_few_arguments;12893 }12894 12895 return static_cast<OverloadFailureKind>(C->FailureKind);12896 }12897 12898 bool operator()(const OverloadCandidate *L,12899 const OverloadCandidate *R) {12900 // Fast-path this check.12901 if (L == R) return false;12902 12903 // Order first by viability.12904 if (L->Viable) {12905 if (!R->Viable) return true;12906 12907 if (int Ord = CompareConversions(*L, *R))12908 return Ord < 0;12909 // Use other tie breakers.12910 } else if (R->Viable)12911 return false;12912 12913 assert(L->Viable == R->Viable);12914 12915 // Criteria by which we can sort non-viable candidates:12916 if (!L->Viable) {12917 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);12918 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);12919 12920 // 1. Arity mismatches come after other candidates.12921 if (LFailureKind == ovl_fail_too_many_arguments ||12922 LFailureKind == ovl_fail_too_few_arguments) {12923 if (RFailureKind == ovl_fail_too_many_arguments ||12924 RFailureKind == ovl_fail_too_few_arguments) {12925 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);12926 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);12927 if (LDist == RDist) {12928 if (LFailureKind == RFailureKind)12929 // Sort non-surrogates before surrogates.12930 return !L->IsSurrogate && R->IsSurrogate;12931 // Sort candidates requiring fewer parameters than there were12932 // arguments given after candidates requiring more parameters12933 // than there were arguments given.12934 return LFailureKind == ovl_fail_too_many_arguments;12935 }12936 return LDist < RDist;12937 }12938 return false;12939 }12940 if (RFailureKind == ovl_fail_too_many_arguments ||12941 RFailureKind == ovl_fail_too_few_arguments)12942 return true;12943 12944 // 2. Bad conversions come first and are ordered by the number12945 // of bad conversions and quality of good conversions.12946 if (LFailureKind == ovl_fail_bad_conversion) {12947 if (RFailureKind != ovl_fail_bad_conversion)12948 return true;12949 12950 // The conversion that can be fixed with a smaller number of changes,12951 // comes first.12952 unsigned numLFixes = L->Fix.NumConversionsFixed;12953 unsigned numRFixes = R->Fix.NumConversionsFixed;12954 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;12955 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;12956 if (numLFixes != numRFixes) {12957 return numLFixes < numRFixes;12958 }12959 12960 // If there's any ordering between the defined conversions...12961 if (int Ord = CompareConversions(*L, *R))12962 return Ord < 0;12963 } else if (RFailureKind == ovl_fail_bad_conversion)12964 return false;12965 12966 if (LFailureKind == ovl_fail_bad_deduction) {12967 if (RFailureKind != ovl_fail_bad_deduction)12968 return true;12969 12970 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {12971 unsigned LRank = RankDeductionFailure(L->DeductionFailure);12972 unsigned RRank = RankDeductionFailure(R->DeductionFailure);12973 if (LRank != RRank)12974 return LRank < RRank;12975 }12976 } else if (RFailureKind == ovl_fail_bad_deduction)12977 return false;12978 12979 // TODO: others?12980 }12981 12982 // Sort everything else by location.12983 SourceLocation LLoc = GetLocationForCandidate(L);12984 SourceLocation RLoc = GetLocationForCandidate(R);12985 12986 // Put candidates without locations (e.g. builtins) at the end.12987 if (LLoc.isValid() && RLoc.isValid())12988 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);12989 if (LLoc.isValid() && !RLoc.isValid())12990 return true;12991 if (RLoc.isValid() && !LLoc.isValid())12992 return false;12993 assert(!LLoc.isValid() && !RLoc.isValid());12994 // For builtins and other functions without locations, fallback to the order12995 // in which they were added into the candidate set.12996 return L < R;12997 }12998 12999private:13000 struct ConversionSignals {13001 unsigned KindRank = 0;13002 ImplicitConversionRank Rank = ICR_Exact_Match;13003 13004 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {13005 ConversionSignals Sig;13006 Sig.KindRank = Seq.getKindRank();13007 if (Seq.isStandard())13008 Sig.Rank = Seq.Standard.getRank();13009 else if (Seq.isUserDefined())13010 Sig.Rank = Seq.UserDefined.After.getRank();13011 // We intend StaticObjectArgumentConversion to compare the same as13012 // StandardConversion with ICR_ExactMatch rank.13013 return Sig;13014 }13015 13016 static ConversionSignals ForObjectArgument() {13017 // We intend StaticObjectArgumentConversion to compare the same as13018 // StandardConversion with ICR_ExactMatch rank. Default give us that.13019 return {};13020 }13021 };13022 13023 // Returns -1 if conversions in L are considered better.13024 // 0 if they are considered indistinguishable.13025 // 1 if conversions in R are better.13026 int CompareConversions(const OverloadCandidate &L,13027 const OverloadCandidate &R) {13028 // We cannot use `isBetterOverloadCandidate` because it is defined13029 // according to the C++ standard and provides a partial order, but we need13030 // a total order as this function is used in sort.13031 assert(L.Conversions.size() == R.Conversions.size());13032 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {13033 auto LS = L.IgnoreObjectArgument && I == 013034 ? ConversionSignals::ForObjectArgument()13035 : ConversionSignals::ForSequence(L.Conversions[I]);13036 auto RS = R.IgnoreObjectArgument13037 ? ConversionSignals::ForObjectArgument()13038 : ConversionSignals::ForSequence(R.Conversions[I]);13039 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))13040 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)13041 ? -113042 : 1;13043 }13044 // FIXME: find a way to compare templates for being more or less13045 // specialized that provides a strict weak ordering.13046 return 0;13047 }13048};13049}13050 13051/// CompleteNonViableCandidate - Normally, overload resolution only13052/// computes up to the first bad conversion. Produces the FixIt set if13053/// possible.13054static void13055CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,13056 ArrayRef<Expr *> Args,13057 OverloadCandidateSet::CandidateSetKind CSK) {13058 assert(!Cand->Viable);13059 13060 // Don't do anything on failures other than bad conversion.13061 if (Cand->FailureKind != ovl_fail_bad_conversion)13062 return;13063 13064 // We only want the FixIts if all the arguments can be corrected.13065 bool Unfixable = false;13066 // Use a implicit copy initialization to check conversion fixes.13067 Cand->Fix.setConversionChecker(TryCopyInitialization);13068 13069 // Attempt to fix the bad conversion.13070 unsigned ConvCount = Cand->Conversions.size();13071 for (unsigned ConvIdx =13072 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 113073 : 0);13074 /**/; ++ConvIdx) {13075 assert(ConvIdx != ConvCount && "no bad conversion in candidate");13076 if (Cand->Conversions[ConvIdx].isInitialized() &&13077 Cand->Conversions[ConvIdx].isBad()) {13078 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);13079 break;13080 }13081 }13082 13083 // FIXME: this should probably be preserved from the overload13084 // operation somehow.13085 bool SuppressUserConversions = false;13086 13087 unsigned ConvIdx = 0;13088 unsigned ArgIdx = 0;13089 ArrayRef<QualType> ParamTypes;13090 bool Reversed = Cand->isReversed();13091 13092 if (Cand->IsSurrogate) {13093 QualType ConvType13094 = Cand->Surrogate->getConversionType().getNonReferenceType();13095 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())13096 ConvType = ConvPtrType->getPointeeType();13097 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();13098 // Conversion 0 is 'this', which doesn't have a corresponding parameter.13099 ConvIdx = 1;13100 } else if (Cand->Function) {13101 ParamTypes =13102 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();13103 if (isa<CXXMethodDecl>(Cand->Function) &&13104 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed &&13105 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {13106 // Conversion 0 is 'this', which doesn't have a corresponding parameter.13107 ConvIdx = 1;13108 if (CSK == OverloadCandidateSet::CSK_Operator &&13109 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&13110 Cand->Function->getDeclName().getCXXOverloadedOperator() !=13111 OO_Subscript)13112 // Argument 0 is 'this', which doesn't have a corresponding parameter.13113 ArgIdx = 1;13114 }13115 } else {13116 // Builtin operator.13117 assert(ConvCount <= 3);13118 ParamTypes = Cand->BuiltinParamTypes;13119 }13120 13121 // Fill in the rest of the conversions.13122 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;13123 ConvIdx != ConvCount && ArgIdx < Args.size();13124 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {13125 if (Cand->Conversions[ConvIdx].isInitialized()) {13126 // We've already checked this conversion.13127 } else if (ParamIdx < ParamTypes.size()) {13128 if (ParamTypes[ParamIdx]->isDependentType())13129 Cand->Conversions[ConvIdx].setAsIdentityConversion(13130 Args[ArgIdx]->getType());13131 else {13132 Cand->Conversions[ConvIdx] =13133 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],13134 SuppressUserConversions,13135 /*InOverloadResolution=*/true,13136 /*AllowObjCWritebackConversion=*/13137 S.getLangOpts().ObjCAutoRefCount);13138 // Store the FixIt in the candidate if it exists.13139 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())13140 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);13141 }13142 } else13143 Cand->Conversions[ConvIdx].setEllipsis();13144 }13145}13146 13147SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(13148 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,13149 SourceLocation OpLoc,13150 llvm::function_ref<bool(OverloadCandidate &)> Filter) {13151 13152 InjectNonDeducedTemplateCandidates(S);13153 13154 // Sort the candidates by viability and position. Sorting directly would13155 // be prohibitive, so we make a set of pointers and sort those.13156 SmallVector<OverloadCandidate*, 32> Cands;13157 if (OCD == OCD_AllCandidates) Cands.reserve(size());13158 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();13159 Cand != LastCand; ++Cand) {13160 if (!Filter(*Cand))13161 continue;13162 switch (OCD) {13163 case OCD_AllCandidates:13164 if (!Cand->Viable) {13165 if (!Cand->Function && !Cand->IsSurrogate) {13166 // This a non-viable builtin candidate. We do not, in general,13167 // want to list every possible builtin candidate.13168 continue;13169 }13170 CompleteNonViableCandidate(S, Cand, Args, Kind);13171 }13172 break;13173 13174 case OCD_ViableCandidates:13175 if (!Cand->Viable)13176 continue;13177 break;13178 13179 case OCD_AmbiguousCandidates:13180 if (!Cand->Best)13181 continue;13182 break;13183 }13184 13185 Cands.push_back(Cand);13186 }13187 13188 llvm::stable_sort(13189 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));13190 13191 return Cands;13192}13193 13194bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,13195 SourceLocation OpLoc) {13196 bool DeferHint = false;13197 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {13198 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or13199 // host device candidates.13200 auto WrongSidedCands =13201 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {13202 return (Cand.Viable == false &&13203 Cand.FailureKind == ovl_fail_bad_target) ||13204 (Cand.Function &&13205 Cand.Function->template hasAttr<CUDAHostAttr>() &&13206 Cand.Function->template hasAttr<CUDADeviceAttr>());13207 });13208 DeferHint = !WrongSidedCands.empty();13209 }13210 return DeferHint;13211}13212 13213/// When overload resolution fails, prints diagnostic messages containing the13214/// candidates in the candidate set.13215void OverloadCandidateSet::NoteCandidates(13216 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,13217 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,13218 llvm::function_ref<bool(OverloadCandidate &)> Filter) {13219 13220 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);13221 13222 {13223 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};13224 S.Diag(PD.first, PD.second);13225 }13226 13227 // In WebAssembly we don't want to emit further diagnostics if a table is13228 // passed as an argument to a function.13229 bool NoteCands = true;13230 for (const Expr *Arg : Args) {13231 if (Arg->getType()->isWebAssemblyTableType())13232 NoteCands = false;13233 }13234 13235 if (NoteCands)13236 NoteCandidates(S, Args, Cands, Opc, OpLoc);13237 13238 if (OCD == OCD_AmbiguousCandidates)13239 MaybeDiagnoseAmbiguousConstraints(S,13240 {Candidates.begin(), Candidates.end()});13241}13242 13243void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,13244 ArrayRef<OverloadCandidate *> Cands,13245 StringRef Opc, SourceLocation OpLoc) {13246 bool ReportedAmbiguousConversions = false;13247 13248 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();13249 unsigned CandsShown = 0;13250 auto I = Cands.begin(), E = Cands.end();13251 for (; I != E; ++I) {13252 OverloadCandidate *Cand = *I;13253 13254 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&13255 ShowOverloads == Ovl_Best) {13256 break;13257 }13258 ++CandsShown;13259 13260 if (Cand->Function)13261 NoteFunctionCandidate(S, Cand, Args.size(),13262 Kind == CSK_AddressOfOverloadSet, DestAS);13263 else if (Cand->IsSurrogate)13264 NoteSurrogateCandidate(S, Cand);13265 else {13266 assert(Cand->Viable &&13267 "Non-viable built-in candidates are not added to Cands.");13268 // Generally we only see ambiguities including viable builtin13269 // operators if overload resolution got screwed up by an13270 // ambiguous user-defined conversion.13271 //13272 // FIXME: It's quite possible for different conversions to see13273 // different ambiguities, though.13274 if (!ReportedAmbiguousConversions) {13275 NoteAmbiguousUserConversions(S, OpLoc, Cand);13276 ReportedAmbiguousConversions = true;13277 }13278 13279 // If this is a viable builtin, print it.13280 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);13281 }13282 }13283 13284 // Inform S.Diags that we've shown an overload set with N elements. This may13285 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().13286 S.Diags.overloadCandidatesShown(CandsShown);13287 13288 if (I != E) {13289 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};13290 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);13291 }13292}13293 13294static SourceLocation13295GetLocationForCandidate(const TemplateSpecCandidate *Cand) {13296 return Cand->Specialization ? Cand->Specialization->getLocation()13297 : SourceLocation();13298}13299 13300namespace {13301struct CompareTemplateSpecCandidatesForDisplay {13302 Sema &S;13303 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}13304 13305 bool operator()(const TemplateSpecCandidate *L,13306 const TemplateSpecCandidate *R) {13307 // Fast-path this check.13308 if (L == R)13309 return false;13310 13311 // Assuming that both candidates are not matches...13312 13313 // Sort by the ranking of deduction failures.13314 if (L->DeductionFailure.Result != R->DeductionFailure.Result)13315 return RankDeductionFailure(L->DeductionFailure) <13316 RankDeductionFailure(R->DeductionFailure);13317 13318 // Sort everything else by location.13319 SourceLocation LLoc = GetLocationForCandidate(L);13320 SourceLocation RLoc = GetLocationForCandidate(R);13321 13322 // Put candidates without locations (e.g. builtins) at the end.13323 if (LLoc.isInvalid())13324 return false;13325 if (RLoc.isInvalid())13326 return true;13327 13328 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);13329 }13330};13331}13332 13333/// Diagnose a template argument deduction failure.13334/// We are treating these failures as overload failures due to bad13335/// deductions.13336void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,13337 bool ForTakingAddress) {13338 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern13339 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);13340}13341 13342void TemplateSpecCandidateSet::destroyCandidates() {13343 for (iterator i = begin(), e = end(); i != e; ++i) {13344 i->DeductionFailure.Destroy();13345 }13346}13347 13348void TemplateSpecCandidateSet::clear() {13349 destroyCandidates();13350 Candidates.clear();13351}13352 13353/// NoteCandidates - When no template specialization match is found, prints13354/// diagnostic messages containing the non-matching specializations that form13355/// the candidate set.13356/// This is analoguous to OverloadCandidateSet::NoteCandidates() with13357/// OCD == OCD_AllCandidates and Cand->Viable == false.13358void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {13359 // Sort the candidates by position (assuming no candidate is a match).13360 // Sorting directly would be prohibitive, so we make a set of pointers13361 // and sort those.13362 SmallVector<TemplateSpecCandidate *, 32> Cands;13363 Cands.reserve(size());13364 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {13365 if (Cand->Specialization)13366 Cands.push_back(Cand);13367 // Otherwise, this is a non-matching builtin candidate. We do not,13368 // in general, want to list every possible builtin candidate.13369 }13370 13371 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));13372 13373 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()13374 // for generalization purposes (?).13375 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();13376 13377 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;13378 unsigned CandsShown = 0;13379 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {13380 TemplateSpecCandidate *Cand = *I;13381 13382 // Set an arbitrary limit on the number of candidates we'll spam13383 // the user with. FIXME: This limit should depend on details of the13384 // candidate list.13385 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)13386 break;13387 ++CandsShown;13388 13389 assert(Cand->Specialization &&13390 "Non-matching built-in candidates are not added to Cands.");13391 Cand->NoteDeductionFailure(S, ForTakingAddress);13392 }13393 13394 if (I != E)13395 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);13396}13397 13398// [PossiblyAFunctionType] --> [Return]13399// NonFunctionType --> NonFunctionType13400// R (A) --> R(A)13401// R (*)(A) --> R (A)13402// R (&)(A) --> R (A)13403// R (S::*)(A) --> R (A)13404QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {13405 QualType Ret = PossiblyAFunctionType;13406 if (const PointerType *ToTypePtr =13407 PossiblyAFunctionType->getAs<PointerType>())13408 Ret = ToTypePtr->getPointeeType();13409 else if (const ReferenceType *ToTypeRef =13410 PossiblyAFunctionType->getAs<ReferenceType>())13411 Ret = ToTypeRef->getPointeeType();13412 else if (const MemberPointerType *MemTypePtr =13413 PossiblyAFunctionType->getAs<MemberPointerType>())13414 Ret = MemTypePtr->getPointeeType();13415 Ret =13416 Context.getCanonicalType(Ret).getUnqualifiedType();13417 return Ret;13418}13419 13420static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,13421 bool Complain = true) {13422 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&13423 S.DeduceReturnType(FD, Loc, Complain))13424 return true;13425 13426 auto *FPT = FD->getType()->castAs<FunctionProtoType>();13427 if (S.getLangOpts().CPlusPlus17 &&13428 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&13429 !S.ResolveExceptionSpec(Loc, FPT))13430 return true;13431 13432 return false;13433}13434 13435namespace {13436// A helper class to help with address of function resolution13437// - allows us to avoid passing around all those ugly parameters13438class AddressOfFunctionResolver {13439 Sema& S;13440 Expr* SourceExpr;13441 const QualType& TargetType;13442 QualType TargetFunctionType; // Extracted function type from target type13443 13444 bool Complain;13445 //DeclAccessPair& ResultFunctionAccessPair;13446 ASTContext& Context;13447 13448 bool TargetTypeIsNonStaticMemberFunction;13449 bool FoundNonTemplateFunction;13450 bool StaticMemberFunctionFromBoundPointer;13451 bool HasComplained;13452 13453 OverloadExpr::FindResult OvlExprInfo;13454 OverloadExpr *OvlExpr;13455 TemplateArgumentListInfo OvlExplicitTemplateArgs;13456 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;13457 TemplateSpecCandidateSet FailedCandidates;13458 13459public:13460 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,13461 const QualType &TargetType, bool Complain)13462 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),13463 Complain(Complain), Context(S.getASTContext()),13464 TargetTypeIsNonStaticMemberFunction(13465 !!TargetType->getAs<MemberPointerType>()),13466 FoundNonTemplateFunction(false),13467 StaticMemberFunctionFromBoundPointer(false),13468 HasComplained(false),13469 OvlExprInfo(OverloadExpr::find(SourceExpr)),13470 OvlExpr(OvlExprInfo.Expression),13471 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {13472 ExtractUnqualifiedFunctionTypeFromTargetType();13473 13474 if (TargetFunctionType->isFunctionType()) {13475 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))13476 if (!UME->isImplicitAccess() &&13477 !S.ResolveSingleFunctionTemplateSpecialization(UME))13478 StaticMemberFunctionFromBoundPointer = true;13479 } else if (OvlExpr->hasExplicitTemplateArgs()) {13480 DeclAccessPair dap;13481 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(13482 OvlExpr, false, &dap)) {13483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))13484 if (!Method->isStatic()) {13485 // If the target type is a non-function type and the function found13486 // is a non-static member function, pretend as if that was the13487 // target, it's the only possible type to end up with.13488 TargetTypeIsNonStaticMemberFunction = true;13489 13490 // And skip adding the function if its not in the proper form.13491 // We'll diagnose this due to an empty set of functions.13492 if (!OvlExprInfo.HasFormOfMemberPointer)13493 return;13494 }13495 13496 Matches.push_back(std::make_pair(dap, Fn));13497 }13498 return;13499 }13500 13501 if (OvlExpr->hasExplicitTemplateArgs())13502 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);13503 13504 if (FindAllFunctionsThatMatchTargetTypeExactly()) {13505 // C++ [over.over]p4:13506 // If more than one function is selected, [...]13507 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {13508 if (FoundNonTemplateFunction) {13509 EliminateAllTemplateMatches();13510 EliminateLessPartialOrderingConstrainedMatches();13511 } else13512 EliminateAllExceptMostSpecializedTemplate();13513 }13514 }13515 13516 if (S.getLangOpts().CUDA && Matches.size() > 1)13517 EliminateSuboptimalCudaMatches();13518 }13519 13520 bool hasComplained() const { return HasComplained; }13521 13522private:13523 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {13524 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||13525 S.IsFunctionConversion(FD->getType(), TargetFunctionType);13526 }13527 13528 /// \return true if A is considered a better overload candidate for the13529 /// desired type than B.13530 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {13531 // If A doesn't have exactly the correct type, we don't want to classify it13532 // as "better" than anything else. This way, the user is required to13533 // disambiguate for us if there are multiple candidates and no exact match.13534 return candidateHasExactlyCorrectType(A) &&13535 (!candidateHasExactlyCorrectType(B) ||13536 compareEnableIfAttrs(S, A, B) == Comparison::Better);13537 }13538 13539 /// \return true if we were able to eliminate all but one overload candidate,13540 /// false otherwise.13541 bool eliminiateSuboptimalOverloadCandidates() {13542 // Same algorithm as overload resolution -- one pass to pick the "best",13543 // another pass to be sure that nothing is better than the best.13544 auto Best = Matches.begin();13545 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)13546 if (isBetterCandidate(I->second, Best->second))13547 Best = I;13548 13549 const FunctionDecl *BestFn = Best->second;13550 auto IsBestOrInferiorToBest = [this, BestFn](13551 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {13552 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);13553 };13554 13555 // Note: We explicitly leave Matches unmodified if there isn't a clear best13556 // option, so we can potentially give the user a better error13557 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))13558 return false;13559 Matches[0] = *Best;13560 Matches.resize(1);13561 return true;13562 }13563 13564 bool isTargetTypeAFunction() const {13565 return TargetFunctionType->isFunctionType();13566 }13567 13568 // [ToType] [Return]13569 13570 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false13571 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false13572 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true13573 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {13574 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);13575 }13576 13577 // return true if any matching specializations were found13578 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,13579 const DeclAccessPair& CurAccessFunPair) {13580 if (CXXMethodDecl *Method13581 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {13582 // Skip non-static function templates when converting to pointer, and13583 // static when converting to member pointer.13584 bool CanConvertToFunctionPointer =13585 Method->isStatic() || Method->isExplicitObjectMemberFunction();13586 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)13587 return false;13588 }13589 else if (TargetTypeIsNonStaticMemberFunction)13590 return false;13591 13592 // C++ [over.over]p2:13593 // If the name is a function template, template argument deduction is13594 // done (14.8.2.2), and if the argument deduction succeeds, the13595 // resulting template argument list is used to generate a single13596 // function template specialization, which is added to the set of13597 // overloaded functions considered.13598 FunctionDecl *Specialization = nullptr;13599 TemplateDeductionInfo Info(FailedCandidates.getLocation());13600 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(13601 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,13602 Specialization, Info, /*IsAddressOfFunction*/ true);13603 Result != TemplateDeductionResult::Success) {13604 // Make a note of the failed deduction for diagnostics.13605 FailedCandidates.addCandidate()13606 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),13607 MakeDeductionFailureInfo(Context, Result, Info));13608 return false;13609 }13610 13611 // Template argument deduction ensures that we have an exact match or13612 // compatible pointer-to-function arguments that would be adjusted by ICS.13613 // This function template specicalization works.13614 assert(S.isSameOrCompatibleFunctionType(13615 Context.getCanonicalType(Specialization->getType()),13616 Context.getCanonicalType(TargetFunctionType)));13617 13618 if (!S.checkAddressOfFunctionIsAvailable(Specialization))13619 return false;13620 13621 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));13622 return true;13623 }13624 13625 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,13626 const DeclAccessPair& CurAccessFunPair) {13627 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {13628 // Skip non-static functions when converting to pointer, and static13629 // when converting to member pointer.13630 bool CanConvertToFunctionPointer =13631 Method->isStatic() || Method->isExplicitObjectMemberFunction();13632 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)13633 return false;13634 }13635 else if (TargetTypeIsNonStaticMemberFunction)13636 return false;13637 13638 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {13639 if (S.getLangOpts().CUDA) {13640 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);13641 if (!(Caller && Caller->isImplicit()) &&13642 !S.CUDA().IsAllowedCall(Caller, FunDecl))13643 return false;13644 }13645 if (FunDecl->isMultiVersion()) {13646 const auto *TA = FunDecl->getAttr<TargetAttr>();13647 if (TA && !TA->isDefaultVersion())13648 return false;13649 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();13650 if (TVA && !TVA->isDefaultVersion())13651 return false;13652 }13653 13654 // If any candidate has a placeholder return type, trigger its deduction13655 // now.13656 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),13657 Complain)) {13658 HasComplained |= Complain;13659 return false;13660 }13661 13662 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))13663 return false;13664 13665 // If we're in C, we need to support types that aren't exactly identical.13666 if (!S.getLangOpts().CPlusPlus ||13667 candidateHasExactlyCorrectType(FunDecl)) {13668 Matches.push_back(std::make_pair(13669 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));13670 FoundNonTemplateFunction = true;13671 return true;13672 }13673 }13674 13675 return false;13676 }13677 13678 bool FindAllFunctionsThatMatchTargetTypeExactly() {13679 bool Ret = false;13680 13681 // If the overload expression doesn't have the form of a pointer to13682 // member, don't try to convert it to a pointer-to-member type.13683 if (IsInvalidFormOfPointerToMemberFunction())13684 return false;13685 13686 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),13687 E = OvlExpr->decls_end();13688 I != E; ++I) {13689 // Look through any using declarations to find the underlying function.13690 NamedDecl *Fn = (*I)->getUnderlyingDecl();13691 13692 // C++ [over.over]p3:13693 // Non-member functions and static member functions match13694 // targets of type "pointer-to-function" or "reference-to-function."13695 // Nonstatic member functions match targets of13696 // type "pointer-to-member-function."13697 // Note that according to DR 247, the containing class does not matter.13698 if (FunctionTemplateDecl *FunctionTemplate13699 = dyn_cast<FunctionTemplateDecl>(Fn)) {13700 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))13701 Ret = true;13702 }13703 // If we have explicit template arguments supplied, skip non-templates.13704 else if (!OvlExpr->hasExplicitTemplateArgs() &&13705 AddMatchingNonTemplateFunction(Fn, I.getPair()))13706 Ret = true;13707 }13708 assert(Ret || Matches.empty());13709 return Ret;13710 }13711 13712 void EliminateAllExceptMostSpecializedTemplate() {13713 // [...] and any given function template specialization F1 is13714 // eliminated if the set contains a second function template13715 // specialization whose function template is more specialized13716 // than the function template of F1 according to the partial13717 // ordering rules of 14.5.5.2.13718 13719 // The algorithm specified above is quadratic. We instead use a13720 // two-pass algorithm (similar to the one used to identify the13721 // best viable function in an overload set) that identifies the13722 // best function template (if it exists).13723 13724 UnresolvedSet<4> MatchesCopy; // TODO: avoid!13725 for (unsigned I = 0, E = Matches.size(); I != E; ++I)13726 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());13727 13728 // TODO: It looks like FailedCandidates does not serve much purpose13729 // here, since the no_viable diagnostic has index 0.13730 UnresolvedSetIterator Result = S.getMostSpecialized(13731 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,13732 SourceExpr->getBeginLoc(), S.PDiag(),13733 S.PDiag(diag::err_addr_ovl_ambiguous)13734 << Matches[0].second->getDeclName(),13735 S.PDiag(diag::note_ovl_candidate)13736 << (unsigned)oc_function << (unsigned)ocs_described_template,13737 Complain, TargetFunctionType);13738 13739 if (Result != MatchesCopy.end()) {13740 // Make it the first and only element13741 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;13742 Matches[0].second = cast<FunctionDecl>(*Result);13743 Matches.resize(1);13744 } else13745 HasComplained |= Complain;13746 }13747 13748 void EliminateAllTemplateMatches() {13749 // [...] any function template specializations in the set are13750 // eliminated if the set also contains a non-template function, [...]13751 for (unsigned I = 0, N = Matches.size(); I != N; ) {13752 if (Matches[I].second->getPrimaryTemplate() == nullptr)13753 ++I;13754 else {13755 Matches[I] = Matches[--N];13756 Matches.resize(N);13757 }13758 }13759 }13760 13761 void EliminateLessPartialOrderingConstrainedMatches() {13762 // C++ [over.over]p5:13763 // [...] Any given non-template function F0 is eliminated if the set13764 // contains a second non-template function that is more13765 // partial-ordering-constrained than F0. [...]13766 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&13767 "Call EliminateAllTemplateMatches() first");13768 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;13769 Results.push_back(Matches[0]);13770 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {13771 assert(Matches[I].second->getPrimaryTemplate() == nullptr);13772 FunctionDecl *F = getMorePartialOrderingConstrained(13773 S, Matches[I].second, Results[0].second,13774 /*IsFn1Reversed=*/false,13775 /*IsFn2Reversed=*/false);13776 if (!F) {13777 Results.push_back(Matches[I]);13778 continue;13779 }13780 if (F == Matches[I].second) {13781 Results.clear();13782 Results.push_back(Matches[I]);13783 }13784 }13785 std::swap(Matches, Results);13786 }13787 13788 void EliminateSuboptimalCudaMatches() {13789 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),13790 Matches);13791 }13792 13793public:13794 void ComplainNoMatchesFound() const {13795 assert(Matches.empty());13796 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)13797 << OvlExpr->getName() << TargetFunctionType13798 << OvlExpr->getSourceRange();13799 if (FailedCandidates.empty())13800 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,13801 /*TakingAddress=*/true);13802 else {13803 // We have some deduction failure messages. Use them to diagnose13804 // the function templates, and diagnose the non-template candidates13805 // normally.13806 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),13807 IEnd = OvlExpr->decls_end();13808 I != IEnd; ++I)13809 if (FunctionDecl *Fun =13810 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))13811 if (!functionHasPassObjectSizeParams(Fun))13812 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,13813 /*TakingAddress=*/true);13814 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());13815 }13816 }13817 13818 bool IsInvalidFormOfPointerToMemberFunction() const {13819 return TargetTypeIsNonStaticMemberFunction &&13820 !OvlExprInfo.HasFormOfMemberPointer;13821 }13822 13823 void ComplainIsInvalidFormOfPointerToMemberFunction() const {13824 // TODO: Should we condition this on whether any functions might13825 // have matched, or is it more appropriate to do that in callers?13826 // TODO: a fixit wouldn't hurt.13827 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)13828 << TargetType << OvlExpr->getSourceRange();13829 }13830 13831 bool IsStaticMemberFunctionFromBoundPointer() const {13832 return StaticMemberFunctionFromBoundPointer;13833 }13834 13835 void ComplainIsStaticMemberFunctionFromBoundPointer() const {13836 S.Diag(OvlExpr->getBeginLoc(),13837 diag::err_invalid_form_pointer_member_function)13838 << OvlExpr->getSourceRange();13839 }13840 13841 void ComplainOfInvalidConversion() const {13842 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)13843 << OvlExpr->getName() << TargetType;13844 }13845 13846 void ComplainMultipleMatchesFound() const {13847 assert(Matches.size() > 1);13848 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)13849 << OvlExpr->getName() << OvlExpr->getSourceRange();13850 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,13851 /*TakingAddress=*/true);13852 }13853 13854 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }13855 13856 int getNumMatches() const { return Matches.size(); }13857 13858 FunctionDecl* getMatchingFunctionDecl() const {13859 if (Matches.size() != 1) return nullptr;13860 return Matches[0].second;13861 }13862 13863 const DeclAccessPair* getMatchingFunctionAccessPair() const {13864 if (Matches.size() != 1) return nullptr;13865 return &Matches[0].first;13866 }13867};13868}13869 13870FunctionDecl *13871Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,13872 QualType TargetType,13873 bool Complain,13874 DeclAccessPair &FoundResult,13875 bool *pHadMultipleCandidates) {13876 assert(AddressOfExpr->getType() == Context.OverloadTy);13877 13878 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,13879 Complain);13880 int NumMatches = Resolver.getNumMatches();13881 FunctionDecl *Fn = nullptr;13882 bool ShouldComplain = Complain && !Resolver.hasComplained();13883 if (NumMatches == 0 && ShouldComplain) {13884 if (Resolver.IsInvalidFormOfPointerToMemberFunction())13885 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();13886 else13887 Resolver.ComplainNoMatchesFound();13888 }13889 else if (NumMatches > 1 && ShouldComplain)13890 Resolver.ComplainMultipleMatchesFound();13891 else if (NumMatches == 1) {13892 Fn = Resolver.getMatchingFunctionDecl();13893 assert(Fn);13894 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())13895 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);13896 FoundResult = *Resolver.getMatchingFunctionAccessPair();13897 if (Complain) {13898 if (Resolver.IsStaticMemberFunctionFromBoundPointer())13899 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();13900 else13901 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);13902 }13903 }13904 13905 if (pHadMultipleCandidates)13906 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();13907 return Fn;13908}13909 13910FunctionDecl *13911Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {13912 OverloadExpr::FindResult R = OverloadExpr::find(E);13913 OverloadExpr *Ovl = R.Expression;13914 bool IsResultAmbiguous = false;13915 FunctionDecl *Result = nullptr;13916 DeclAccessPair DAP;13917 SmallVector<FunctionDecl *, 2> AmbiguousDecls;13918 13919 // Return positive for better, negative for worse, 0 for equal preference.13920 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {13921 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);13922 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -13923 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));13924 };13925 13926 // Don't use the AddressOfResolver because we're specifically looking for13927 // cases where we have one overload candidate that lacks13928 // enable_if/pass_object_size/...13929 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {13930 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());13931 if (!FD)13932 return nullptr;13933 13934 if (!checkAddressOfFunctionIsAvailable(FD))13935 continue;13936 13937 // If we found a better result, update Result.13938 auto FoundBetter = [&]() {13939 IsResultAmbiguous = false;13940 DAP = I.getPair();13941 Result = FD;13942 };13943 13944 // We have more than one result - see if it is more13945 // partial-ordering-constrained than the previous one.13946 if (Result) {13947 // Check CUDA preference first. If the candidates have differennt CUDA13948 // preference, choose the one with higher CUDA preference. Otherwise,13949 // choose the one with more constraints.13950 if (getLangOpts().CUDA) {13951 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);13952 // FD has different preference than Result.13953 if (PreferenceByCUDA != 0) {13954 // FD is more preferable than Result.13955 if (PreferenceByCUDA > 0)13956 FoundBetter();13957 continue;13958 }13959 }13960 // FD has the same CUDA preference than Result. Continue to check13961 // constraints.13962 13963 // C++ [over.over]p5:13964 // [...] Any given non-template function F0 is eliminated if the set13965 // contains a second non-template function that is more13966 // partial-ordering-constrained than F0 [...]13967 FunctionDecl *MoreConstrained =13968 getMorePartialOrderingConstrained(*this, FD, Result,13969 /*IsFn1Reversed=*/false,13970 /*IsFn2Reversed=*/false);13971 if (MoreConstrained != FD) {13972 if (!MoreConstrained) {13973 IsResultAmbiguous = true;13974 AmbiguousDecls.push_back(FD);13975 }13976 continue;13977 }13978 // FD is more constrained - replace Result with it.13979 }13980 FoundBetter();13981 }13982 13983 if (IsResultAmbiguous)13984 return nullptr;13985 13986 if (Result) {13987 // We skipped over some ambiguous declarations which might be ambiguous with13988 // the selected result.13989 for (FunctionDecl *Skipped : AmbiguousDecls) {13990 // If skipped candidate has different CUDA preference than the result,13991 // there is no ambiguity. Otherwise check whether they have different13992 // constraints.13993 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)13994 continue;13995 if (!getMoreConstrainedFunction(Skipped, Result))13996 return nullptr;13997 }13998 Pair = DAP;13999 }14000 return Result;14001}14002 14003bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(14004 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {14005 Expr *E = SrcExpr.get();14006 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");14007 14008 DeclAccessPair DAP;14009 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);14010 if (!Found || Found->isCPUDispatchMultiVersion() ||14011 Found->isCPUSpecificMultiVersion())14012 return false;14013 14014 // Emitting multiple diagnostics for a function that is both inaccessible and14015 // unavailable is consistent with our behavior elsewhere. So, always check14016 // for both.14017 DiagnoseUseOfDecl(Found, E->getExprLoc());14018 CheckAddressOfMemberAccess(E, DAP);14019 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);14020 if (Res.isInvalid())14021 return false;14022 Expr *Fixed = Res.get();14023 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())14024 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);14025 else14026 SrcExpr = Fixed;14027 return true;14028}14029 14030FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(14031 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,14032 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {14033 // C++ [over.over]p1:14034 // [...] [Note: any redundant set of parentheses surrounding the14035 // overloaded function name is ignored (5.1). ]14036 // C++ [over.over]p1:14037 // [...] The overloaded function name can be preceded by the &14038 // operator.14039 14040 // If we didn't actually find any template-ids, we're done.14041 if (!ovl->hasExplicitTemplateArgs())14042 return nullptr;14043 14044 TemplateArgumentListInfo ExplicitTemplateArgs;14045 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);14046 14047 // Look through all of the overloaded functions, searching for one14048 // whose type matches exactly.14049 FunctionDecl *Matched = nullptr;14050 for (UnresolvedSetIterator I = ovl->decls_begin(),14051 E = ovl->decls_end(); I != E; ++I) {14052 // C++0x [temp.arg.explicit]p3:14053 // [...] In contexts where deduction is done and fails, or in contexts14054 // where deduction is not done, if a template argument list is14055 // specified and it, along with any default template arguments,14056 // identifies a single function template specialization, then the14057 // template-id is an lvalue for the function template specialization.14058 FunctionTemplateDecl *FunctionTemplate =14059 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());14060 if (!FunctionTemplate)14061 continue;14062 14063 // C++ [over.over]p2:14064 // If the name is a function template, template argument deduction is14065 // done (14.8.2.2), and if the argument deduction succeeds, the14066 // resulting template argument list is used to generate a single14067 // function template specialization, which is added to the set of14068 // overloaded functions considered.14069 FunctionDecl *Specialization = nullptr;14070 TemplateDeductionInfo Info(ovl->getNameLoc());14071 if (TemplateDeductionResult Result = DeduceTemplateArguments(14072 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,14073 /*IsAddressOfFunction*/ true);14074 Result != TemplateDeductionResult::Success) {14075 // Make a note of the failed deduction for diagnostics.14076 if (FailedTSC)14077 FailedTSC->addCandidate().set(14078 I.getPair(), FunctionTemplate->getTemplatedDecl(),14079 MakeDeductionFailureInfo(Context, Result, Info));14080 continue;14081 }14082 14083 assert(Specialization && "no specialization and no error?");14084 14085 // C++ [temp.deduct.call]p6:14086 // [...] If all successful deductions yield the same deduced A, that14087 // deduced A is the result of deduction; otherwise, the parameter is14088 // treated as a non-deduced context.14089 if (Matched) {14090 if (ForTypeDeduction &&14091 isSameOrCompatibleFunctionType(Matched->getType(),14092 Specialization->getType()))14093 continue;14094 // Multiple matches; we can't resolve to a single declaration.14095 if (Complain) {14096 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)14097 << ovl->getName();14098 NoteAllOverloadCandidates(ovl);14099 }14100 return nullptr;14101 }14102 14103 Matched = Specialization;14104 if (FoundResult) *FoundResult = I.getPair();14105 }14106 14107 if (Matched &&14108 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))14109 return nullptr;14110 14111 return Matched;14112}14113 14114bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(14115 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,14116 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,14117 unsigned DiagIDForComplaining) {14118 assert(SrcExpr.get()->getType() == Context.OverloadTy);14119 14120 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());14121 14122 DeclAccessPair found;14123 ExprResult SingleFunctionExpression;14124 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(14125 ovl.Expression, /*complain*/ false, &found)) {14126 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {14127 SrcExpr = ExprError();14128 return true;14129 }14130 14131 // It is only correct to resolve to an instance method if we're14132 // resolving a form that's permitted to be a pointer to member.14133 // Otherwise we'll end up making a bound member expression, which14134 // is illegal in all the contexts we resolve like this.14135 if (!ovl.HasFormOfMemberPointer &&14136 isa<CXXMethodDecl>(fn) &&14137 cast<CXXMethodDecl>(fn)->isInstance()) {14138 if (!complain) return false;14139 14140 Diag(ovl.Expression->getExprLoc(),14141 diag::err_bound_member_function)14142 << 0 << ovl.Expression->getSourceRange();14143 14144 // TODO: I believe we only end up here if there's a mix of14145 // static and non-static candidates (otherwise the expression14146 // would have 'bound member' type, not 'overload' type).14147 // Ideally we would note which candidate was chosen and why14148 // the static candidates were rejected.14149 SrcExpr = ExprError();14150 return true;14151 }14152 14153 // Fix the expression to refer to 'fn'.14154 SingleFunctionExpression =14155 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);14156 14157 // If desired, do function-to-pointer decay.14158 if (doFunctionPointerConversion) {14159 SingleFunctionExpression =14160 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());14161 if (SingleFunctionExpression.isInvalid()) {14162 SrcExpr = ExprError();14163 return true;14164 }14165 }14166 }14167 14168 if (!SingleFunctionExpression.isUsable()) {14169 if (complain) {14170 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)14171 << ovl.Expression->getName()14172 << DestTypeForComplaining14173 << OpRangeForComplaining14174 << ovl.Expression->getQualifierLoc().getSourceRange();14175 NoteAllOverloadCandidates(SrcExpr.get());14176 14177 SrcExpr = ExprError();14178 return true;14179 }14180 14181 return false;14182 }14183 14184 SrcExpr = SingleFunctionExpression;14185 return true;14186}14187 14188/// Add a single candidate to the overload set.14189static void AddOverloadedCallCandidate(Sema &S,14190 DeclAccessPair FoundDecl,14191 TemplateArgumentListInfo *ExplicitTemplateArgs,14192 ArrayRef<Expr *> Args,14193 OverloadCandidateSet &CandidateSet,14194 bool PartialOverloading,14195 bool KnownValid) {14196 NamedDecl *Callee = FoundDecl.getDecl();14197 if (isa<UsingShadowDecl>(Callee))14198 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();14199 14200 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {14201 if (ExplicitTemplateArgs) {14202 assert(!KnownValid && "Explicit template arguments?");14203 return;14204 }14205 // Prevent ill-formed function decls to be added as overload candidates.14206 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))14207 return;14208 14209 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,14210 /*SuppressUserConversions=*/false,14211 PartialOverloading);14212 return;14213 }14214 14215 if (FunctionTemplateDecl *FuncTemplate14216 = dyn_cast<FunctionTemplateDecl>(Callee)) {14217 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,14218 ExplicitTemplateArgs, Args, CandidateSet,14219 /*SuppressUserConversions=*/false,14220 PartialOverloading);14221 return;14222 }14223 14224 assert(!KnownValid && "unhandled case in overloaded call candidate");14225}14226 14227void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,14228 ArrayRef<Expr *> Args,14229 OverloadCandidateSet &CandidateSet,14230 bool PartialOverloading) {14231 14232#ifndef NDEBUG14233 // Verify that ArgumentDependentLookup is consistent with the rules14234 // in C++0x [basic.lookup.argdep]p3:14235 //14236 // Let X be the lookup set produced by unqualified lookup (3.4.1)14237 // and let Y be the lookup set produced by argument dependent14238 // lookup (defined as follows). If X contains14239 //14240 // -- a declaration of a class member, or14241 //14242 // -- a block-scope function declaration that is not a14243 // using-declaration, or14244 //14245 // -- a declaration that is neither a function or a function14246 // template14247 //14248 // then Y is empty.14249 14250 if (ULE->requiresADL()) {14251 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),14252 E = ULE->decls_end(); I != E; ++I) {14253 assert(!(*I)->getDeclContext()->isRecord());14254 assert(isa<UsingShadowDecl>(*I) ||14255 !(*I)->getDeclContext()->isFunctionOrMethod());14256 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());14257 }14258 }14259#endif14260 14261 // It would be nice to avoid this copy.14262 TemplateArgumentListInfo TABuffer;14263 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;14264 if (ULE->hasExplicitTemplateArgs()) {14265 ULE->copyTemplateArgumentsInto(TABuffer);14266 ExplicitTemplateArgs = &TABuffer;14267 }14268 14269 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),14270 E = ULE->decls_end(); I != E; ++I)14271 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,14272 CandidateSet, PartialOverloading,14273 /*KnownValid*/ true);14274 14275 if (ULE->requiresADL())14276 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),14277 Args, ExplicitTemplateArgs,14278 CandidateSet, PartialOverloading);14279}14280 14281void Sema::AddOverloadedCallCandidates(14282 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,14283 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {14284 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)14285 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,14286 CandidateSet, false, /*KnownValid*/ false);14287}14288 14289/// Determine whether a declaration with the specified name could be moved into14290/// a different namespace.14291static bool canBeDeclaredInNamespace(const DeclarationName &Name) {14292 switch (Name.getCXXOverloadedOperator()) {14293 case OO_New: case OO_Array_New:14294 case OO_Delete: case OO_Array_Delete:14295 return false;14296 14297 default:14298 return true;14299 }14300}14301 14302/// Attempt to recover from an ill-formed use of a non-dependent name in a14303/// template, where the non-dependent name was declared after the template14304/// was defined. This is common in code written for a compilers which do not14305/// correctly implement two-stage name lookup.14306///14307/// Returns true if a viable candidate was found and a diagnostic was issued.14308static bool DiagnoseTwoPhaseLookup(14309 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,14310 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,14311 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,14312 CXXRecordDecl **FoundInClass = nullptr) {14313 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())14314 return false;14315 14316 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {14317 if (DC->isTransparentContext())14318 continue;14319 14320 SemaRef.LookupQualifiedName(R, DC);14321 14322 if (!R.empty()) {14323 R.suppressDiagnostics();14324 14325 OverloadCandidateSet Candidates(FnLoc, CSK);14326 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,14327 Candidates);14328 14329 OverloadCandidateSet::iterator Best;14330 OverloadingResult OR =14331 Candidates.BestViableFunction(SemaRef, FnLoc, Best);14332 14333 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {14334 // We either found non-function declarations or a best viable function14335 // at class scope. A class-scope lookup result disables ADL. Don't14336 // look past this, but let the caller know that we found something that14337 // either is, or might be, usable in this class.14338 if (FoundInClass) {14339 *FoundInClass = RD;14340 if (OR == OR_Success) {14341 R.clear();14342 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());14343 R.resolveKind();14344 }14345 }14346 return false;14347 }14348 14349 if (OR != OR_Success) {14350 // There wasn't a unique best function or function template.14351 return false;14352 }14353 14354 // Find the namespaces where ADL would have looked, and suggest14355 // declaring the function there instead.14356 Sema::AssociatedNamespaceSet AssociatedNamespaces;14357 Sema::AssociatedClassSet AssociatedClasses;14358 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,14359 AssociatedNamespaces,14360 AssociatedClasses);14361 Sema::AssociatedNamespaceSet SuggestedNamespaces;14362 if (canBeDeclaredInNamespace(R.getLookupName())) {14363 DeclContext *Std = SemaRef.getStdNamespace();14364 for (Sema::AssociatedNamespaceSet::iterator14365 it = AssociatedNamespaces.begin(),14366 end = AssociatedNamespaces.end(); it != end; ++it) {14367 // Never suggest declaring a function within namespace 'std'.14368 if (Std && Std->Encloses(*it))14369 continue;14370 14371 // Never suggest declaring a function within a namespace with a14372 // reserved name, like __gnu_cxx.14373 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);14374 if (NS &&14375 NS->getQualifiedNameAsString().find("__") != std::string::npos)14376 continue;14377 14378 SuggestedNamespaces.insert(*it);14379 }14380 }14381 14382 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)14383 << R.getLookupName();14384 if (SuggestedNamespaces.empty()) {14385 SemaRef.Diag(Best->Function->getLocation(),14386 diag::note_not_found_by_two_phase_lookup)14387 << R.getLookupName() << 0;14388 } else if (SuggestedNamespaces.size() == 1) {14389 SemaRef.Diag(Best->Function->getLocation(),14390 diag::note_not_found_by_two_phase_lookup)14391 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();14392 } else {14393 // FIXME: It would be useful to list the associated namespaces here,14394 // but the diagnostics infrastructure doesn't provide a way to produce14395 // a localized representation of a list of items.14396 SemaRef.Diag(Best->Function->getLocation(),14397 diag::note_not_found_by_two_phase_lookup)14398 << R.getLookupName() << 2;14399 }14400 14401 // Try to recover by calling this function.14402 return true;14403 }14404 14405 R.clear();14406 }14407 14408 return false;14409}14410 14411/// Attempt to recover from ill-formed use of a non-dependent operator in a14412/// template, where the non-dependent operator was declared after the template14413/// was defined.14414///14415/// Returns true if a viable candidate was found and a diagnostic was issued.14416static bool14417DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,14418 SourceLocation OpLoc,14419 ArrayRef<Expr *> Args) {14420 DeclarationName OpName =14421 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);14422 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);14423 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,14424 OverloadCandidateSet::CSK_Operator,14425 /*ExplicitTemplateArgs=*/nullptr, Args);14426}14427 14428namespace {14429class BuildRecoveryCallExprRAII {14430 Sema &SemaRef;14431 Sema::SatisfactionStackResetRAII SatStack;14432 14433public:14434 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {14435 assert(SemaRef.IsBuildingRecoveryCallExpr == false);14436 SemaRef.IsBuildingRecoveryCallExpr = true;14437 }14438 14439 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }14440};14441}14442 14443/// Attempts to recover from a call where no functions were found.14444///14445/// This function will do one of three things:14446/// * Diagnose, recover, and return a recovery expression.14447/// * Diagnose, fail to recover, and return ExprError().14448/// * Do not diagnose, do not recover, and return ExprResult(). The caller is14449/// expected to diagnose as appropriate.14450static ExprResult14451BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,14452 UnresolvedLookupExpr *ULE,14453 SourceLocation LParenLoc,14454 MutableArrayRef<Expr *> Args,14455 SourceLocation RParenLoc,14456 bool EmptyLookup, bool AllowTypoCorrection) {14457 // Do not try to recover if it is already building a recovery call.14458 // This stops infinite loops for template instantiations like14459 //14460 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}14461 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}14462 if (SemaRef.IsBuildingRecoveryCallExpr)14463 return ExprResult();14464 BuildRecoveryCallExprRAII RCE(SemaRef);14465 14466 CXXScopeSpec SS;14467 SS.Adopt(ULE->getQualifierLoc());14468 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();14469 14470 TemplateArgumentListInfo TABuffer;14471 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;14472 if (ULE->hasExplicitTemplateArgs()) {14473 ULE->copyTemplateArgumentsInto(TABuffer);14474 ExplicitTemplateArgs = &TABuffer;14475 }14476 14477 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),14478 Sema::LookupOrdinaryName);14479 CXXRecordDecl *FoundInClass = nullptr;14480 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,14481 OverloadCandidateSet::CSK_Normal,14482 ExplicitTemplateArgs, Args, &FoundInClass)) {14483 // OK, diagnosed a two-phase lookup issue.14484 } else if (EmptyLookup) {14485 // Try to recover from an empty lookup with typo correction.14486 R.clear();14487 NoTypoCorrectionCCC NoTypoValidator{};14488 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),14489 ExplicitTemplateArgs != nullptr,14490 dyn_cast<MemberExpr>(Fn));14491 CorrectionCandidateCallback &Validator =14492 AllowTypoCorrection14493 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)14494 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);14495 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,14496 Args))14497 return ExprError();14498 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {14499 // We found a usable declaration of the name in a dependent base of some14500 // enclosing class.14501 // FIXME: We should also explain why the candidates found by name lookup14502 // were not viable.14503 if (SemaRef.DiagnoseDependentMemberLookup(R))14504 return ExprError();14505 } else {14506 // We had viable candidates and couldn't recover; let the caller diagnose14507 // this.14508 return ExprResult();14509 }14510 14511 // If we get here, we should have issued a diagnostic and formed a recovery14512 // lookup result.14513 assert(!R.empty() && "lookup results empty despite recovery");14514 14515 // If recovery created an ambiguity, just bail out.14516 if (R.isAmbiguous()) {14517 R.suppressDiagnostics();14518 return ExprError();14519 }14520 14521 // Build an implicit member call if appropriate. Just drop the14522 // casts and such from the call, we don't really care.14523 ExprResult NewFn = ExprError();14524 if ((*R.begin())->isCXXClassMember())14525 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,14526 ExplicitTemplateArgs, S);14527 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())14528 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,14529 ExplicitTemplateArgs);14530 else14531 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);14532 14533 if (NewFn.isInvalid())14534 return ExprError();14535 14536 // This shouldn't cause an infinite loop because we're giving it14537 // an expression with viable lookup results, which should never14538 // end up here.14539 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,14540 MultiExprArg(Args.data(), Args.size()),14541 RParenLoc);14542}14543 14544bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,14545 UnresolvedLookupExpr *ULE,14546 MultiExprArg Args,14547 SourceLocation RParenLoc,14548 OverloadCandidateSet *CandidateSet,14549 ExprResult *Result) {14550#ifndef NDEBUG14551 if (ULE->requiresADL()) {14552 // To do ADL, we must have found an unqualified name.14553 assert(!ULE->getQualifier() && "qualified name with ADL");14554 14555 // We don't perform ADL for implicit declarations of builtins.14556 // Verify that this was correctly set up.14557 FunctionDecl *F;14558 if (ULE->decls_begin() != ULE->decls_end() &&14559 ULE->decls_begin() + 1 == ULE->decls_end() &&14560 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&14561 F->getBuiltinID() && F->isImplicit())14562 llvm_unreachable("performing ADL for builtin");14563 14564 // We don't perform ADL in C.14565 assert(getLangOpts().CPlusPlus && "ADL enabled in C");14566 }14567#endif14568 14569 UnbridgedCastsSet UnbridgedCasts;14570 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {14571 *Result = ExprError();14572 return true;14573 }14574 14575 // Add the functions denoted by the callee to the set of candidate14576 // functions, including those from argument-dependent lookup.14577 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);14578 14579 if (getLangOpts().MSVCCompat &&14580 CurContext->isDependentContext() && !isSFINAEContext() &&14581 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {14582 14583 OverloadCandidateSet::iterator Best;14584 if (CandidateSet->empty() ||14585 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==14586 OR_No_Viable_Function) {14587 // In Microsoft mode, if we are inside a template class member function14588 // then create a type dependent CallExpr. The goal is to postpone name14589 // lookup to instantiation time to be able to search into type dependent14590 // base classes.14591 CallExpr *CE =14592 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,14593 RParenLoc, CurFPFeatureOverrides());14594 CE->markDependentForPostponedNameLookup();14595 *Result = CE;14596 return true;14597 }14598 }14599 14600 if (CandidateSet->empty())14601 return false;14602 14603 UnbridgedCasts.restore();14604 return false;14605}14606 14607// Guess at what the return type for an unresolvable overload should be.14608static QualType chooseRecoveryType(OverloadCandidateSet &CS,14609 OverloadCandidateSet::iterator *Best) {14610 std::optional<QualType> Result;14611 // Adjust Type after seeing a candidate.14612 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {14613 if (!Candidate.Function)14614 return;14615 if (Candidate.Function->isInvalidDecl())14616 return;14617 QualType T = Candidate.Function->getReturnType();14618 if (T.isNull())14619 return;14620 if (!Result)14621 Result = T;14622 else if (Result != T)14623 Result = QualType();14624 };14625 14626 // Look for an unambiguous type from a progressively larger subset.14627 // e.g. if types disagree, but all *viable* overloads return int, choose int.14628 //14629 // First, consider only the best candidate.14630 if (Best && *Best != CS.end())14631 ConsiderCandidate(**Best);14632 // Next, consider only viable candidates.14633 if (!Result)14634 for (const auto &C : CS)14635 if (C.Viable)14636 ConsiderCandidate(C);14637 // Finally, consider all candidates.14638 if (!Result)14639 for (const auto &C : CS)14640 ConsiderCandidate(C);14641 14642 if (!Result)14643 return QualType();14644 auto Value = *Result;14645 if (Value.isNull() || Value->isUndeducedType())14646 return QualType();14647 return Value;14648}14649 14650/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns14651/// the completed call expression. If overload resolution fails, emits14652/// diagnostics and returns ExprError()14653static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,14654 UnresolvedLookupExpr *ULE,14655 SourceLocation LParenLoc,14656 MultiExprArg Args,14657 SourceLocation RParenLoc,14658 Expr *ExecConfig,14659 OverloadCandidateSet *CandidateSet,14660 OverloadCandidateSet::iterator *Best,14661 OverloadingResult OverloadResult,14662 bool AllowTypoCorrection) {14663 switch (OverloadResult) {14664 case OR_Success: {14665 FunctionDecl *FDecl = (*Best)->Function;14666 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);14667 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))14668 return ExprError();14669 ExprResult Res =14670 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);14671 if (Res.isInvalid())14672 return ExprError();14673 return SemaRef.BuildResolvedCallExpr(14674 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,14675 /*IsExecConfig=*/false,14676 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));14677 }14678 14679 case OR_No_Viable_Function: {14680 if (*Best != CandidateSet->end() &&14681 CandidateSet->getKind() ==14682 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {14683 if (CXXMethodDecl *M =14684 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);14685 M && M->isImplicitObjectMemberFunction()) {14686 CandidateSet->NoteCandidates(14687 PartialDiagnosticAt(14688 Fn->getBeginLoc(),14689 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),14690 SemaRef, OCD_AmbiguousCandidates, Args);14691 return ExprError();14692 }14693 }14694 14695 // Try to recover by looking for viable functions which the user might14696 // have meant to call.14697 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,14698 Args, RParenLoc,14699 CandidateSet->empty(),14700 AllowTypoCorrection);14701 if (Recovery.isInvalid() || Recovery.isUsable())14702 return Recovery;14703 14704 // If the user passes in a function that we can't take the address of, we14705 // generally end up emitting really bad error messages. Here, we attempt to14706 // emit better ones.14707 for (const Expr *Arg : Args) {14708 if (!Arg->getType()->isFunctionType())14709 continue;14710 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {14711 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());14712 if (FD &&14713 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,14714 Arg->getExprLoc()))14715 return ExprError();14716 }14717 }14718 14719 CandidateSet->NoteCandidates(14720 PartialDiagnosticAt(14721 Fn->getBeginLoc(),14722 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)14723 << ULE->getName() << Fn->getSourceRange()),14724 SemaRef, OCD_AllCandidates, Args);14725 break;14726 }14727 14728 case OR_Ambiguous:14729 CandidateSet->NoteCandidates(14730 PartialDiagnosticAt(Fn->getBeginLoc(),14731 SemaRef.PDiag(diag::err_ovl_ambiguous_call)14732 << ULE->getName() << Fn->getSourceRange()),14733 SemaRef, OCD_AmbiguousCandidates, Args);14734 break;14735 14736 case OR_Deleted: {14737 FunctionDecl *FDecl = (*Best)->Function;14738 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),14739 Fn->getSourceRange(), ULE->getName(),14740 *CandidateSet, FDecl, Args);14741 14742 // We emitted an error for the unavailable/deleted function call but keep14743 // the call in the AST.14744 ExprResult Res =14745 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);14746 if (Res.isInvalid())14747 return ExprError();14748 return SemaRef.BuildResolvedCallExpr(14749 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,14750 /*IsExecConfig=*/false,14751 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));14752 }14753 }14754 14755 // Overload resolution failed, try to recover.14756 SmallVector<Expr *, 8> SubExprs = {Fn};14757 SubExprs.append(Args.begin(), Args.end());14758 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,14759 chooseRecoveryType(*CandidateSet, Best));14760}14761 14762static void markUnaddressableCandidatesUnviable(Sema &S,14763 OverloadCandidateSet &CS) {14764 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {14765 if (I->Viable &&14766 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {14767 I->Viable = false;14768 I->FailureKind = ovl_fail_addr_not_available;14769 }14770 }14771}14772 14773ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,14774 UnresolvedLookupExpr *ULE,14775 SourceLocation LParenLoc,14776 MultiExprArg Args,14777 SourceLocation RParenLoc,14778 Expr *ExecConfig,14779 bool AllowTypoCorrection,14780 bool CalleesAddressIsTaken) {14781 14782 OverloadCandidateSet::CandidateSetKind CSK =14783 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet14784 : OverloadCandidateSet::CSK_Normal;14785 14786 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);14787 ExprResult result;14788 14789 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,14790 &result))14791 return result;14792 14793 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that14794 // functions that aren't addressible are considered unviable.14795 if (CalleesAddressIsTaken)14796 markUnaddressableCandidatesUnviable(*this, CandidateSet);14797 14798 OverloadCandidateSet::iterator Best;14799 OverloadingResult OverloadResult =14800 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);14801 14802 // [C++23][over.call.func]14803 // if overload resolution selects a non-static member function,14804 // the call is ill-formed;14805 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&14806 Best != CandidateSet.end()) {14807 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);14808 M && M->isImplicitObjectMemberFunction()) {14809 OverloadResult = OR_No_Viable_Function;14810 }14811 }14812 14813 // Model the case with a call to a templated function whose definition14814 // encloses the call and whose return type contains a placeholder type as if14815 // the UnresolvedLookupExpr was type-dependent.14816 if (OverloadResult == OR_Success) {14817 const FunctionDecl *FDecl = Best->Function;14818 if (LangOpts.CUDA)14819 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);14820 if (FDecl && FDecl->isTemplateInstantiation() &&14821 FDecl->getReturnType()->isUndeducedType()) {14822 14823 // Creating dependent CallExpr is not okay if the enclosing context itself14824 // is not dependent. This situation notably arises if a non-dependent14825 // member function calls the later-defined overloaded static function.14826 //14827 // For example, in14828 // class A {14829 // void c() { callee(1); }14830 // static auto callee(auto x) { }14831 // };14832 //14833 // Here callee(1) is unresolved at the call site, but is not inside a14834 // dependent context. There will be no further attempt to resolve this14835 // call if it is made dependent.14836 14837 if (const auto *TP =14838 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);14839 TP && TP->willHaveBody() && CurContext->isDependentContext()) {14840 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,14841 VK_PRValue, RParenLoc, CurFPFeatureOverrides());14842 }14843 }14844 }14845 14846 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,14847 ExecConfig, &CandidateSet, &Best,14848 OverloadResult, AllowTypoCorrection);14849}14850 14851ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,14852 NestedNameSpecifierLoc NNSLoc,14853 DeclarationNameInfo DNI,14854 const UnresolvedSetImpl &Fns,14855 bool PerformADL) {14856 return UnresolvedLookupExpr::Create(14857 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),14858 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);14859}14860 14861ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,14862 CXXConversionDecl *Method,14863 bool HadMultipleCandidates) {14864 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in14865 // the FoundDecl as it impedes TransformMemberExpr.14866 // We go a bit further here: if there's no difference in UnderlyingDecl,14867 // then using FoundDecl vs Method shouldn't make a difference either.14868 if (FoundDecl->getUnderlyingDecl() == FoundDecl)14869 FoundDecl = Method;14870 // Convert the expression to match the conversion function's implicit object14871 // parameter.14872 ExprResult Exp;14873 if (Method->isExplicitObjectMemberFunction())14874 Exp = InitializeExplicitObjectArgument(*this, E, Method);14875 else14876 Exp = PerformImplicitObjectArgumentInitialization(14877 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);14878 if (Exp.isInvalid())14879 return true;14880 14881 if (Method->getParent()->isLambda() &&14882 Method->getConversionType()->isBlockPointerType()) {14883 // This is a lambda conversion to block pointer; check if the argument14884 // was a LambdaExpr.14885 Expr *SubE = E;14886 auto *CE = dyn_cast<CastExpr>(SubE);14887 if (CE && CE->getCastKind() == CK_NoOp)14888 SubE = CE->getSubExpr();14889 SubE = SubE->IgnoreParens();14890 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))14891 SubE = BE->getSubExpr();14892 if (isa<LambdaExpr>(SubE)) {14893 // For the conversion to block pointer on a lambda expression, we14894 // construct a special BlockLiteral instead; this doesn't really make14895 // a difference in ARC, but outside of ARC the resulting block literal14896 // follows the normal lifetime rules for block literals instead of being14897 // autoreleased.14898 PushExpressionEvaluationContext(14899 ExpressionEvaluationContext::PotentiallyEvaluated);14900 ExprResult BlockExp = BuildBlockForLambdaConversion(14901 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());14902 PopExpressionEvaluationContext();14903 14904 // FIXME: This note should be produced by a CodeSynthesisContext.14905 if (BlockExp.isInvalid())14906 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);14907 return BlockExp;14908 }14909 }14910 CallExpr *CE;14911 QualType ResultType = Method->getReturnType();14912 ExprValueKind VK = Expr::getValueKindForType(ResultType);14913 ResultType = ResultType.getNonLValueExprType(Context);14914 if (Method->isExplicitObjectMemberFunction()) {14915 ExprResult FnExpr =14916 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),14917 HadMultipleCandidates, E->getBeginLoc());14918 if (FnExpr.isInvalid())14919 return ExprError();14920 Expr *ObjectParam = Exp.get();14921 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),14922 ResultType, VK, Exp.get()->getEndLoc(),14923 CurFPFeatureOverrides());14924 CE->setUsesMemberSyntax(true);14925 } else {14926 MemberExpr *ME =14927 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),14928 NestedNameSpecifierLoc(), SourceLocation(), Method,14929 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),14930 HadMultipleCandidates, DeclarationNameInfo(),14931 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);14932 14933 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,14934 Exp.get()->getEndLoc(),14935 CurFPFeatureOverrides());14936 }14937 14938 if (CheckFunctionCall(Method, CE,14939 Method->getType()->castAs<FunctionProtoType>()))14940 return ExprError();14941 14942 return CheckForImmediateInvocation(CE, CE->getDirectCallee());14943}14944 14945ExprResult14946Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,14947 const UnresolvedSetImpl &Fns,14948 Expr *Input, bool PerformADL) {14949 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);14950 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");14951 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);14952 // TODO: provide better source location info.14953 DeclarationNameInfo OpNameInfo(OpName, OpLoc);14954 14955 if (checkPlaceholderForOverload(*this, Input))14956 return ExprError();14957 14958 Expr *Args[2] = { Input, nullptr };14959 unsigned NumArgs = 1;14960 14961 // For post-increment and post-decrement, add the implicit '0' as14962 // the second argument, so that we know this is a post-increment or14963 // post-decrement.14964 if (Opc == UO_PostInc || Opc == UO_PostDec) {14965 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);14966 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,14967 SourceLocation());14968 NumArgs = 2;14969 }14970 14971 ArrayRef<Expr *> ArgsArray(Args, NumArgs);14972 14973 if (Input->isTypeDependent()) {14974 ExprValueKind VK = ExprValueKind::VK_PRValue;14975 // [C++26][expr.unary.op][expr.pre.incr]14976 // The * operator yields an lvalue of type14977 // The pre/post increment operators yied an lvalue.14978 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)14979 VK = VK_LValue;14980 14981 if (Fns.empty())14982 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,14983 OK_Ordinary, OpLoc, false,14984 CurFPFeatureOverrides());14985 14986 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators14987 ExprResult Fn = CreateUnresolvedLookupExpr(14988 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);14989 if (Fn.isInvalid())14990 return ExprError();14991 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,14992 Context.DependentTy, VK_PRValue, OpLoc,14993 CurFPFeatureOverrides());14994 }14995 14996 // Build an empty overload set.14997 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);14998 14999 // Add the candidates from the given function set.15000 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);15001 15002 // Add operator candidates that are member functions.15003 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);15004 15005 // Add candidates from ADL.15006 if (PerformADL) {15007 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,15008 /*ExplicitTemplateArgs*/nullptr,15009 CandidateSet);15010 }15011 15012 // Add builtin operator candidates.15013 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);15014 15015 bool HadMultipleCandidates = (CandidateSet.size() > 1);15016 15017 // Perform overload resolution.15018 OverloadCandidateSet::iterator Best;15019 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {15020 case OR_Success: {15021 // We found a built-in operator or an overloaded operator.15022 FunctionDecl *FnDecl = Best->Function;15023 15024 if (FnDecl) {15025 Expr *Base = nullptr;15026 // We matched an overloaded operator. Build a call to that15027 // operator.15028 15029 // Convert the arguments.15030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {15031 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);15032 15033 ExprResult InputInit;15034 if (Method->isExplicitObjectMemberFunction())15035 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);15036 else15037 InputInit = PerformImplicitObjectArgumentInitialization(15038 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);15039 if (InputInit.isInvalid())15040 return ExprError();15041 Base = Input = InputInit.get();15042 } else {15043 // Convert the arguments.15044 ExprResult InputInit15045 = PerformCopyInitialization(InitializedEntity::InitializeParameter(15046 Context,15047 FnDecl->getParamDecl(0)),15048 SourceLocation(),15049 Input);15050 if (InputInit.isInvalid())15051 return ExprError();15052 Input = InputInit.get();15053 }15054 15055 // Build the actual expression node.15056 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,15057 Base, HadMultipleCandidates,15058 OpLoc);15059 if (FnExpr.isInvalid())15060 return ExprError();15061 15062 // Determine the result type.15063 QualType ResultTy = FnDecl->getReturnType();15064 ExprValueKind VK = Expr::getValueKindForType(ResultTy);15065 ResultTy = ResultTy.getNonLValueExprType(Context);15066 15067 Args[0] = Input;15068 CallExpr *TheCall = CXXOperatorCallExpr::Create(15069 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,15070 CurFPFeatureOverrides(),15071 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));15072 15073 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))15074 return ExprError();15075 15076 if (CheckFunctionCall(FnDecl, TheCall,15077 FnDecl->getType()->castAs<FunctionProtoType>()))15078 return ExprError();15079 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);15080 } else {15081 // We matched a built-in operator. Convert the arguments, then15082 // break out so that we will build the appropriate built-in15083 // operator node.15084 ExprResult InputRes = PerformImplicitConversion(15085 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],15086 AssignmentAction::Passing,15087 CheckedConversionKind::ForBuiltinOverloadedOp);15088 if (InputRes.isInvalid())15089 return ExprError();15090 Input = InputRes.get();15091 break;15092 }15093 }15094 15095 case OR_No_Viable_Function:15096 // This is an erroneous use of an operator which can be overloaded by15097 // a non-member function. Check for non-member operators which were15098 // defined too late to be candidates.15099 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))15100 // FIXME: Recover by calling the found function.15101 return ExprError();15102 15103 // No viable function; fall through to handling this as a15104 // built-in operator, which will produce an error message for us.15105 break;15106 15107 case OR_Ambiguous:15108 CandidateSet.NoteCandidates(15109 PartialDiagnosticAt(OpLoc,15110 PDiag(diag::err_ovl_ambiguous_oper_unary)15111 << UnaryOperator::getOpcodeStr(Opc)15112 << Input->getType() << Input->getSourceRange()),15113 *this, OCD_AmbiguousCandidates, ArgsArray,15114 UnaryOperator::getOpcodeStr(Opc), OpLoc);15115 return ExprError();15116 15117 case OR_Deleted: {15118 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the15119 // object whose method was called. Later in NoteCandidates size of ArgsArray15120 // is passed further and it eventually ends up compared to number of15121 // function candidate parameters which never includes the object parameter,15122 // so slice ArgsArray to make sure apples are compared to apples.15123 StringLiteral *Msg = Best->Function->getDeletedMessage();15124 CandidateSet.NoteCandidates(15125 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)15126 << UnaryOperator::getOpcodeStr(Opc)15127 << (Msg != nullptr)15128 << (Msg ? Msg->getString() : StringRef())15129 << Input->getSourceRange()),15130 *this, OCD_AllCandidates, ArgsArray.drop_front(),15131 UnaryOperator::getOpcodeStr(Opc), OpLoc);15132 return ExprError();15133 }15134 }15135 15136 // Either we found no viable overloaded operator or we matched a15137 // built-in operator. In either case, fall through to trying to15138 // build a built-in operation.15139 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);15140}15141 15142void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,15143 OverloadedOperatorKind Op,15144 const UnresolvedSetImpl &Fns,15145 ArrayRef<Expr *> Args, bool PerformADL) {15146 SourceLocation OpLoc = CandidateSet.getLocation();15147 15148 OverloadedOperatorKind ExtraOp =15149 CandidateSet.getRewriteInfo().AllowRewrittenCandidates15150 ? getRewrittenOverloadedOperator(Op)15151 : OO_None;15152 15153 // Add the candidates from the given function set. This also adds the15154 // rewritten candidates using these functions if necessary.15155 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);15156 15157 // As template candidates are not deduced immediately,15158 // persist the array in the overload set.15159 ArrayRef<Expr *> ReversedArgs;15160 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||15161 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))15162 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);15163 15164 // Add operator candidates that are member functions.15165 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);15166 if (CandidateSet.getRewriteInfo().allowsReversed(Op))15167 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,15168 OverloadCandidateParamOrder::Reversed);15169 15170 // In C++20, also add any rewritten member candidates.15171 if (ExtraOp) {15172 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);15173 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))15174 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,15175 OverloadCandidateParamOrder::Reversed);15176 }15177 15178 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not15179 // performed for an assignment operator (nor for operator[] nor operator->,15180 // which don't get here).15181 if (Op != OO_Equal && PerformADL) {15182 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);15183 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,15184 /*ExplicitTemplateArgs*/ nullptr,15185 CandidateSet);15186 if (ExtraOp) {15187 DeclarationName ExtraOpName =15188 Context.DeclarationNames.getCXXOperatorName(ExtraOp);15189 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,15190 /*ExplicitTemplateArgs*/ nullptr,15191 CandidateSet);15192 }15193 }15194 15195 // Add builtin operator candidates.15196 //15197 // FIXME: We don't add any rewritten candidates here. This is strictly15198 // incorrect; a builtin candidate could be hidden by a non-viable candidate,15199 // resulting in our selecting a rewritten builtin candidate. For example:15200 //15201 // enum class E { e };15202 // bool operator!=(E, E) requires false;15203 // bool k = E::e != E::e;15204 //15205 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But15206 // it seems unreasonable to consider rewritten builtin candidates. A core15207 // issue has been filed proposing to removed this requirement.15208 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);15209}15210 15211ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,15212 BinaryOperatorKind Opc,15213 const UnresolvedSetImpl &Fns, Expr *LHS,15214 Expr *RHS, bool PerformADL,15215 bool AllowRewrittenCandidates,15216 FunctionDecl *DefaultedFn) {15217 Expr *Args[2] = { LHS, RHS };15218 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple15219 15220 if (!getLangOpts().CPlusPlus20)15221 AllowRewrittenCandidates = false;15222 15223 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);15224 15225 // If either side is type-dependent, create an appropriate dependent15226 // expression.15227 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {15228 if (Fns.empty()) {15229 // If there are no functions to store, just build a dependent15230 // BinaryOperator or CompoundAssignment.15231 if (BinaryOperator::isCompoundAssignmentOp(Opc))15232 return CompoundAssignOperator::Create(15233 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,15234 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,15235 Context.DependentTy);15236 return BinaryOperator::Create(15237 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,15238 OK_Ordinary, OpLoc, CurFPFeatureOverrides());15239 }15240 15241 // FIXME: save results of ADL from here?15242 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators15243 // TODO: provide better source location info in DNLoc component.15244 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);15245 DeclarationNameInfo OpNameInfo(OpName, OpLoc);15246 ExprResult Fn = CreateUnresolvedLookupExpr(15247 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);15248 if (Fn.isInvalid())15249 return ExprError();15250 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,15251 Context.DependentTy, VK_PRValue, OpLoc,15252 CurFPFeatureOverrides());15253 }15254 15255 // If this is the .* operator, which is not overloadable, just15256 // create a built-in binary operator.15257 if (Opc == BO_PtrMemD) {15258 auto CheckPlaceholder = [&](Expr *&Arg) {15259 ExprResult Res = CheckPlaceholderExpr(Arg);15260 if (Res.isUsable())15261 Arg = Res.get();15262 return !Res.isUsable();15263 };15264 15265 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'15266 // expression that contains placeholders (in either the LHS or RHS).15267 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))15268 return ExprError();15269 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);15270 }15271 15272 // Always do placeholder-like conversions on the RHS.15273 if (checkPlaceholderForOverload(*this, Args[1]))15274 return ExprError();15275 15276 // Do placeholder-like conversion on the LHS; note that we should15277 // not get here with a PseudoObject LHS.15278 assert(Args[0]->getObjectKind() != OK_ObjCProperty);15279 if (checkPlaceholderForOverload(*this, Args[0]))15280 return ExprError();15281 15282 // If this is the assignment operator, we only perform overload resolution15283 // if the left-hand side is a class or enumeration type. This is actually15284 // a hack. The standard requires that we do overload resolution between the15285 // various built-in candidates, but as DR507 points out, this can lead to15286 // problems. So we do it this way, which pretty much follows what GCC does.15287 // Note that we go the traditional code path for compound assignment forms.15288 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())15289 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);15290 15291 // Build the overload set.15292 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,15293 OverloadCandidateSet::OperatorRewriteInfo(15294 Op, OpLoc, AllowRewrittenCandidates));15295 if (DefaultedFn)15296 CandidateSet.exclude(DefaultedFn);15297 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);15298 15299 bool HadMultipleCandidates = (CandidateSet.size() > 1);15300 15301 // Perform overload resolution.15302 OverloadCandidateSet::iterator Best;15303 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {15304 case OR_Success: {15305 // We found a built-in operator or an overloaded operator.15306 FunctionDecl *FnDecl = Best->Function;15307 15308 bool IsReversed = Best->isReversed();15309 if (IsReversed)15310 std::swap(Args[0], Args[1]);15311 15312 if (FnDecl) {15313 15314 if (FnDecl->isInvalidDecl())15315 return ExprError();15316 15317 Expr *Base = nullptr;15318 // We matched an overloaded operator. Build a call to that15319 // operator.15320 15321 OverloadedOperatorKind ChosenOp =15322 FnDecl->getDeclName().getCXXOverloadedOperator();15323 15324 // C++2a [over.match.oper]p9:15325 // If a rewritten operator== candidate is selected by overload15326 // resolution for an operator@, its return type shall be cv bool15327 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&15328 !FnDecl->getReturnType()->isBooleanType()) {15329 bool IsExtension =15330 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();15331 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool15332 : diag::err_ovl_rewrite_equalequal_not_bool)15333 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)15334 << Args[0]->getSourceRange() << Args[1]->getSourceRange();15335 Diag(FnDecl->getLocation(), diag::note_declared_at);15336 if (!IsExtension)15337 return ExprError();15338 }15339 15340 if (AllowRewrittenCandidates && !IsReversed &&15341 CandidateSet.getRewriteInfo().isReversible()) {15342 // We could have reversed this operator, but didn't. Check if some15343 // reversed form was a viable candidate, and if so, if it had a15344 // better conversion for either parameter. If so, this call is15345 // formally ambiguous, and allowing it is an extension.15346 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;15347 for (OverloadCandidate &Cand : CandidateSet) {15348 if (Cand.Viable && Cand.Function && Cand.isReversed() &&15349 allowAmbiguity(Context, Cand.Function, FnDecl)) {15350 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {15351 if (CompareImplicitConversionSequences(15352 *this, OpLoc, Cand.Conversions[ArgIdx],15353 Best->Conversions[ArgIdx]) ==15354 ImplicitConversionSequence::Better) {15355 AmbiguousWith.push_back(Cand.Function);15356 break;15357 }15358 }15359 }15360 }15361 15362 if (!AmbiguousWith.empty()) {15363 bool AmbiguousWithSelf =15364 AmbiguousWith.size() == 1 &&15365 declaresSameEntity(AmbiguousWith.front(), FnDecl);15366 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)15367 << BinaryOperator::getOpcodeStr(Opc)15368 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf15369 << Args[0]->getSourceRange() << Args[1]->getSourceRange();15370 if (AmbiguousWithSelf) {15371 Diag(FnDecl->getLocation(),15372 diag::note_ovl_ambiguous_oper_binary_reversed_self);15373 // Mark member== const or provide matching != to disallow reversed15374 // args. Eg.15375 // struct S { bool operator==(const S&); };15376 // S()==S();15377 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))15378 if (Op == OverloadedOperatorKind::OO_EqualEqual &&15379 !MD->isConst() &&15380 !MD->hasCXXExplicitFunctionObjectParameter() &&15381 Context.hasSameUnqualifiedType(15382 MD->getFunctionObjectParameterType(),15383 MD->getParamDecl(0)->getType().getNonReferenceType()) &&15384 Context.hasSameUnqualifiedType(15385 MD->getFunctionObjectParameterType(),15386 Args[0]->getType()) &&15387 Context.hasSameUnqualifiedType(15388 MD->getFunctionObjectParameterType(),15389 Args[1]->getType()))15390 Diag(FnDecl->getLocation(),15391 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);15392 } else {15393 Diag(FnDecl->getLocation(),15394 diag::note_ovl_ambiguous_oper_binary_selected_candidate);15395 for (auto *F : AmbiguousWith)15396 Diag(F->getLocation(),15397 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);15398 }15399 }15400 }15401 15402 // Check for nonnull = nullable.15403 // This won't be caught in the arg's initialization: the parameter to15404 // the assignment operator is not marked nonnull.15405 if (Op == OO_Equal)15406 diagnoseNullableToNonnullConversion(Args[0]->getType(),15407 Args[1]->getType(), OpLoc);15408 15409 // Convert the arguments.15410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {15411 // Best->Access is only meaningful for class members.15412 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);15413 15414 ExprResult Arg0, Arg1;15415 unsigned ParamIdx = 0;15416 if (Method->isExplicitObjectMemberFunction()) {15417 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);15418 ParamIdx = 1;15419 } else {15420 Arg0 = PerformImplicitObjectArgumentInitialization(15421 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);15422 }15423 Arg1 = PerformCopyInitialization(15424 InitializedEntity::InitializeParameter(15425 Context, FnDecl->getParamDecl(ParamIdx)),15426 SourceLocation(), Args[1]);15427 if (Arg0.isInvalid() || Arg1.isInvalid())15428 return ExprError();15429 15430 Base = Args[0] = Arg0.getAs<Expr>();15431 Args[1] = RHS = Arg1.getAs<Expr>();15432 } else {15433 // Convert the arguments.15434 ExprResult Arg0 = PerformCopyInitialization(15435 InitializedEntity::InitializeParameter(Context,15436 FnDecl->getParamDecl(0)),15437 SourceLocation(), Args[0]);15438 if (Arg0.isInvalid())15439 return ExprError();15440 15441 ExprResult Arg1 =15442 PerformCopyInitialization(15443 InitializedEntity::InitializeParameter(Context,15444 FnDecl->getParamDecl(1)),15445 SourceLocation(), Args[1]);15446 if (Arg1.isInvalid())15447 return ExprError();15448 Args[0] = LHS = Arg0.getAs<Expr>();15449 Args[1] = RHS = Arg1.getAs<Expr>();15450 }15451 15452 // Build the actual expression node.15453 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,15454 Best->FoundDecl, Base,15455 HadMultipleCandidates, OpLoc);15456 if (FnExpr.isInvalid())15457 return ExprError();15458 15459 // Determine the result type.15460 QualType ResultTy = FnDecl->getReturnType();15461 ExprValueKind VK = Expr::getValueKindForType(ResultTy);15462 ResultTy = ResultTy.getNonLValueExprType(Context);15463 15464 CallExpr *TheCall;15465 ArrayRef<const Expr *> ArgsArray(Args, 2);15466 const Expr *ImplicitThis = nullptr;15467 15468 // We always create a CXXOperatorCallExpr, even for explicit object15469 // members; CodeGen should take care not to emit the this pointer.15470 TheCall = CXXOperatorCallExpr::Create(15471 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,15472 CurFPFeatureOverrides(),15473 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));15474 15475 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);15476 Method && Method->isImplicitObjectMemberFunction()) {15477 // Cut off the implicit 'this'.15478 ImplicitThis = ArgsArray[0];15479 ArgsArray = ArgsArray.slice(1);15480 }15481 15482 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,15483 FnDecl))15484 return ExprError();15485 15486 if (Op == OO_Equal) {15487 // Check for a self move.15488 DiagnoseSelfMove(Args[0], Args[1], OpLoc);15489 // lifetime check.15490 checkAssignmentLifetime(15491 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},15492 Args[1]);15493 }15494 if (ImplicitThis) {15495 QualType ThisType = Context.getPointerType(ImplicitThis->getType());15496 QualType ThisTypeFromDecl = Context.getPointerType(15497 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());15498 15499 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,15500 ThisTypeFromDecl);15501 }15502 15503 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,15504 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),15505 VariadicCallType::DoesNotApply);15506 15507 ExprResult R = MaybeBindToTemporary(TheCall);15508 if (R.isInvalid())15509 return ExprError();15510 15511 R = CheckForImmediateInvocation(R, FnDecl);15512 if (R.isInvalid())15513 return ExprError();15514 15515 // For a rewritten candidate, we've already reversed the arguments15516 // if needed. Perform the rest of the rewrite now.15517 if ((Best->RewriteKind & CRK_DifferentOperator) ||15518 (Op == OO_Spaceship && IsReversed)) {15519 if (Op == OO_ExclaimEqual) {15520 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");15521 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());15522 } else {15523 assert(ChosenOp == OO_Spaceship && "unexpected operator name");15524 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);15525 Expr *ZeroLiteral =15526 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);15527 15528 Sema::CodeSynthesisContext Ctx;15529 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;15530 Ctx.Entity = FnDecl;15531 pushCodeSynthesisContext(Ctx);15532 15533 R = CreateOverloadedBinOp(15534 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),15535 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,15536 /*AllowRewrittenCandidates=*/false);15537 15538 popCodeSynthesisContext();15539 }15540 if (R.isInvalid())15541 return ExprError();15542 } else {15543 assert(ChosenOp == Op && "unexpected operator name");15544 }15545 15546 // Make a note in the AST if we did any rewriting.15547 if (Best->RewriteKind != CRK_None)15548 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);15549 15550 return R;15551 } else {15552 // We matched a built-in operator. Convert the arguments, then15553 // break out so that we will build the appropriate built-in15554 // operator node.15555 ExprResult ArgsRes0 = PerformImplicitConversion(15556 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],15557 AssignmentAction::Passing,15558 CheckedConversionKind::ForBuiltinOverloadedOp);15559 if (ArgsRes0.isInvalid())15560 return ExprError();15561 Args[0] = ArgsRes0.get();15562 15563 ExprResult ArgsRes1 = PerformImplicitConversion(15564 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],15565 AssignmentAction::Passing,15566 CheckedConversionKind::ForBuiltinOverloadedOp);15567 if (ArgsRes1.isInvalid())15568 return ExprError();15569 Args[1] = ArgsRes1.get();15570 break;15571 }15572 }15573 15574 case OR_No_Viable_Function: {15575 // C++ [over.match.oper]p9:15576 // If the operator is the operator , [...] and there are no15577 // viable functions, then the operator is assumed to be the15578 // built-in operator and interpreted according to clause 5.15579 if (Opc == BO_Comma)15580 break;15581 15582 // When defaulting an 'operator<=>', we can try to synthesize a three-way15583 // compare result using '==' and '<'.15584 if (DefaultedFn && Opc == BO_Cmp) {15585 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],15586 Args[1], DefaultedFn);15587 if (E.isInvalid() || E.isUsable())15588 return E;15589 }15590 15591 // For class as left operand for assignment or compound assignment15592 // operator do not fall through to handling in built-in, but report that15593 // no overloaded assignment operator found15594 ExprResult Result = ExprError();15595 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);15596 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,15597 Args, OpLoc);15598 DeferDiagsRAII DDR(*this,15599 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));15600 if (Args[0]->getType()->isRecordType() &&15601 Opc >= BO_Assign && Opc <= BO_OrAssign) {15602 Diag(OpLoc, diag::err_ovl_no_viable_oper)15603 << BinaryOperator::getOpcodeStr(Opc)15604 << Args[0]->getSourceRange() << Args[1]->getSourceRange();15605 if (Args[0]->getType()->isIncompleteType()) {15606 Diag(OpLoc, diag::note_assign_lhs_incomplete)15607 << Args[0]->getType()15608 << Args[0]->getSourceRange() << Args[1]->getSourceRange();15609 }15610 } else {15611 // This is an erroneous use of an operator which can be overloaded by15612 // a non-member function. Check for non-member operators which were15613 // defined too late to be candidates.15614 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))15615 // FIXME: Recover by calling the found function.15616 return ExprError();15617 15618 // No viable function; try to create a built-in operation, which will15619 // produce an error. Then, show the non-viable candidates.15620 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);15621 }15622 assert(Result.isInvalid() &&15623 "C++ binary operator overloading is missing candidates!");15624 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);15625 return Result;15626 }15627 15628 case OR_Ambiguous:15629 CandidateSet.NoteCandidates(15630 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)15631 << BinaryOperator::getOpcodeStr(Opc)15632 << Args[0]->getType()15633 << Args[1]->getType()15634 << Args[0]->getSourceRange()15635 << Args[1]->getSourceRange()),15636 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),15637 OpLoc);15638 return ExprError();15639 15640 case OR_Deleted: {15641 if (isImplicitlyDeleted(Best->Function)) {15642 FunctionDecl *DeletedFD = Best->Function;15643 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);15644 if (DFK.isSpecialMember()) {15645 Diag(OpLoc, diag::err_ovl_deleted_special_oper)15646 << Args[0]->getType() << DFK.asSpecialMember();15647 } else {15648 assert(DFK.isComparison());15649 Diag(OpLoc, diag::err_ovl_deleted_comparison)15650 << Args[0]->getType() << DeletedFD;15651 }15652 15653 // The user probably meant to call this special member. Just15654 // explain why it's deleted.15655 NoteDeletedFunction(DeletedFD);15656 return ExprError();15657 }15658 15659 StringLiteral *Msg = Best->Function->getDeletedMessage();15660 CandidateSet.NoteCandidates(15661 PartialDiagnosticAt(15662 OpLoc,15663 PDiag(diag::err_ovl_deleted_oper)15664 << getOperatorSpelling(Best->Function->getDeclName()15665 .getCXXOverloadedOperator())15666 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())15667 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),15668 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),15669 OpLoc);15670 return ExprError();15671 }15672 }15673 15674 // We matched a built-in operator; build it.15675 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);15676}15677 15678ExprResult Sema::BuildSynthesizedThreeWayComparison(15679 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,15680 FunctionDecl *DefaultedFn) {15681 const ComparisonCategoryInfo *Info =15682 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());15683 // If we're not producing a known comparison category type, we can't15684 // synthesize a three-way comparison. Let the caller diagnose this.15685 if (!Info)15686 return ExprResult((Expr*)nullptr);15687 15688 // If we ever want to perform this synthesis more generally, we will need to15689 // apply the temporary materialization conversion to the operands.15690 assert(LHS->isGLValue() && RHS->isGLValue() &&15691 "cannot use prvalue expressions more than once");15692 Expr *OrigLHS = LHS;15693 Expr *OrigRHS = RHS;15694 15695 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to15696 // each of them multiple times below.15697 LHS = new (Context)15698 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),15699 LHS->getObjectKind(), LHS);15700 RHS = new (Context)15701 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),15702 RHS->getObjectKind(), RHS);15703 15704 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,15705 DefaultedFn);15706 if (Eq.isInvalid())15707 return ExprError();15708 15709 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,15710 true, DefaultedFn);15711 if (Less.isInvalid())15712 return ExprError();15713 15714 ExprResult Greater;15715 if (Info->isPartial()) {15716 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,15717 DefaultedFn);15718 if (Greater.isInvalid())15719 return ExprError();15720 }15721 15722 // Form the list of comparisons we're going to perform.15723 struct Comparison {15724 ExprResult Cmp;15725 ComparisonCategoryResult Result;15726 } Comparisons[4] =15727 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal15728 : ComparisonCategoryResult::Equivalent},15729 {Less, ComparisonCategoryResult::Less},15730 {Greater, ComparisonCategoryResult::Greater},15731 {ExprResult(), ComparisonCategoryResult::Unordered},15732 };15733 15734 int I = Info->isPartial() ? 3 : 2;15735 15736 // Combine the comparisons with suitable conditional expressions.15737 ExprResult Result;15738 for (; I >= 0; --I) {15739 // Build a reference to the comparison category constant.15740 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);15741 // FIXME: Missing a constant for a comparison category. Diagnose this?15742 if (!VI)15743 return ExprResult((Expr*)nullptr);15744 ExprResult ThisResult =15745 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);15746 if (ThisResult.isInvalid())15747 return ExprError();15748 15749 // Build a conditional unless this is the final case.15750 if (Result.get()) {15751 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),15752 ThisResult.get(), Result.get());15753 if (Result.isInvalid())15754 return ExprError();15755 } else {15756 Result = ThisResult;15757 }15758 }15759 15760 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to15761 // bind the OpaqueValueExprs before they're (repeatedly) used.15762 Expr *SyntacticForm = BinaryOperator::Create(15763 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),15764 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,15765 CurFPFeatureOverrides());15766 Expr *SemanticForm[] = {LHS, RHS, Result.get()};15767 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);15768}15769 15770static bool PrepareArgumentsForCallToObjectOfClassType(15771 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,15772 MultiExprArg Args, SourceLocation LParenLoc) {15773 15774 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();15775 unsigned NumParams = Proto->getNumParams();15776 unsigned NumArgsSlots =15777 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);15778 // Build the full argument list for the method call (the implicit object15779 // parameter is placed at the beginning of the list).15780 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);15781 bool IsError = false;15782 // Initialize the implicit object parameter.15783 // Check the argument types.15784 for (unsigned i = 0; i != NumParams; i++) {15785 Expr *Arg;15786 if (i < Args.size()) {15787 Arg = Args[i];15788 ExprResult InputInit =15789 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(15790 S.Context, Method->getParamDecl(i)),15791 SourceLocation(), Arg);15792 IsError |= InputInit.isInvalid();15793 Arg = InputInit.getAs<Expr>();15794 } else {15795 ExprResult DefArg =15796 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));15797 if (DefArg.isInvalid()) {15798 IsError = true;15799 break;15800 }15801 Arg = DefArg.getAs<Expr>();15802 }15803 15804 MethodArgs.push_back(Arg);15805 }15806 return IsError;15807}15808 15809ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,15810 SourceLocation RLoc,15811 Expr *Base,15812 MultiExprArg ArgExpr) {15813 SmallVector<Expr *, 2> Args;15814 Args.push_back(Base);15815 for (auto *e : ArgExpr) {15816 Args.push_back(e);15817 }15818 DeclarationName OpName =15819 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);15820 15821 SourceRange Range = ArgExpr.empty()15822 ? SourceRange{}15823 : SourceRange(ArgExpr.front()->getBeginLoc(),15824 ArgExpr.back()->getEndLoc());15825 15826 // If either side is type-dependent, create an appropriate dependent15827 // expression.15828 if (Expr::hasAnyTypeDependentArguments(Args)) {15829 15830 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators15831 // CHECKME: no 'operator' keyword?15832 DeclarationNameInfo OpNameInfo(OpName, LLoc);15833 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));15834 ExprResult Fn = CreateUnresolvedLookupExpr(15835 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());15836 if (Fn.isInvalid())15837 return ExprError();15838 // Can't add any actual overloads yet15839 15840 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,15841 Context.DependentTy, VK_PRValue, RLoc,15842 CurFPFeatureOverrides());15843 }15844 15845 // Handle placeholders15846 UnbridgedCastsSet UnbridgedCasts;15847 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {15848 return ExprError();15849 }15850 // Build an empty overload set.15851 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);15852 15853 // Subscript can only be overloaded as a member function.15854 15855 // Add operator candidates that are member functions.15856 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);15857 15858 // Add builtin operator candidates.15859 if (Args.size() == 2)15860 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);15861 15862 bool HadMultipleCandidates = (CandidateSet.size() > 1);15863 15864 // Perform overload resolution.15865 OverloadCandidateSet::iterator Best;15866 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {15867 case OR_Success: {15868 // We found a built-in operator or an overloaded operator.15869 FunctionDecl *FnDecl = Best->Function;15870 15871 if (FnDecl) {15872 // We matched an overloaded operator. Build a call to that15873 // operator.15874 15875 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);15876 15877 // Convert the arguments.15878 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);15879 SmallVector<Expr *, 2> MethodArgs;15880 15881 // Initialize the object parameter.15882 if (Method->isExplicitObjectMemberFunction()) {15883 ExprResult Res =15884 InitializeExplicitObjectArgument(*this, Args[0], Method);15885 if (Res.isInvalid())15886 return ExprError();15887 Args[0] = Res.get();15888 ArgExpr = Args;15889 } else {15890 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(15891 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);15892 if (Arg0.isInvalid())15893 return ExprError();15894 15895 MethodArgs.push_back(Arg0.get());15896 }15897 15898 bool IsError = PrepareArgumentsForCallToObjectOfClassType(15899 *this, MethodArgs, Method, ArgExpr, LLoc);15900 if (IsError)15901 return ExprError();15902 15903 // Build the actual expression node.15904 DeclarationNameInfo OpLocInfo(OpName, LLoc);15905 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));15906 ExprResult FnExpr = CreateFunctionRefExpr(15907 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,15908 OpLocInfo.getLoc(), OpLocInfo.getInfo());15909 if (FnExpr.isInvalid())15910 return ExprError();15911 15912 // Determine the result type15913 QualType ResultTy = FnDecl->getReturnType();15914 ExprValueKind VK = Expr::getValueKindForType(ResultTy);15915 ResultTy = ResultTy.getNonLValueExprType(Context);15916 15917 CallExpr *TheCall = CXXOperatorCallExpr::Create(15918 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,15919 CurFPFeatureOverrides());15920 15921 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))15922 return ExprError();15923 15924 if (CheckFunctionCall(Method, TheCall,15925 Method->getType()->castAs<FunctionProtoType>()))15926 return ExprError();15927 15928 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),15929 FnDecl);15930 } else {15931 // We matched a built-in operator. Convert the arguments, then15932 // break out so that we will build the appropriate built-in15933 // operator node.15934 ExprResult ArgsRes0 = PerformImplicitConversion(15935 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],15936 AssignmentAction::Passing,15937 CheckedConversionKind::ForBuiltinOverloadedOp);15938 if (ArgsRes0.isInvalid())15939 return ExprError();15940 Args[0] = ArgsRes0.get();15941 15942 ExprResult ArgsRes1 = PerformImplicitConversion(15943 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],15944 AssignmentAction::Passing,15945 CheckedConversionKind::ForBuiltinOverloadedOp);15946 if (ArgsRes1.isInvalid())15947 return ExprError();15948 Args[1] = ArgsRes1.get();15949 15950 break;15951 }15952 }15953 15954 case OR_No_Viable_Function: {15955 PartialDiagnostic PD =15956 CandidateSet.empty()15957 ? (PDiag(diag::err_ovl_no_oper)15958 << Args[0]->getType() << /*subscript*/ 015959 << Args[0]->getSourceRange() << Range)15960 : (PDiag(diag::err_ovl_no_viable_subscript)15961 << Args[0]->getType() << Args[0]->getSourceRange() << Range);15962 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,15963 OCD_AllCandidates, ArgExpr, "[]", LLoc);15964 return ExprError();15965 }15966 15967 case OR_Ambiguous:15968 if (Args.size() == 2) {15969 CandidateSet.NoteCandidates(15970 PartialDiagnosticAt(15971 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)15972 << "[]" << Args[0]->getType() << Args[1]->getType()15973 << Args[0]->getSourceRange() << Range),15974 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);15975 } else {15976 CandidateSet.NoteCandidates(15977 PartialDiagnosticAt(LLoc,15978 PDiag(diag::err_ovl_ambiguous_subscript_call)15979 << Args[0]->getType()15980 << Args[0]->getSourceRange() << Range),15981 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);15982 }15983 return ExprError();15984 15985 case OR_Deleted: {15986 StringLiteral *Msg = Best->Function->getDeletedMessage();15987 CandidateSet.NoteCandidates(15988 PartialDiagnosticAt(LLoc,15989 PDiag(diag::err_ovl_deleted_oper)15990 << "[]" << (Msg != nullptr)15991 << (Msg ? Msg->getString() : StringRef())15992 << Args[0]->getSourceRange() << Range),15993 *this, OCD_AllCandidates, Args, "[]", LLoc);15994 return ExprError();15995 }15996 }15997 15998 // We matched a built-in operator; build it.15999 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);16000}16001 16002ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,16003 SourceLocation LParenLoc,16004 MultiExprArg Args,16005 SourceLocation RParenLoc,16006 Expr *ExecConfig, bool IsExecConfig,16007 bool AllowRecovery) {16008 assert(MemExprE->getType() == Context.BoundMemberTy ||16009 MemExprE->getType() == Context.OverloadTy);16010 16011 // Dig out the member expression. This holds both the object16012 // argument and the member function we're referring to.16013 Expr *NakedMemExpr = MemExprE->IgnoreParens();16014 16015 // Determine whether this is a call to a pointer-to-member function.16016 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {16017 assert(op->getType() == Context.BoundMemberTy);16018 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);16019 16020 QualType fnType =16021 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();16022 16023 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();16024 QualType resultType = proto->getCallResultType(Context);16025 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());16026 16027 // Check that the object type isn't more qualified than the16028 // member function we're calling.16029 Qualifiers funcQuals = proto->getMethodQuals();16030 16031 QualType objectType = op->getLHS()->getType();16032 if (op->getOpcode() == BO_PtrMemI)16033 objectType = objectType->castAs<PointerType>()->getPointeeType();16034 Qualifiers objectQuals = objectType.getQualifiers();16035 16036 Qualifiers difference = objectQuals - funcQuals;16037 difference.removeObjCGCAttr();16038 difference.removeAddressSpace();16039 if (difference) {16040 std::string qualsString = difference.getAsString();16041 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)16042 << fnType.getUnqualifiedType()16043 << qualsString16044 << (qualsString.find(' ') == std::string::npos ? 1 : 2);16045 }16046 16047 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(16048 Context, MemExprE, Args, resultType, valueKind, RParenLoc,16049 CurFPFeatureOverrides(), proto->getNumParams());16050 16051 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),16052 call, nullptr))16053 return ExprError();16054 16055 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))16056 return ExprError();16057 16058 if (CheckOtherCall(call, proto))16059 return ExprError();16060 16061 return MaybeBindToTemporary(call);16062 }16063 16064 // We only try to build a recovery expr at this level if we can preserve16065 // the return type, otherwise we return ExprError() and let the caller16066 // recover.16067 auto BuildRecoveryExpr = [&](QualType Type) {16068 if (!AllowRecovery)16069 return ExprError();16070 std::vector<Expr *> SubExprs = {MemExprE};16071 llvm::append_range(SubExprs, Args);16072 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,16073 Type);16074 };16075 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))16076 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,16077 RParenLoc, CurFPFeatureOverrides());16078 16079 UnbridgedCastsSet UnbridgedCasts;16080 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))16081 return ExprError();16082 16083 MemberExpr *MemExpr;16084 CXXMethodDecl *Method = nullptr;16085 bool HadMultipleCandidates = false;16086 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);16087 NestedNameSpecifier Qualifier = std::nullopt;16088 if (isa<MemberExpr>(NakedMemExpr)) {16089 MemExpr = cast<MemberExpr>(NakedMemExpr);16090 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());16091 FoundDecl = MemExpr->getFoundDecl();16092 Qualifier = MemExpr->getQualifier();16093 UnbridgedCasts.restore();16094 } else {16095 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);16096 Qualifier = UnresExpr->getQualifier();16097 16098 QualType ObjectType = UnresExpr->getBaseType();16099 Expr::Classification ObjectClassification16100 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()16101 : UnresExpr->getBase()->Classify(Context);16102 16103 // Add overload candidates16104 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),16105 OverloadCandidateSet::CSK_Normal);16106 16107 // FIXME: avoid copy.16108 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;16109 if (UnresExpr->hasExplicitTemplateArgs()) {16110 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);16111 TemplateArgs = &TemplateArgsBuffer;16112 }16113 16114 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),16115 E = UnresExpr->decls_end(); I != E; ++I) {16116 16117 QualType ExplicitObjectType = ObjectType;16118 16119 NamedDecl *Func = *I;16120 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());16121 if (isa<UsingShadowDecl>(Func))16122 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();16123 16124 bool HasExplicitParameter = false;16125 if (const auto *M = dyn_cast<FunctionDecl>(Func);16126 M && M->hasCXXExplicitFunctionObjectParameter())16127 HasExplicitParameter = true;16128 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);16129 M &&16130 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())16131 HasExplicitParameter = true;16132 16133 if (HasExplicitParameter)16134 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);16135 16136 // Microsoft supports direct constructor calls.16137 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {16138 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,16139 CandidateSet,16140 /*SuppressUserConversions*/ false);16141 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {16142 // If explicit template arguments were provided, we can't call a16143 // non-template member function.16144 if (TemplateArgs)16145 continue;16146 16147 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,16148 ObjectClassification, Args, CandidateSet,16149 /*SuppressUserConversions=*/false);16150 } else {16151 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),16152 I.getPair(), ActingDC, TemplateArgs,16153 ExplicitObjectType, ObjectClassification,16154 Args, CandidateSet,16155 /*SuppressUserConversions=*/false);16156 }16157 }16158 16159 HadMultipleCandidates = (CandidateSet.size() > 1);16160 16161 DeclarationName DeclName = UnresExpr->getMemberName();16162 16163 UnbridgedCasts.restore();16164 16165 OverloadCandidateSet::iterator Best;16166 bool Succeeded = false;16167 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),16168 Best)) {16169 case OR_Success:16170 Method = cast<CXXMethodDecl>(Best->Function);16171 FoundDecl = Best->FoundDecl;16172 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);16173 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))16174 break;16175 // If FoundDecl is different from Method (such as if one is a template16176 // and the other a specialization), make sure DiagnoseUseOfDecl is16177 // called on both.16178 // FIXME: This would be more comprehensively addressed by modifying16179 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl16180 // being used.16181 if (Method != FoundDecl.getDecl() &&16182 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))16183 break;16184 Succeeded = true;16185 break;16186 16187 case OR_No_Viable_Function:16188 CandidateSet.NoteCandidates(16189 PartialDiagnosticAt(16190 UnresExpr->getMemberLoc(),16191 PDiag(diag::err_ovl_no_viable_member_function_in_call)16192 << DeclName << MemExprE->getSourceRange()),16193 *this, OCD_AllCandidates, Args);16194 break;16195 case OR_Ambiguous:16196 CandidateSet.NoteCandidates(16197 PartialDiagnosticAt(UnresExpr->getMemberLoc(),16198 PDiag(diag::err_ovl_ambiguous_member_call)16199 << DeclName << MemExprE->getSourceRange()),16200 *this, OCD_AmbiguousCandidates, Args);16201 break;16202 case OR_Deleted:16203 DiagnoseUseOfDeletedFunction(16204 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,16205 CandidateSet, Best->Function, Args, /*IsMember=*/true);16206 break;16207 }16208 // Overload resolution fails, try to recover.16209 if (!Succeeded)16210 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));16211 16212 ExprResult Res =16213 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);16214 if (Res.isInvalid())16215 return ExprError();16216 MemExprE = Res.get();16217 16218 // If overload resolution picked a static member16219 // build a non-member call based on that function.16220 if (Method->isStatic()) {16221 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,16222 ExecConfig, IsExecConfig);16223 }16224 16225 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());16226 }16227 16228 QualType ResultType = Method->getReturnType();16229 ExprValueKind VK = Expr::getValueKindForType(ResultType);16230 ResultType = ResultType.getNonLValueExprType(Context);16231 16232 assert(Method && "Member call to something that isn't a method?");16233 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();16234 16235 CallExpr *TheCall = nullptr;16236 llvm::SmallVector<Expr *, 8> NewArgs;16237 if (Method->isExplicitObjectMemberFunction()) {16238 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,16239 NewArgs))16240 return ExprError();16241 16242 // Build the actual expression node.16243 ExprResult FnExpr =16244 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,16245 HadMultipleCandidates, MemExpr->getExprLoc());16246 if (FnExpr.isInvalid())16247 return ExprError();16248 16249 TheCall =16250 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,16251 CurFPFeatureOverrides(), Proto->getNumParams());16252 TheCall->setUsesMemberSyntax(true);16253 } else {16254 // Convert the object argument (for a non-static member function call).16255 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(16256 MemExpr->getBase(), Qualifier, FoundDecl, Method);16257 if (ObjectArg.isInvalid())16258 return ExprError();16259 MemExpr->setBase(ObjectArg.get());16260 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,16261 RParenLoc, CurFPFeatureOverrides(),16262 Proto->getNumParams());16263 }16264 16265 // Check for a valid return type.16266 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),16267 TheCall, Method))16268 return BuildRecoveryExpr(ResultType);16269 16270 // Convert the rest of the arguments16271 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,16272 RParenLoc))16273 return BuildRecoveryExpr(ResultType);16274 16275 DiagnoseSentinelCalls(Method, LParenLoc, Args);16276 16277 if (CheckFunctionCall(Method, TheCall, Proto))16278 return ExprError();16279 16280 // In the case the method to call was not selected by the overloading16281 // resolution process, we still need to handle the enable_if attribute. Do16282 // that here, so it will not hide previous -- and more relevant -- errors.16283 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {16284 if (const EnableIfAttr *Attr =16285 CheckEnableIf(Method, LParenLoc, Args, true)) {16286 Diag(MemE->getMemberLoc(),16287 diag::err_ovl_no_viable_member_function_in_call)16288 << Method << Method->getSourceRange();16289 Diag(Method->getLocation(),16290 diag::note_ovl_candidate_disabled_by_function_cond_attr)16291 << Attr->getCond()->getSourceRange() << Attr->getMessage();16292 return ExprError();16293 }16294 }16295 16296 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&16297 TheCall->getDirectCallee()->isPureVirtual()) {16298 const FunctionDecl *MD = TheCall->getDirectCallee();16299 16300 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&16301 MemExpr->performsVirtualDispatch(getLangOpts())) {16302 Diag(MemExpr->getBeginLoc(),16303 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)16304 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)16305 << MD->getParent();16306 16307 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();16308 if (getLangOpts().AppleKext)16309 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)16310 << MD->getParent() << MD->getDeclName();16311 }16312 }16313 16314 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {16315 // a->A::f() doesn't go through the vtable, except in AppleKext mode.16316 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;16317 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,16318 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,16319 MemExpr->getMemberLoc());16320 }16321 16322 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),16323 TheCall->getDirectCallee());16324}16325 16326ExprResult16327Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,16328 SourceLocation LParenLoc,16329 MultiExprArg Args,16330 SourceLocation RParenLoc) {16331 if (checkPlaceholderForOverload(*this, Obj))16332 return ExprError();16333 ExprResult Object = Obj;16334 16335 UnbridgedCastsSet UnbridgedCasts;16336 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))16337 return ExprError();16338 16339 assert(Object.get()->getType()->isRecordType() &&16340 "Requires object type argument");16341 16342 // C++ [over.call.object]p1:16343 // If the primary-expression E in the function call syntax16344 // evaluates to a class object of type "cv T", then the set of16345 // candidate functions includes at least the function call16346 // operators of T. The function call operators of T are obtained by16347 // ordinary lookup of the name operator() in the context of16348 // (E).operator().16349 OverloadCandidateSet CandidateSet(LParenLoc,16350 OverloadCandidateSet::CSK_Operator);16351 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);16352 16353 if (RequireCompleteType(LParenLoc, Object.get()->getType(),16354 diag::err_incomplete_object_call, Object.get()))16355 return true;16356 16357 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();16358 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);16359 LookupQualifiedName(R, Record);16360 R.suppressAccessDiagnostics();16361 16362 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();16363 Oper != OperEnd; ++Oper) {16364 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),16365 Object.get()->Classify(Context), Args, CandidateSet,16366 /*SuppressUserConversion=*/false);16367 }16368 16369 // When calling a lambda, both the call operator, and16370 // the conversion operator to function pointer16371 // are considered. But when constraint checking16372 // on the call operator fails, it will also fail on the16373 // conversion operator as the constraints are always the same.16374 // As the user probably does not intend to perform a surrogate call,16375 // we filter them out to produce better error diagnostics, ie to avoid16376 // showing 2 failed overloads instead of one.16377 bool IgnoreSurrogateFunctions = false;16378 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {16379 const OverloadCandidate &Candidate = *CandidateSet.begin();16380 if (!Candidate.Viable &&16381 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)16382 IgnoreSurrogateFunctions = true;16383 }16384 16385 // C++ [over.call.object]p2:16386 // In addition, for each (non-explicit in C++0x) conversion function16387 // declared in T of the form16388 //16389 // operator conversion-type-id () cv-qualifier;16390 //16391 // where cv-qualifier is the same cv-qualification as, or a16392 // greater cv-qualification than, cv, and where conversion-type-id16393 // denotes the type "pointer to function of (P1,...,Pn) returning16394 // R", or the type "reference to pointer to function of16395 // (P1,...,Pn) returning R", or the type "reference to function16396 // of (P1,...,Pn) returning R", a surrogate call function [...]16397 // is also considered as a candidate function. Similarly,16398 // surrogate call functions are added to the set of candidate16399 // functions for each conversion function declared in an16400 // accessible base class provided the function is not hidden16401 // within T by another intervening declaration.16402 const auto &Conversions = Record->getVisibleConversionFunctions();16403 for (auto I = Conversions.begin(), E = Conversions.end();16404 !IgnoreSurrogateFunctions && I != E; ++I) {16405 NamedDecl *D = *I;16406 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());16407 if (isa<UsingShadowDecl>(D))16408 D = cast<UsingShadowDecl>(D)->getTargetDecl();16409 16410 // Skip over templated conversion functions; they aren't16411 // surrogates.16412 if (isa<FunctionTemplateDecl>(D))16413 continue;16414 16415 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);16416 if (!Conv->isExplicit()) {16417 // Strip the reference type (if any) and then the pointer type (if16418 // any) to get down to what might be a function type.16419 QualType ConvType = Conv->getConversionType().getNonReferenceType();16420 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())16421 ConvType = ConvPtrType->getPointeeType();16422 16423 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())16424 {16425 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,16426 Object.get(), Args, CandidateSet);16427 }16428 }16429 }16430 16431 bool HadMultipleCandidates = (CandidateSet.size() > 1);16432 16433 // Perform overload resolution.16434 OverloadCandidateSet::iterator Best;16435 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),16436 Best)) {16437 case OR_Success:16438 // Overload resolution succeeded; we'll build the appropriate call16439 // below.16440 break;16441 16442 case OR_No_Viable_Function: {16443 PartialDiagnostic PD =16444 CandidateSet.empty()16445 ? (PDiag(diag::err_ovl_no_oper)16446 << Object.get()->getType() << /*call*/ 116447 << Object.get()->getSourceRange())16448 : (PDiag(diag::err_ovl_no_viable_object_call)16449 << Object.get()->getType() << Object.get()->getSourceRange());16450 CandidateSet.NoteCandidates(16451 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,16452 OCD_AllCandidates, Args);16453 break;16454 }16455 case OR_Ambiguous:16456 if (!R.isAmbiguous())16457 CandidateSet.NoteCandidates(16458 PartialDiagnosticAt(Object.get()->getBeginLoc(),16459 PDiag(diag::err_ovl_ambiguous_object_call)16460 << Object.get()->getType()16461 << Object.get()->getSourceRange()),16462 *this, OCD_AmbiguousCandidates, Args);16463 break;16464 16465 case OR_Deleted: {16466 // FIXME: Is this diagnostic here really necessary? It seems that16467 // 1. we don't have any tests for this diagnostic, and16468 // 2. we already issue err_deleted_function_use for this later on anyway.16469 StringLiteral *Msg = Best->Function->getDeletedMessage();16470 CandidateSet.NoteCandidates(16471 PartialDiagnosticAt(Object.get()->getBeginLoc(),16472 PDiag(diag::err_ovl_deleted_object_call)16473 << Object.get()->getType() << (Msg != nullptr)16474 << (Msg ? Msg->getString() : StringRef())16475 << Object.get()->getSourceRange()),16476 *this, OCD_AllCandidates, Args);16477 break;16478 }16479 }16480 16481 if (Best == CandidateSet.end())16482 return true;16483 16484 UnbridgedCasts.restore();16485 16486 if (Best->Function == nullptr) {16487 // Since there is no function declaration, this is one of the16488 // surrogate candidates. Dig out the conversion function.16489 CXXConversionDecl *Conv16490 = cast<CXXConversionDecl>(16491 Best->Conversions[0].UserDefined.ConversionFunction);16492 16493 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,16494 Best->FoundDecl);16495 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))16496 return ExprError();16497 assert(Conv == Best->FoundDecl.getDecl() &&16498 "Found Decl & conversion-to-functionptr should be same, right?!");16499 // We selected one of the surrogate functions that converts the16500 // object parameter to a function pointer. Perform the conversion16501 // on the object argument, then let BuildCallExpr finish the job.16502 16503 // Create an implicit member expr to refer to the conversion operator.16504 // and then call it.16505 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,16506 Conv, HadMultipleCandidates);16507 if (Call.isInvalid())16508 return ExprError();16509 // Record usage of conversion in an implicit cast.16510 Call = ImplicitCastExpr::Create(16511 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),16512 nullptr, VK_PRValue, CurFPFeatureOverrides());16513 16514 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);16515 }16516 16517 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);16518 16519 // We found an overloaded operator(). Build a CXXOperatorCallExpr16520 // that calls this method, using Object for the implicit object16521 // parameter and passing along the remaining arguments.16522 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);16523 16524 // An error diagnostic has already been printed when parsing the declaration.16525 if (Method->isInvalidDecl())16526 return ExprError();16527 16528 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();16529 unsigned NumParams = Proto->getNumParams();16530 16531 DeclarationNameInfo OpLocInfo(16532 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);16533 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));16534 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,16535 Obj, HadMultipleCandidates,16536 OpLocInfo.getLoc(),16537 OpLocInfo.getInfo());16538 if (NewFn.isInvalid())16539 return true;16540 16541 SmallVector<Expr *, 8> MethodArgs;16542 MethodArgs.reserve(NumParams + 1);16543 16544 bool IsError = false;16545 16546 // Initialize the object parameter.16547 llvm::SmallVector<Expr *, 8> NewArgs;16548 if (Method->isExplicitObjectMemberFunction()) {16549 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);16550 } else {16551 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(16552 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);16553 if (ObjRes.isInvalid())16554 IsError = true;16555 else16556 Object = ObjRes;16557 MethodArgs.push_back(Object.get());16558 }16559 16560 IsError |= PrepareArgumentsForCallToObjectOfClassType(16561 *this, MethodArgs, Method, Args, LParenLoc);16562 16563 // If this is a variadic call, handle args passed through "...".16564 if (Proto->isVariadic()) {16565 // Promote the arguments (C99 6.5.2.2p7).16566 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {16567 ExprResult Arg = DefaultVariadicArgumentPromotion(16568 Args[i], VariadicCallType::Method, nullptr);16569 IsError |= Arg.isInvalid();16570 MethodArgs.push_back(Arg.get());16571 }16572 }16573 16574 if (IsError)16575 return true;16576 16577 DiagnoseSentinelCalls(Method, LParenLoc, Args);16578 16579 // Once we've built TheCall, all of the expressions are properly owned.16580 QualType ResultTy = Method->getReturnType();16581 ExprValueKind VK = Expr::getValueKindForType(ResultTy);16582 ResultTy = ResultTy.getNonLValueExprType(Context);16583 16584 CallExpr *TheCall = CXXOperatorCallExpr::Create(16585 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,16586 CurFPFeatureOverrides());16587 16588 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))16589 return true;16590 16591 if (CheckFunctionCall(Method, TheCall, Proto))16592 return true;16593 16594 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);16595}16596 16597ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,16598 SourceLocation OpLoc,16599 bool *NoArrowOperatorFound) {16600 assert(Base->getType()->isRecordType() &&16601 "left-hand side must have class type");16602 16603 if (checkPlaceholderForOverload(*this, Base))16604 return ExprError();16605 16606 SourceLocation Loc = Base->getExprLoc();16607 16608 // C++ [over.ref]p1:16609 //16610 // [...] An expression x->m is interpreted as (x.operator->())->m16611 // for a class object x of type T if T::operator->() exists and if16612 // the operator is selected as the best match function by the16613 // overload resolution mechanism (13.3).16614 DeclarationName OpName =16615 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);16616 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);16617 16618 if (RequireCompleteType(Loc, Base->getType(),16619 diag::err_typecheck_incomplete_tag, Base))16620 return ExprError();16621 16622 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);16623 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());16624 R.suppressAccessDiagnostics();16625 16626 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();16627 Oper != OperEnd; ++Oper) {16628 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),16629 {}, CandidateSet,16630 /*SuppressUserConversion=*/false);16631 }16632 16633 bool HadMultipleCandidates = (CandidateSet.size() > 1);16634 16635 // Perform overload resolution.16636 OverloadCandidateSet::iterator Best;16637 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {16638 case OR_Success:16639 // Overload resolution succeeded; we'll build the call below.16640 break;16641 16642 case OR_No_Viable_Function: {16643 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);16644 if (CandidateSet.empty()) {16645 QualType BaseType = Base->getType();16646 if (NoArrowOperatorFound) {16647 // Report this specific error to the caller instead of emitting a16648 // diagnostic, as requested.16649 *NoArrowOperatorFound = true;16650 return ExprError();16651 }16652 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)16653 << BaseType << Base->getSourceRange();16654 if (BaseType->isRecordType() && !BaseType->isPointerType()) {16655 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)16656 << FixItHint::CreateReplacement(OpLoc, ".");16657 }16658 } else16659 Diag(OpLoc, diag::err_ovl_no_viable_oper)16660 << "operator->" << Base->getSourceRange();16661 CandidateSet.NoteCandidates(*this, Base, Cands);16662 return ExprError();16663 }16664 case OR_Ambiguous:16665 if (!R.isAmbiguous())16666 CandidateSet.NoteCandidates(16667 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)16668 << "->" << Base->getType()16669 << Base->getSourceRange()),16670 *this, OCD_AmbiguousCandidates, Base);16671 return ExprError();16672 16673 case OR_Deleted: {16674 StringLiteral *Msg = Best->Function->getDeletedMessage();16675 CandidateSet.NoteCandidates(16676 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)16677 << "->" << (Msg != nullptr)16678 << (Msg ? Msg->getString() : StringRef())16679 << Base->getSourceRange()),16680 *this, OCD_AllCandidates, Base);16681 return ExprError();16682 }16683 }16684 16685 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);16686 16687 // Convert the object parameter.16688 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);16689 16690 if (Method->isExplicitObjectMemberFunction()) {16691 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);16692 if (R.isInvalid())16693 return ExprError();16694 Base = R.get();16695 } else {16696 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(16697 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);16698 if (BaseResult.isInvalid())16699 return ExprError();16700 Base = BaseResult.get();16701 }16702 16703 // Build the operator call.16704 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,16705 Base, HadMultipleCandidates, OpLoc);16706 if (FnExpr.isInvalid())16707 return ExprError();16708 16709 QualType ResultTy = Method->getReturnType();16710 ExprValueKind VK = Expr::getValueKindForType(ResultTy);16711 ResultTy = ResultTy.getNonLValueExprType(Context);16712 16713 CallExpr *TheCall =16714 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,16715 ResultTy, VK, OpLoc, CurFPFeatureOverrides());16716 16717 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))16718 return ExprError();16719 16720 if (CheckFunctionCall(Method, TheCall,16721 Method->getType()->castAs<FunctionProtoType>()))16722 return ExprError();16723 16724 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);16725}16726 16727ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,16728 DeclarationNameInfo &SuffixInfo,16729 ArrayRef<Expr*> Args,16730 SourceLocation LitEndLoc,16731 TemplateArgumentListInfo *TemplateArgs) {16732 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();16733 16734 OverloadCandidateSet CandidateSet(UDSuffixLoc,16735 OverloadCandidateSet::CSK_Normal);16736 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,16737 TemplateArgs);16738 16739 bool HadMultipleCandidates = (CandidateSet.size() > 1);16740 16741 // Perform overload resolution. This will usually be trivial, but might need16742 // to perform substitutions for a literal operator template.16743 OverloadCandidateSet::iterator Best;16744 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {16745 case OR_Success:16746 case OR_Deleted:16747 break;16748 16749 case OR_No_Viable_Function:16750 CandidateSet.NoteCandidates(16751 PartialDiagnosticAt(UDSuffixLoc,16752 PDiag(diag::err_ovl_no_viable_function_in_call)16753 << R.getLookupName()),16754 *this, OCD_AllCandidates, Args);16755 return ExprError();16756 16757 case OR_Ambiguous:16758 CandidateSet.NoteCandidates(16759 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)16760 << R.getLookupName()),16761 *this, OCD_AmbiguousCandidates, Args);16762 return ExprError();16763 }16764 16765 FunctionDecl *FD = Best->Function;16766 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,16767 nullptr, HadMultipleCandidates,16768 SuffixInfo.getLoc(),16769 SuffixInfo.getInfo());16770 if (Fn.isInvalid())16771 return true;16772 16773 // Check the argument types. This should almost always be a no-op, except16774 // that array-to-pointer decay is applied to string literals.16775 Expr *ConvArgs[2];16776 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {16777 ExprResult InputInit = PerformCopyInitialization(16778 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),16779 SourceLocation(), Args[ArgIdx]);16780 if (InputInit.isInvalid())16781 return true;16782 ConvArgs[ArgIdx] = InputInit.get();16783 }16784 16785 QualType ResultTy = FD->getReturnType();16786 ExprValueKind VK = Expr::getValueKindForType(ResultTy);16787 ResultTy = ResultTy.getNonLValueExprType(Context);16788 16789 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(16790 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,16791 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());16792 16793 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))16794 return ExprError();16795 16796 if (CheckFunctionCall(FD, UDL, nullptr))16797 return ExprError();16798 16799 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);16800}16801 16802Sema::ForRangeStatus16803Sema::BuildForRangeBeginEndCall(SourceLocation Loc,16804 SourceLocation RangeLoc,16805 const DeclarationNameInfo &NameInfo,16806 LookupResult &MemberLookup,16807 OverloadCandidateSet *CandidateSet,16808 Expr *Range, ExprResult *CallExpr) {16809 Scope *S = nullptr;16810 16811 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);16812 if (!MemberLookup.empty()) {16813 ExprResult MemberRef =16814 BuildMemberReferenceExpr(Range, Range->getType(), Loc,16815 /*IsPtr=*/false, CXXScopeSpec(),16816 /*TemplateKWLoc=*/SourceLocation(),16817 /*FirstQualifierInScope=*/nullptr,16818 MemberLookup,16819 /*TemplateArgs=*/nullptr, S);16820 if (MemberRef.isInvalid()) {16821 *CallExpr = ExprError();16822 return FRS_DiagnosticIssued;16823 }16824 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);16825 if (CallExpr->isInvalid()) {16826 *CallExpr = ExprError();16827 return FRS_DiagnosticIssued;16828 }16829 } else {16830 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,16831 NestedNameSpecifierLoc(),16832 NameInfo, UnresolvedSet<0>());16833 if (FnR.isInvalid())16834 return FRS_DiagnosticIssued;16835 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());16836 16837 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,16838 CandidateSet, CallExpr);16839 if (CandidateSet->empty() || CandidateSetError) {16840 *CallExpr = ExprError();16841 return FRS_NoViableFunction;16842 }16843 OverloadCandidateSet::iterator Best;16844 OverloadingResult OverloadResult =16845 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);16846 16847 if (OverloadResult == OR_No_Viable_Function) {16848 *CallExpr = ExprError();16849 return FRS_NoViableFunction;16850 }16851 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,16852 Loc, nullptr, CandidateSet, &Best,16853 OverloadResult,16854 /*AllowTypoCorrection=*/false);16855 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {16856 *CallExpr = ExprError();16857 return FRS_DiagnosticIssued;16858 }16859 }16860 return FRS_Success;16861}16862 16863ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,16864 FunctionDecl *Fn) {16865 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {16866 ExprResult SubExpr =16867 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);16868 if (SubExpr.isInvalid())16869 return ExprError();16870 if (SubExpr.get() == PE->getSubExpr())16871 return PE;16872 16873 return new (Context)16874 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());16875 }16876 16877 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {16878 ExprResult SubExpr =16879 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);16880 if (SubExpr.isInvalid())16881 return ExprError();16882 assert(Context.hasSameType(ICE->getSubExpr()->getType(),16883 SubExpr.get()->getType()) &&16884 "Implicit cast type cannot be determined from overload");16885 assert(ICE->path_empty() && "fixing up hierarchy conversion?");16886 if (SubExpr.get() == ICE->getSubExpr())16887 return ICE;16888 16889 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),16890 SubExpr.get(), nullptr, ICE->getValueKind(),16891 CurFPFeatureOverrides());16892 }16893 16894 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {16895 if (!GSE->isResultDependent()) {16896 ExprResult SubExpr =16897 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);16898 if (SubExpr.isInvalid())16899 return ExprError();16900 if (SubExpr.get() == GSE->getResultExpr())16901 return GSE;16902 16903 // Replace the resulting type information before rebuilding the generic16904 // selection expression.16905 ArrayRef<Expr *> A = GSE->getAssocExprs();16906 SmallVector<Expr *, 4> AssocExprs(A);16907 unsigned ResultIdx = GSE->getResultIndex();16908 AssocExprs[ResultIdx] = SubExpr.get();16909 16910 if (GSE->isExprPredicate())16911 return GenericSelectionExpr::Create(16912 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),16913 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),16914 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),16915 ResultIdx);16916 return GenericSelectionExpr::Create(16917 Context, GSE->getGenericLoc(), GSE->getControllingType(),16918 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),16919 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),16920 ResultIdx);16921 }16922 // Rather than fall through to the unreachable, return the original generic16923 // selection expression.16924 return GSE;16925 }16926 16927 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {16928 assert(UnOp->getOpcode() == UO_AddrOf &&16929 "Can only take the address of an overloaded function");16930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {16931 if (!Method->isImplicitObjectMemberFunction()) {16932 // Do nothing: the address of static and16933 // explicit object member functions is a (non-member) function pointer.16934 } else {16935 // Fix the subexpression, which really has to be an16936 // UnresolvedLookupExpr holding an overloaded member function16937 // or template.16938 ExprResult SubExpr =16939 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);16940 if (SubExpr.isInvalid())16941 return ExprError();16942 if (SubExpr.get() == UnOp->getSubExpr())16943 return UnOp;16944 16945 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),16946 SubExpr.get(), Method))16947 return ExprError();16948 16949 assert(isa<DeclRefExpr>(SubExpr.get()) &&16950 "fixed to something other than a decl ref");16951 NestedNameSpecifier Qualifier =16952 cast<DeclRefExpr>(SubExpr.get())->getQualifier();16953 assert(Qualifier &&16954 "fixed to a member ref with no nested name qualifier");16955 16956 // We have taken the address of a pointer to member16957 // function. Perform the computation here so that we get the16958 // appropriate pointer to member type.16959 QualType MemPtrType = Context.getMemberPointerType(16960 Fn->getType(), Qualifier,16961 cast<CXXRecordDecl>(Method->getDeclContext()));16962 // Under the MS ABI, lock down the inheritance model now.16963 if (Context.getTargetInfo().getCXXABI().isMicrosoft())16964 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);16965 16966 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,16967 MemPtrType, VK_PRValue, OK_Ordinary,16968 UnOp->getOperatorLoc(), false,16969 CurFPFeatureOverrides());16970 }16971 }16972 ExprResult SubExpr =16973 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);16974 if (SubExpr.isInvalid())16975 return ExprError();16976 if (SubExpr.get() == UnOp->getSubExpr())16977 return UnOp;16978 16979 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,16980 SubExpr.get());16981 }16982 16983 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {16984 if (Found.getAccess() == AS_none) {16985 CheckUnresolvedLookupAccess(ULE, Found);16986 }16987 // FIXME: avoid copy.16988 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;16989 if (ULE->hasExplicitTemplateArgs()) {16990 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);16991 TemplateArgs = &TemplateArgsBuffer;16992 }16993 16994 QualType Type = Fn->getType();16995 ExprValueKind ValueKind =16996 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()16997 ? VK_LValue16998 : VK_PRValue;16999 17000 // FIXME: Duplicated from BuildDeclarationNameExpr.17001 if (unsigned BID = Fn->getBuiltinID()) {17002 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {17003 Type = Context.BuiltinFnTy;17004 ValueKind = VK_PRValue;17005 }17006 }17007 17008 DeclRefExpr *DRE = BuildDeclRefExpr(17009 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),17010 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);17011 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);17012 return DRE;17013 }17014 17015 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {17016 // FIXME: avoid copy.17017 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;17018 if (MemExpr->hasExplicitTemplateArgs()) {17019 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);17020 TemplateArgs = &TemplateArgsBuffer;17021 }17022 17023 Expr *Base;17024 17025 // If we're filling in a static method where we used to have an17026 // implicit member access, rewrite to a simple decl ref.17027 if (MemExpr->isImplicitAccess()) {17028 if (cast<CXXMethodDecl>(Fn)->isStatic()) {17029 DeclRefExpr *DRE = BuildDeclRefExpr(17030 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),17031 MemExpr->getQualifierLoc(), Found.getDecl(),17032 MemExpr->getTemplateKeywordLoc(), TemplateArgs);17033 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);17034 return DRE;17035 } else {17036 SourceLocation Loc = MemExpr->getMemberLoc();17037 if (MemExpr->getQualifier())17038 Loc = MemExpr->getQualifierLoc().getBeginLoc();17039 Base =17040 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);17041 }17042 } else17043 Base = MemExpr->getBase();17044 17045 ExprValueKind valueKind;17046 QualType type;17047 if (cast<CXXMethodDecl>(Fn)->isStatic()) {17048 valueKind = VK_LValue;17049 type = Fn->getType();17050 } else {17051 valueKind = VK_PRValue;17052 type = Context.BoundMemberTy;17053 }17054 17055 return BuildMemberExpr(17056 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),17057 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,17058 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),17059 type, valueKind, OK_Ordinary, TemplateArgs);17060 }17061 17062 llvm_unreachable("Invalid reference to overloaded function");17063}17064 17065ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,17066 DeclAccessPair Found,17067 FunctionDecl *Fn) {17068 return FixOverloadedFunctionReference(E.get(), Found, Fn);17069}17070 17071bool clang::shouldEnforceArgLimit(bool PartialOverloading,17072 FunctionDecl *Function) {17073 if (!PartialOverloading || !Function)17074 return true;17075 if (Function->isVariadic())17076 return false;17077 if (const auto *Proto =17078 dyn_cast<FunctionProtoType>(Function->getFunctionType()))17079 if (Proto->isTemplateVariadic())17080 return false;17081 if (auto *Pattern = Function->getTemplateInstantiationPattern())17082 if (const auto *Proto =17083 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))17084 if (Proto->isTemplateVariadic())17085 return false;17086 return true;17087}17088 17089void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,17090 DeclarationName Name,17091 OverloadCandidateSet &CandidateSet,17092 FunctionDecl *Fn, MultiExprArg Args,17093 bool IsMember) {17094 StringLiteral *Msg = Fn->getDeletedMessage();17095 CandidateSet.NoteCandidates(17096 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)17097 << IsMember << Name << (Msg != nullptr)17098 << (Msg ? Msg->getString() : StringRef())17099 << Range),17100 *this, OCD_AllCandidates, Args);17101}17102