1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CheckExprLifetime.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/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/SemaCUDA.h" 34 #include "clang/Sema/SemaObjC.h" 35 #include "clang/Sema/Template.h" 36 #include "clang/Sema/TemplateDeduction.h" 37 #include "llvm/ADT/DenseSet.h" 38 #include "llvm/ADT/STLExtras.h" 39 #include "llvm/ADT/STLForwardCompat.h" 40 #include "llvm/ADT/ScopeExit.h" 41 #include "llvm/ADT/SmallPtrSet.h" 42 #include "llvm/ADT/SmallVector.h" 43 #include <algorithm> 44 #include <cassert> 45 #include <cstddef> 46 #include <cstdlib> 47 #include <optional> 48 49 using namespace clang; 50 using namespace sema; 51 52 using AllowedExplicit = Sema::AllowedExplicit; 53 54 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 55 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 56 return P->hasAttr<PassObjectSizeAttr>(); 57 }); 58 } 59 60 /// A convenience routine for creating a decayed reference to a function. 61 static ExprResult CreateFunctionRefExpr( 62 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, 63 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), 64 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { 65 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 66 return ExprError(); 67 // If FoundDecl is different from Fn (such as if one is a template 68 // and the other a specialization), make sure DiagnoseUseOfDecl is 69 // called on both. 70 // FIXME: This would be more comprehensively addressed by modifying 71 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 72 // being used. 73 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 74 return ExprError(); 75 DeclRefExpr *DRE = new (S.Context) 76 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 77 if (HadMultipleCandidates) 78 DRE->setHadMultipleCandidates(true); 79 80 S.MarkDeclRefReferenced(DRE, Base); 81 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 82 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 83 S.ResolveExceptionSpec(Loc, FPT); 84 DRE->setType(Fn->getType()); 85 } 86 } 87 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 88 CK_FunctionToPointerDecay); 89 } 90 91 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 92 bool InOverloadResolution, 93 StandardConversionSequence &SCS, 94 bool CStyle, 95 bool AllowObjCWritebackConversion); 96 97 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 98 QualType &ToType, 99 bool InOverloadResolution, 100 StandardConversionSequence &SCS, 101 bool CStyle); 102 static OverloadingResult 103 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 104 UserDefinedConversionSequence& User, 105 OverloadCandidateSet& Conversions, 106 AllowedExplicit AllowExplicit, 107 bool AllowObjCConversionOnExplicit); 108 109 static ImplicitConversionSequence::CompareKind 110 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 111 const StandardConversionSequence& SCS1, 112 const StandardConversionSequence& SCS2); 113 114 static ImplicitConversionSequence::CompareKind 115 CompareQualificationConversions(Sema &S, 116 const StandardConversionSequence& SCS1, 117 const StandardConversionSequence& SCS2); 118 119 static ImplicitConversionSequence::CompareKind 120 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 121 const StandardConversionSequence& SCS1, 122 const StandardConversionSequence& SCS2); 123 124 /// GetConversionRank - Retrieve the implicit conversion rank 125 /// corresponding to the given implicit conversion kind. 126 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 127 static const ImplicitConversionRank Rank[] = { 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Exact_Match, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Promotion, 137 ICR_Conversion, 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_OCL_Scalar_Widening, 150 ICR_Complex_Real_Conversion, 151 ICR_Conversion, 152 ICR_Conversion, 153 ICR_Writeback_Conversion, 154 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 155 // it was omitted by the patch that added 156 // ICK_Zero_Event_Conversion 157 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right -- 158 // it was omitted by the patch that added 159 // ICK_Zero_Queue_Conversion 160 ICR_C_Conversion, 161 ICR_C_Conversion_Extension, 162 ICR_Conversion, 163 ICR_HLSL_Dimension_Reduction, 164 ICR_Conversion, 165 ICR_HLSL_Scalar_Widening, 166 }; 167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds); 168 return Rank[(int)Kind]; 169 } 170 171 ImplicitConversionRank 172 clang::GetDimensionConversionRank(ImplicitConversionRank Base, 173 ImplicitConversionKind Dimension) { 174 ImplicitConversionRank Rank = GetConversionRank(Dimension); 175 if (Rank == ICR_HLSL_Scalar_Widening) { 176 if (Base == ICR_Promotion) 177 return ICR_HLSL_Scalar_Widening_Promotion; 178 if (Base == ICR_Conversion) 179 return ICR_HLSL_Scalar_Widening_Conversion; 180 } 181 if (Rank == ICR_HLSL_Dimension_Reduction) { 182 if (Base == ICR_Promotion) 183 return ICR_HLSL_Dimension_Reduction_Promotion; 184 if (Base == ICR_Conversion) 185 return ICR_HLSL_Dimension_Reduction_Conversion; 186 } 187 return Rank; 188 } 189 190 /// GetImplicitConversionName - Return the name of this kind of 191 /// implicit conversion. 192 static const char *GetImplicitConversionName(ImplicitConversionKind Kind) { 193 static const char *const Name[] = { 194 "No conversion", 195 "Lvalue-to-rvalue", 196 "Array-to-pointer", 197 "Function-to-pointer", 198 "Function pointer conversion", 199 "Qualification", 200 "Integral promotion", 201 "Floating point promotion", 202 "Complex promotion", 203 "Integral conversion", 204 "Floating conversion", 205 "Complex conversion", 206 "Floating-integral conversion", 207 "Pointer conversion", 208 "Pointer-to-member conversion", 209 "Boolean conversion", 210 "Compatible-types conversion", 211 "Derived-to-base conversion", 212 "Vector conversion", 213 "SVE Vector conversion", 214 "RVV Vector conversion", 215 "Vector splat", 216 "Complex-real conversion", 217 "Block Pointer conversion", 218 "Transparent Union Conversion", 219 "Writeback conversion", 220 "OpenCL Zero Event Conversion", 221 "OpenCL Zero Queue Conversion", 222 "C specific type conversion", 223 "Incompatible pointer conversion", 224 "Fixed point conversion", 225 "HLSL vector truncation", 226 "Non-decaying array conversion", 227 "HLSL vector splat", 228 }; 229 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds); 230 return Name[Kind]; 231 } 232 233 /// StandardConversionSequence - Set the standard conversion 234 /// sequence to the identity conversion. 235 void StandardConversionSequence::setAsIdentityConversion() { 236 First = ICK_Identity; 237 Second = ICK_Identity; 238 Dimension = ICK_Identity; 239 Third = ICK_Identity; 240 DeprecatedStringLiteralToCharPtr = false; 241 QualificationIncludesObjCLifetime = false; 242 ReferenceBinding = false; 243 DirectBinding = false; 244 IsLvalueReference = true; 245 BindsToFunctionLvalue = false; 246 BindsToRvalue = false; 247 BindsImplicitObjectArgumentWithoutRefQualifier = false; 248 ObjCLifetimeConversionBinding = false; 249 CopyConstructor = nullptr; 250 } 251 252 /// getRank - Retrieve the rank of this standard conversion sequence 253 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 254 /// implicit conversions. 255 ImplicitConversionRank StandardConversionSequence::getRank() const { 256 ImplicitConversionRank Rank = ICR_Exact_Match; 257 if (GetConversionRank(First) > Rank) 258 Rank = GetConversionRank(First); 259 if (GetConversionRank(Second) > Rank) 260 Rank = GetConversionRank(Second); 261 if (GetDimensionConversionRank(Rank, Dimension) > Rank) 262 Rank = GetDimensionConversionRank(Rank, Dimension); 263 if (GetConversionRank(Third) > Rank) 264 Rank = GetConversionRank(Third); 265 return Rank; 266 } 267 268 /// isPointerConversionToBool - Determines whether this conversion is 269 /// a conversion of a pointer or pointer-to-member to bool. This is 270 /// used as part of the ranking of standard conversion sequences 271 /// (C++ 13.3.3.2p4). 272 bool StandardConversionSequence::isPointerConversionToBool() const { 273 // Note that FromType has not necessarily been transformed by the 274 // array-to-pointer or function-to-pointer implicit conversions, so 275 // check for their presence as well as checking whether FromType is 276 // a pointer. 277 if (getToType(1)->isBooleanType() && 278 (getFromType()->isPointerType() || 279 getFromType()->isMemberPointerType() || 280 getFromType()->isObjCObjectPointerType() || 281 getFromType()->isBlockPointerType() || 282 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 283 return true; 284 285 return false; 286 } 287 288 /// isPointerConversionToVoidPointer - Determines whether this 289 /// conversion is a conversion of a pointer to a void pointer. This is 290 /// used as part of the ranking of standard conversion sequences (C++ 291 /// 13.3.3.2p4). 292 bool 293 StandardConversionSequence:: 294 isPointerConversionToVoidPointer(ASTContext& Context) const { 295 QualType FromType = getFromType(); 296 QualType ToType = getToType(1); 297 298 // Note that FromType has not necessarily been transformed by the 299 // array-to-pointer implicit conversion, so check for its presence 300 // and redo the conversion to get a pointer. 301 if (First == ICK_Array_To_Pointer) 302 FromType = Context.getArrayDecayedType(FromType); 303 304 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 305 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 306 return ToPtrType->getPointeeType()->isVoidType(); 307 308 return false; 309 } 310 311 /// Skip any implicit casts which could be either part of a narrowing conversion 312 /// or after one in an implicit conversion. 313 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 314 const Expr *Converted) { 315 // We can have cleanups wrapping the converted expression; these need to be 316 // preserved so that destructors run if necessary. 317 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 318 Expr *Inner = 319 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 320 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 321 EWC->getObjects()); 322 } 323 324 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 325 switch (ICE->getCastKind()) { 326 case CK_NoOp: 327 case CK_IntegralCast: 328 case CK_IntegralToBoolean: 329 case CK_IntegralToFloating: 330 case CK_BooleanToSignedIntegral: 331 case CK_FloatingToIntegral: 332 case CK_FloatingToBoolean: 333 case CK_FloatingCast: 334 Converted = ICE->getSubExpr(); 335 continue; 336 337 default: 338 return Converted; 339 } 340 } 341 342 return Converted; 343 } 344 345 /// Check if this standard conversion sequence represents a narrowing 346 /// conversion, according to C++11 [dcl.init.list]p7. 347 /// 348 /// \param Ctx The AST context. 349 /// \param Converted The result of applying this standard conversion sequence. 350 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 351 /// value of the expression prior to the narrowing conversion. 352 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 353 /// type of the expression prior to the narrowing conversion. 354 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 355 /// from floating point types to integral types should be ignored. 356 NarrowingKind StandardConversionSequence::getNarrowingKind( 357 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 358 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 359 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) && 360 "narrowing check outside C++"); 361 362 // C++11 [dcl.init.list]p7: 363 // A narrowing conversion is an implicit conversion ... 364 QualType FromType = getToType(0); 365 QualType ToType = getToType(1); 366 367 // A conversion to an enumeration type is narrowing if the conversion to 368 // the underlying type is narrowing. This only arises for expressions of 369 // the form 'Enum{init}'. 370 if (auto *ET = ToType->getAs<EnumType>()) 371 ToType = ET->getDecl()->getIntegerType(); 372 373 switch (Second) { 374 // 'bool' is an integral type; dispatch to the right place to handle it. 375 case ICK_Boolean_Conversion: 376 if (FromType->isRealFloatingType()) 377 goto FloatingIntegralConversion; 378 if (FromType->isIntegralOrUnscopedEnumerationType()) 379 goto IntegralConversion; 380 // -- from a pointer type or pointer-to-member type to bool, or 381 return NK_Type_Narrowing; 382 383 // -- from a floating-point type to an integer type, or 384 // 385 // -- from an integer type or unscoped enumeration type to a floating-point 386 // type, except where the source is a constant expression and the actual 387 // value after conversion will fit into the target type and will produce 388 // the original value when converted back to the original type, or 389 case ICK_Floating_Integral: 390 FloatingIntegralConversion: 391 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 392 return NK_Type_Narrowing; 393 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 394 ToType->isRealFloatingType()) { 395 if (IgnoreFloatToIntegralConversion) 396 return NK_Not_Narrowing; 397 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 398 assert(Initializer && "Unknown conversion expression"); 399 400 // If it's value-dependent, we can't tell whether it's narrowing. 401 if (Initializer->isValueDependent()) 402 return NK_Dependent_Narrowing; 403 404 if (std::optional<llvm::APSInt> IntConstantValue = 405 Initializer->getIntegerConstantExpr(Ctx)) { 406 // Convert the integer to the floating type. 407 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 408 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 409 llvm::APFloat::rmNearestTiesToEven); 410 // And back. 411 llvm::APSInt ConvertedValue = *IntConstantValue; 412 bool ignored; 413 Result.convertToInteger(ConvertedValue, 414 llvm::APFloat::rmTowardZero, &ignored); 415 // If the resulting value is different, this was a narrowing conversion. 416 if (*IntConstantValue != ConvertedValue) { 417 ConstantValue = APValue(*IntConstantValue); 418 ConstantType = Initializer->getType(); 419 return NK_Constant_Narrowing; 420 } 421 } else { 422 // Variables are always narrowings. 423 return NK_Variable_Narrowing; 424 } 425 } 426 return NK_Not_Narrowing; 427 428 // -- from long double to double or float, or from double to float, except 429 // where the source is a constant expression and the actual value after 430 // conversion is within the range of values that can be represented (even 431 // if it cannot be represented exactly), or 432 case ICK_Floating_Conversion: 433 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 434 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 435 // FromType is larger than ToType. 436 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 437 438 // If it's value-dependent, we can't tell whether it's narrowing. 439 if (Initializer->isValueDependent()) 440 return NK_Dependent_Narrowing; 441 442 Expr::EvalResult R; 443 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) || 444 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 445 // Constant! 446 if (Ctx.getLangOpts().C23) 447 ConstantValue = R.Val; 448 assert(ConstantValue.isFloat()); 449 llvm::APFloat FloatVal = ConstantValue.getFloat(); 450 // Convert the source value into the target type. 451 bool ignored; 452 llvm::APFloat Converted = FloatVal; 453 llvm::APFloat::opStatus ConvertStatus = 454 Converted.convert(Ctx.getFloatTypeSemantics(ToType), 455 llvm::APFloat::rmNearestTiesToEven, &ignored); 456 Converted.convert(Ctx.getFloatTypeSemantics(FromType), 457 llvm::APFloat::rmNearestTiesToEven, &ignored); 458 if (Ctx.getLangOpts().C23) { 459 if (FloatVal.isNaN() && Converted.isNaN() && 460 !FloatVal.isSignaling() && !Converted.isSignaling()) { 461 // Quiet NaNs are considered the same value, regardless of 462 // payloads. 463 return NK_Not_Narrowing; 464 } 465 // For normal values, check exact equality. 466 if (!Converted.bitwiseIsEqual(FloatVal)) { 467 ConstantType = Initializer->getType(); 468 return NK_Constant_Narrowing; 469 } 470 } else { 471 // If there was no overflow, the source value is within the range of 472 // values that can be represented. 473 if (ConvertStatus & llvm::APFloat::opOverflow) { 474 ConstantType = Initializer->getType(); 475 return NK_Constant_Narrowing; 476 } 477 } 478 } else { 479 return NK_Variable_Narrowing; 480 } 481 } 482 return NK_Not_Narrowing; 483 484 // -- from an integer type or unscoped enumeration type to an integer type 485 // that cannot represent all the values of the original type, except where 486 // (CWG2627) -- the source is a bit-field whose width w is less than that 487 // of its type (or, for an enumeration type, its underlying type) and the 488 // target type can represent all the values of a hypothetical extended 489 // integer type with width w and with the same signedness as the original 490 // type or 491 // -- the source is a constant expression and the actual value after 492 // conversion will fit into the target type and will produce the original 493 // value when converted back to the original type. 494 case ICK_Integral_Conversion: 495 IntegralConversion: { 496 assert(FromType->isIntegralOrUnscopedEnumerationType()); 497 assert(ToType->isIntegralOrUnscopedEnumerationType()); 498 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 499 unsigned FromWidth = Ctx.getIntWidth(FromType); 500 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 501 const unsigned ToWidth = Ctx.getIntWidth(ToType); 502 503 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth, 504 bool ToSigned, unsigned ToWidth) { 505 return (FromWidth < ToWidth + (FromSigned == ToSigned)) && 506 !(FromSigned && !ToSigned); 507 }; 508 509 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth)) 510 return NK_Not_Narrowing; 511 512 // Not all values of FromType can be represented in ToType. 513 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 514 515 bool DependentBitField = false; 516 if (const FieldDecl *BitField = Initializer->getSourceBitField()) { 517 if (BitField->getBitWidth()->isValueDependent()) 518 DependentBitField = true; 519 else if (unsigned BitFieldWidth = BitField->getBitWidthValue(); 520 BitFieldWidth < FromWidth) { 521 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth)) 522 return NK_Not_Narrowing; 523 524 // The initializer will be truncated to the bit-field width 525 FromWidth = BitFieldWidth; 526 } 527 } 528 529 // If it's value-dependent, we can't tell whether it's narrowing. 530 if (Initializer->isValueDependent()) 531 return NK_Dependent_Narrowing; 532 533 std::optional<llvm::APSInt> OptInitializerValue = 534 Initializer->getIntegerConstantExpr(Ctx); 535 if (!OptInitializerValue) { 536 // If the bit-field width was dependent, it might end up being small 537 // enough to fit in the target type (unless the target type is unsigned 538 // and the source type is signed, in which case it will never fit) 539 if (DependentBitField && !(FromSigned && !ToSigned)) 540 return NK_Dependent_Narrowing; 541 542 // Otherwise, such a conversion is always narrowing 543 return NK_Variable_Narrowing; 544 } 545 llvm::APSInt &InitializerValue = *OptInitializerValue; 546 bool Narrowing = false; 547 if (FromWidth < ToWidth) { 548 // Negative -> unsigned is narrowing. Otherwise, more bits is never 549 // narrowing. 550 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 551 Narrowing = true; 552 } else { 553 // Add a bit to the InitializerValue so we don't have to worry about 554 // signed vs. unsigned comparisons. 555 InitializerValue = 556 InitializerValue.extend(InitializerValue.getBitWidth() + 1); 557 // Convert the initializer to and from the target width and signed-ness. 558 llvm::APSInt ConvertedValue = InitializerValue; 559 ConvertedValue = ConvertedValue.trunc(ToWidth); 560 ConvertedValue.setIsSigned(ToSigned); 561 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 562 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 563 // If the result is different, this was a narrowing conversion. 564 if (ConvertedValue != InitializerValue) 565 Narrowing = true; 566 } 567 if (Narrowing) { 568 ConstantType = Initializer->getType(); 569 ConstantValue = APValue(InitializerValue); 570 return NK_Constant_Narrowing; 571 } 572 573 return NK_Not_Narrowing; 574 } 575 case ICK_Complex_Real: 576 if (FromType->isComplexType() && !ToType->isComplexType()) 577 return NK_Type_Narrowing; 578 return NK_Not_Narrowing; 579 580 case ICK_Floating_Promotion: 581 if (Ctx.getLangOpts().C23) { 582 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 583 Expr::EvalResult R; 584 if (Initializer->EvaluateAsRValue(R, Ctx)) { 585 ConstantValue = R.Val; 586 assert(ConstantValue.isFloat()); 587 llvm::APFloat FloatVal = ConstantValue.getFloat(); 588 // C23 6.7.3p6 If the initializer has real type and a signaling NaN 589 // value, the unqualified versions of the type of the initializer and 590 // the corresponding real type of the object declared shall be 591 // compatible. 592 if (FloatVal.isNaN() && FloatVal.isSignaling()) { 593 ConstantType = Initializer->getType(); 594 return NK_Constant_Narrowing; 595 } 596 } 597 } 598 return NK_Not_Narrowing; 599 default: 600 // Other kinds of conversions are not narrowings. 601 return NK_Not_Narrowing; 602 } 603 } 604 605 /// dump - Print this standard conversion sequence to standard 606 /// error. Useful for debugging overloading issues. 607 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 608 raw_ostream &OS = llvm::errs(); 609 bool PrintedSomething = false; 610 if (First != ICK_Identity) { 611 OS << GetImplicitConversionName(First); 612 PrintedSomething = true; 613 } 614 615 if (Second != ICK_Identity) { 616 if (PrintedSomething) { 617 OS << " -> "; 618 } 619 OS << GetImplicitConversionName(Second); 620 621 if (CopyConstructor) { 622 OS << " (by copy constructor)"; 623 } else if (DirectBinding) { 624 OS << " (direct reference binding)"; 625 } else if (ReferenceBinding) { 626 OS << " (reference binding)"; 627 } 628 PrintedSomething = true; 629 } 630 631 if (Third != ICK_Identity) { 632 if (PrintedSomething) { 633 OS << " -> "; 634 } 635 OS << GetImplicitConversionName(Third); 636 PrintedSomething = true; 637 } 638 639 if (!PrintedSomething) { 640 OS << "No conversions required"; 641 } 642 } 643 644 /// dump - Print this user-defined conversion sequence to standard 645 /// error. Useful for debugging overloading issues. 646 void UserDefinedConversionSequence::dump() const { 647 raw_ostream &OS = llvm::errs(); 648 if (Before.First || Before.Second || Before.Third) { 649 Before.dump(); 650 OS << " -> "; 651 } 652 if (ConversionFunction) 653 OS << '\'' << *ConversionFunction << '\''; 654 else 655 OS << "aggregate initialization"; 656 if (After.First || After.Second || After.Third) { 657 OS << " -> "; 658 After.dump(); 659 } 660 } 661 662 /// dump - Print this implicit conversion sequence to standard 663 /// error. Useful for debugging overloading issues. 664 void ImplicitConversionSequence::dump() const { 665 raw_ostream &OS = llvm::errs(); 666 if (hasInitializerListContainerType()) 667 OS << "Worst list element conversion: "; 668 switch (ConversionKind) { 669 case StandardConversion: 670 OS << "Standard conversion: "; 671 Standard.dump(); 672 break; 673 case UserDefinedConversion: 674 OS << "User-defined conversion: "; 675 UserDefined.dump(); 676 break; 677 case EllipsisConversion: 678 OS << "Ellipsis conversion"; 679 break; 680 case AmbiguousConversion: 681 OS << "Ambiguous conversion"; 682 break; 683 case BadConversion: 684 OS << "Bad conversion"; 685 break; 686 } 687 688 OS << "\n"; 689 } 690 691 void AmbiguousConversionSequence::construct() { 692 new (&conversions()) ConversionSet(); 693 } 694 695 void AmbiguousConversionSequence::destruct() { 696 conversions().~ConversionSet(); 697 } 698 699 void 700 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 701 FromTypePtr = O.FromTypePtr; 702 ToTypePtr = O.ToTypePtr; 703 new (&conversions()) ConversionSet(O.conversions()); 704 } 705 706 namespace { 707 // Structure used by DeductionFailureInfo to store 708 // template argument information. 709 struct DFIArguments { 710 TemplateArgument FirstArg; 711 TemplateArgument SecondArg; 712 }; 713 // Structure used by DeductionFailureInfo to store 714 // template parameter and template argument information. 715 struct DFIParamWithArguments : DFIArguments { 716 TemplateParameter Param; 717 }; 718 // Structure used by DeductionFailureInfo to store template argument 719 // information and the index of the problematic call argument. 720 struct DFIDeducedMismatchArgs : DFIArguments { 721 TemplateArgumentList *TemplateArgs; 722 unsigned CallArgIndex; 723 }; 724 // Structure used by DeductionFailureInfo to store information about 725 // unsatisfied constraints. 726 struct CNSInfo { 727 TemplateArgumentList *TemplateArgs; 728 ConstraintSatisfaction Satisfaction; 729 }; 730 } 731 732 /// Convert from Sema's representation of template deduction information 733 /// to the form used in overload-candidate information. 734 DeductionFailureInfo 735 clang::MakeDeductionFailureInfo(ASTContext &Context, 736 TemplateDeductionResult TDK, 737 TemplateDeductionInfo &Info) { 738 DeductionFailureInfo Result; 739 Result.Result = static_cast<unsigned>(TDK); 740 Result.HasDiagnostic = false; 741 switch (TDK) { 742 case TemplateDeductionResult::Invalid: 743 case TemplateDeductionResult::InstantiationDepth: 744 case TemplateDeductionResult::TooManyArguments: 745 case TemplateDeductionResult::TooFewArguments: 746 case TemplateDeductionResult::MiscellaneousDeductionFailure: 747 case TemplateDeductionResult::CUDATargetMismatch: 748 Result.Data = nullptr; 749 break; 750 751 case TemplateDeductionResult::Incomplete: 752 case TemplateDeductionResult::InvalidExplicitArguments: 753 Result.Data = Info.Param.getOpaqueValue(); 754 break; 755 756 case TemplateDeductionResult::DeducedMismatch: 757 case TemplateDeductionResult::DeducedMismatchNested: { 758 // FIXME: Should allocate from normal heap so that we can free this later. 759 auto *Saved = new (Context) DFIDeducedMismatchArgs; 760 Saved->FirstArg = Info.FirstArg; 761 Saved->SecondArg = Info.SecondArg; 762 Saved->TemplateArgs = Info.takeSugared(); 763 Saved->CallArgIndex = Info.CallArgIndex; 764 Result.Data = Saved; 765 break; 766 } 767 768 case TemplateDeductionResult::NonDeducedMismatch: { 769 // FIXME: Should allocate from normal heap so that we can free this later. 770 DFIArguments *Saved = new (Context) DFIArguments; 771 Saved->FirstArg = Info.FirstArg; 772 Saved->SecondArg = Info.SecondArg; 773 Result.Data = Saved; 774 break; 775 } 776 777 case TemplateDeductionResult::IncompletePack: 778 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 779 case TemplateDeductionResult::Inconsistent: 780 case TemplateDeductionResult::Underqualified: { 781 // FIXME: Should allocate from normal heap so that we can free this later. 782 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 783 Saved->Param = Info.Param; 784 Saved->FirstArg = Info.FirstArg; 785 Saved->SecondArg = Info.SecondArg; 786 Result.Data = Saved; 787 break; 788 } 789 790 case TemplateDeductionResult::SubstitutionFailure: 791 Result.Data = Info.takeSugared(); 792 if (Info.hasSFINAEDiagnostic()) { 793 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 794 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 795 Info.takeSFINAEDiagnostic(*Diag); 796 Result.HasDiagnostic = true; 797 } 798 break; 799 800 case TemplateDeductionResult::ConstraintsNotSatisfied: { 801 CNSInfo *Saved = new (Context) CNSInfo; 802 Saved->TemplateArgs = Info.takeSugared(); 803 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 804 Result.Data = Saved; 805 break; 806 } 807 808 case TemplateDeductionResult::Success: 809 case TemplateDeductionResult::NonDependentConversionFailure: 810 case TemplateDeductionResult::AlreadyDiagnosed: 811 llvm_unreachable("not a deduction failure"); 812 } 813 814 return Result; 815 } 816 817 void DeductionFailureInfo::Destroy() { 818 switch (static_cast<TemplateDeductionResult>(Result)) { 819 case TemplateDeductionResult::Success: 820 case TemplateDeductionResult::Invalid: 821 case TemplateDeductionResult::InstantiationDepth: 822 case TemplateDeductionResult::Incomplete: 823 case TemplateDeductionResult::TooManyArguments: 824 case TemplateDeductionResult::TooFewArguments: 825 case TemplateDeductionResult::InvalidExplicitArguments: 826 case TemplateDeductionResult::CUDATargetMismatch: 827 case TemplateDeductionResult::NonDependentConversionFailure: 828 break; 829 830 case TemplateDeductionResult::IncompletePack: 831 case TemplateDeductionResult::Inconsistent: 832 case TemplateDeductionResult::Underqualified: 833 case TemplateDeductionResult::DeducedMismatch: 834 case TemplateDeductionResult::DeducedMismatchNested: 835 case TemplateDeductionResult::NonDeducedMismatch: 836 // FIXME: Destroy the data? 837 Data = nullptr; 838 break; 839 840 case TemplateDeductionResult::SubstitutionFailure: 841 // FIXME: Destroy the template argument list? 842 Data = nullptr; 843 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 844 Diag->~PartialDiagnosticAt(); 845 HasDiagnostic = false; 846 } 847 break; 848 849 case TemplateDeductionResult::ConstraintsNotSatisfied: 850 // FIXME: Destroy the template argument list? 851 Data = nullptr; 852 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 853 Diag->~PartialDiagnosticAt(); 854 HasDiagnostic = false; 855 } 856 break; 857 858 // Unhandled 859 case TemplateDeductionResult::MiscellaneousDeductionFailure: 860 case TemplateDeductionResult::AlreadyDiagnosed: 861 break; 862 } 863 } 864 865 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 866 if (HasDiagnostic) 867 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 868 return nullptr; 869 } 870 871 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 872 switch (static_cast<TemplateDeductionResult>(Result)) { 873 case TemplateDeductionResult::Success: 874 case TemplateDeductionResult::Invalid: 875 case TemplateDeductionResult::InstantiationDepth: 876 case TemplateDeductionResult::TooManyArguments: 877 case TemplateDeductionResult::TooFewArguments: 878 case TemplateDeductionResult::SubstitutionFailure: 879 case TemplateDeductionResult::DeducedMismatch: 880 case TemplateDeductionResult::DeducedMismatchNested: 881 case TemplateDeductionResult::NonDeducedMismatch: 882 case TemplateDeductionResult::CUDATargetMismatch: 883 case TemplateDeductionResult::NonDependentConversionFailure: 884 case TemplateDeductionResult::ConstraintsNotSatisfied: 885 return TemplateParameter(); 886 887 case TemplateDeductionResult::Incomplete: 888 case TemplateDeductionResult::InvalidExplicitArguments: 889 return TemplateParameter::getFromOpaqueValue(Data); 890 891 case TemplateDeductionResult::IncompletePack: 892 case TemplateDeductionResult::Inconsistent: 893 case TemplateDeductionResult::Underqualified: 894 return static_cast<DFIParamWithArguments*>(Data)->Param; 895 896 // Unhandled 897 case TemplateDeductionResult::MiscellaneousDeductionFailure: 898 case TemplateDeductionResult::AlreadyDiagnosed: 899 break; 900 } 901 902 return TemplateParameter(); 903 } 904 905 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 906 switch (static_cast<TemplateDeductionResult>(Result)) { 907 case TemplateDeductionResult::Success: 908 case TemplateDeductionResult::Invalid: 909 case TemplateDeductionResult::InstantiationDepth: 910 case TemplateDeductionResult::TooManyArguments: 911 case TemplateDeductionResult::TooFewArguments: 912 case TemplateDeductionResult::Incomplete: 913 case TemplateDeductionResult::IncompletePack: 914 case TemplateDeductionResult::InvalidExplicitArguments: 915 case TemplateDeductionResult::Inconsistent: 916 case TemplateDeductionResult::Underqualified: 917 case TemplateDeductionResult::NonDeducedMismatch: 918 case TemplateDeductionResult::CUDATargetMismatch: 919 case TemplateDeductionResult::NonDependentConversionFailure: 920 return nullptr; 921 922 case TemplateDeductionResult::DeducedMismatch: 923 case TemplateDeductionResult::DeducedMismatchNested: 924 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 925 926 case TemplateDeductionResult::SubstitutionFailure: 927 return static_cast<TemplateArgumentList*>(Data); 928 929 case TemplateDeductionResult::ConstraintsNotSatisfied: 930 return static_cast<CNSInfo*>(Data)->TemplateArgs; 931 932 // Unhandled 933 case TemplateDeductionResult::MiscellaneousDeductionFailure: 934 case TemplateDeductionResult::AlreadyDiagnosed: 935 break; 936 } 937 938 return nullptr; 939 } 940 941 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 942 switch (static_cast<TemplateDeductionResult>(Result)) { 943 case TemplateDeductionResult::Success: 944 case TemplateDeductionResult::Invalid: 945 case TemplateDeductionResult::InstantiationDepth: 946 case TemplateDeductionResult::Incomplete: 947 case TemplateDeductionResult::TooManyArguments: 948 case TemplateDeductionResult::TooFewArguments: 949 case TemplateDeductionResult::InvalidExplicitArguments: 950 case TemplateDeductionResult::SubstitutionFailure: 951 case TemplateDeductionResult::CUDATargetMismatch: 952 case TemplateDeductionResult::NonDependentConversionFailure: 953 case TemplateDeductionResult::ConstraintsNotSatisfied: 954 return nullptr; 955 956 case TemplateDeductionResult::IncompletePack: 957 case TemplateDeductionResult::Inconsistent: 958 case TemplateDeductionResult::Underqualified: 959 case TemplateDeductionResult::DeducedMismatch: 960 case TemplateDeductionResult::DeducedMismatchNested: 961 case TemplateDeductionResult::NonDeducedMismatch: 962 return &static_cast<DFIArguments*>(Data)->FirstArg; 963 964 // Unhandled 965 case TemplateDeductionResult::MiscellaneousDeductionFailure: 966 case TemplateDeductionResult::AlreadyDiagnosed: 967 break; 968 } 969 970 return nullptr; 971 } 972 973 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 974 switch (static_cast<TemplateDeductionResult>(Result)) { 975 case TemplateDeductionResult::Success: 976 case TemplateDeductionResult::Invalid: 977 case TemplateDeductionResult::InstantiationDepth: 978 case TemplateDeductionResult::Incomplete: 979 case TemplateDeductionResult::IncompletePack: 980 case TemplateDeductionResult::TooManyArguments: 981 case TemplateDeductionResult::TooFewArguments: 982 case TemplateDeductionResult::InvalidExplicitArguments: 983 case TemplateDeductionResult::SubstitutionFailure: 984 case TemplateDeductionResult::CUDATargetMismatch: 985 case TemplateDeductionResult::NonDependentConversionFailure: 986 case TemplateDeductionResult::ConstraintsNotSatisfied: 987 return nullptr; 988 989 case TemplateDeductionResult::Inconsistent: 990 case TemplateDeductionResult::Underqualified: 991 case TemplateDeductionResult::DeducedMismatch: 992 case TemplateDeductionResult::DeducedMismatchNested: 993 case TemplateDeductionResult::NonDeducedMismatch: 994 return &static_cast<DFIArguments*>(Data)->SecondArg; 995 996 // Unhandled 997 case TemplateDeductionResult::MiscellaneousDeductionFailure: 998 case TemplateDeductionResult::AlreadyDiagnosed: 999 break; 1000 } 1001 1002 return nullptr; 1003 } 1004 1005 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 1006 switch (static_cast<TemplateDeductionResult>(Result)) { 1007 case TemplateDeductionResult::DeducedMismatch: 1008 case TemplateDeductionResult::DeducedMismatchNested: 1009 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 1010 1011 default: 1012 return std::nullopt; 1013 } 1014 } 1015 1016 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, 1017 const FunctionDecl *Y) { 1018 if (!X || !Y) 1019 return false; 1020 if (X->getNumParams() != Y->getNumParams()) 1021 return false; 1022 // FIXME: when do rewritten comparison operators 1023 // with explicit object parameters correspond? 1024 // https://cplusplus.github.io/CWG/issues/2797.html 1025 for (unsigned I = 0; I < X->getNumParams(); ++I) 1026 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(), 1027 Y->getParamDecl(I)->getType())) 1028 return false; 1029 if (auto *FTX = X->getDescribedFunctionTemplate()) { 1030 auto *FTY = Y->getDescribedFunctionTemplate(); 1031 if (!FTY) 1032 return false; 1033 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(), 1034 FTY->getTemplateParameters())) 1035 return false; 1036 } 1037 return true; 1038 } 1039 1040 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, 1041 Expr *FirstOperand, FunctionDecl *EqFD) { 1042 assert(EqFD->getOverloadedOperator() == 1043 OverloadedOperatorKind::OO_EqualEqual); 1044 // C++2a [over.match.oper]p4: 1045 // A non-template function or function template F named operator== is a 1046 // rewrite target with first operand o unless a search for the name operator!= 1047 // in the scope S from the instantiation context of the operator expression 1048 // finds a function or function template that would correspond 1049 // ([basic.scope.scope]) to F if its name were operator==, where S is the 1050 // scope of the class type of o if F is a class member, and the namespace 1051 // scope of which F is a member otherwise. A function template specialization 1052 // named operator== is a rewrite target if its function template is a rewrite 1053 // target. 1054 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName( 1055 OverloadedOperatorKind::OO_ExclaimEqual); 1056 if (isa<CXXMethodDecl>(EqFD)) { 1057 // If F is a class member, search scope is class type of first operand. 1058 QualType RHS = FirstOperand->getType(); 1059 auto *RHSRec = RHS->getAs<RecordType>(); 1060 if (!RHSRec) 1061 return true; 1062 LookupResult Members(S, NotEqOp, OpLoc, 1063 Sema::LookupNameKind::LookupMemberName); 1064 S.LookupQualifiedName(Members, RHSRec->getDecl()); 1065 Members.suppressAccessDiagnostics(); 1066 for (NamedDecl *Op : Members) 1067 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction())) 1068 return false; 1069 return true; 1070 } 1071 // Otherwise the search scope is the namespace scope of which F is a member. 1072 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) { 1073 auto *NotEqFD = Op->getAsFunction(); 1074 if (auto *UD = dyn_cast<UsingShadowDecl>(Op)) 1075 NotEqFD = UD->getUnderlyingDecl()->getAsFunction(); 1076 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) && 1077 declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()), 1078 cast<Decl>(Op->getLexicalDeclContext()))) 1079 return false; 1080 } 1081 return true; 1082 } 1083 1084 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed( 1085 OverloadedOperatorKind Op) { 1086 if (!AllowRewrittenCandidates) 1087 return false; 1088 return Op == OO_EqualEqual || Op == OO_Spaceship; 1089 } 1090 1091 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 1092 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) { 1093 auto Op = FD->getOverloadedOperator(); 1094 if (!allowsReversed(Op)) 1095 return false; 1096 if (Op == OverloadedOperatorKind::OO_EqualEqual) { 1097 assert(OriginalArgs.size() == 2); 1098 if (!shouldAddReversedEqEq( 1099 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD)) 1100 return false; 1101 } 1102 // Don't bother adding a reversed candidate that can never be a better 1103 // match than the non-reversed version. 1104 return FD->getNumNonObjectParams() != 2 || 1105 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 1106 FD->getParamDecl(1)->getType()) || 1107 FD->hasAttr<EnableIfAttr>(); 1108 } 1109 1110 void OverloadCandidateSet::destroyCandidates() { 1111 for (iterator i = begin(), e = end(); i != e; ++i) { 1112 for (auto &C : i->Conversions) 1113 C.~ImplicitConversionSequence(); 1114 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 1115 i->DeductionFailure.Destroy(); 1116 } 1117 } 1118 1119 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 1120 destroyCandidates(); 1121 SlabAllocator.Reset(); 1122 NumInlineBytesUsed = 0; 1123 Candidates.clear(); 1124 Functions.clear(); 1125 Kind = CSK; 1126 } 1127 1128 namespace { 1129 class UnbridgedCastsSet { 1130 struct Entry { 1131 Expr **Addr; 1132 Expr *Saved; 1133 }; 1134 SmallVector<Entry, 2> Entries; 1135 1136 public: 1137 void save(Sema &S, Expr *&E) { 1138 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 1139 Entry entry = { &E, E }; 1140 Entries.push_back(entry); 1141 E = S.ObjC().stripARCUnbridgedCast(E); 1142 } 1143 1144 void restore() { 1145 for (SmallVectorImpl<Entry>::iterator 1146 i = Entries.begin(), e = Entries.end(); i != e; ++i) 1147 *i->Addr = i->Saved; 1148 } 1149 }; 1150 } 1151 1152 /// checkPlaceholderForOverload - Do any interesting placeholder-like 1153 /// preprocessing on the given expression. 1154 /// 1155 /// \param unbridgedCasts a collection to which to add unbridged casts; 1156 /// without this, they will be immediately diagnosed as errors 1157 /// 1158 /// Return true on unrecoverable error. 1159 static bool 1160 checkPlaceholderForOverload(Sema &S, Expr *&E, 1161 UnbridgedCastsSet *unbridgedCasts = nullptr) { 1162 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 1163 // We can't handle overloaded expressions here because overload 1164 // resolution might reasonably tweak them. 1165 if (placeholder->getKind() == BuiltinType::Overload) return false; 1166 1167 // If the context potentially accepts unbridged ARC casts, strip 1168 // the unbridged cast and add it to the collection for later restoration. 1169 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 1170 unbridgedCasts) { 1171 unbridgedCasts->save(S, E); 1172 return false; 1173 } 1174 1175 // Go ahead and check everything else. 1176 ExprResult result = S.CheckPlaceholderExpr(E); 1177 if (result.isInvalid()) 1178 return true; 1179 1180 E = result.get(); 1181 return false; 1182 } 1183 1184 // Nothing to do. 1185 return false; 1186 } 1187 1188 /// checkArgPlaceholdersForOverload - Check a set of call operands for 1189 /// placeholders. 1190 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, 1191 UnbridgedCastsSet &unbridged) { 1192 for (unsigned i = 0, e = Args.size(); i != e; ++i) 1193 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 1194 return true; 1195 1196 return false; 1197 } 1198 1199 Sema::OverloadKind 1200 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1201 NamedDecl *&Match, bool NewIsUsingDecl) { 1202 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1203 I != E; ++I) { 1204 NamedDecl *OldD = *I; 1205 1206 bool OldIsUsingDecl = false; 1207 if (isa<UsingShadowDecl>(OldD)) { 1208 OldIsUsingDecl = true; 1209 1210 // We can always introduce two using declarations into the same 1211 // context, even if they have identical signatures. 1212 if (NewIsUsingDecl) continue; 1213 1214 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1215 } 1216 1217 // A using-declaration does not conflict with another declaration 1218 // if one of them is hidden. 1219 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1220 continue; 1221 1222 // If either declaration was introduced by a using declaration, 1223 // we'll need to use slightly different rules for matching. 1224 // Essentially, these rules are the normal rules, except that 1225 // function templates hide function templates with different 1226 // return types or template parameter lists. 1227 bool UseMemberUsingDeclRules = 1228 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1229 !New->getFriendObjectKind(); 1230 1231 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1232 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1233 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1234 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1235 continue; 1236 } 1237 1238 if (!isa<FunctionTemplateDecl>(OldD) && 1239 !shouldLinkPossiblyHiddenDecl(*I, New)) 1240 continue; 1241 1242 Match = *I; 1243 return Ovl_Match; 1244 } 1245 1246 // Builtins that have custom typechecking or have a reference should 1247 // not be overloadable or redeclarable. 1248 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1249 Match = *I; 1250 return Ovl_NonFunction; 1251 } 1252 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1253 // We can overload with these, which can show up when doing 1254 // redeclaration checks for UsingDecls. 1255 assert(Old.getLookupKind() == LookupUsingDeclName); 1256 } else if (isa<TagDecl>(OldD)) { 1257 // We can always overload with tags by hiding them. 1258 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1259 // Optimistically assume that an unresolved using decl will 1260 // overload; if it doesn't, we'll have to diagnose during 1261 // template instantiation. 1262 // 1263 // Exception: if the scope is dependent and this is not a class 1264 // member, the using declaration can only introduce an enumerator. 1265 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1266 Match = *I; 1267 return Ovl_NonFunction; 1268 } 1269 } else { 1270 // (C++ 13p1): 1271 // Only function declarations can be overloaded; object and type 1272 // declarations cannot be overloaded. 1273 Match = *I; 1274 return Ovl_NonFunction; 1275 } 1276 } 1277 1278 // C++ [temp.friend]p1: 1279 // For a friend function declaration that is not a template declaration: 1280 // -- if the name of the friend is a qualified or unqualified template-id, 1281 // [...], otherwise 1282 // -- if the name of the friend is a qualified-id and a matching 1283 // non-template function is found in the specified class or namespace, 1284 // the friend declaration refers to that function, otherwise, 1285 // -- if the name of the friend is a qualified-id and a matching function 1286 // template is found in the specified class or namespace, the friend 1287 // declaration refers to the deduced specialization of that function 1288 // template, otherwise 1289 // -- the name shall be an unqualified-id [...] 1290 // If we get here for a qualified friend declaration, we've just reached the 1291 // third bullet. If the type of the friend is dependent, skip this lookup 1292 // until instantiation. 1293 if (New->getFriendObjectKind() && New->getQualifier() && 1294 !New->getDescribedFunctionTemplate() && 1295 !New->getDependentSpecializationInfo() && 1296 !New->getType()->isDependentType()) { 1297 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1298 TemplateSpecResult.addAllDecls(Old); 1299 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1300 /*QualifiedFriend*/true)) { 1301 New->setInvalidDecl(); 1302 return Ovl_Overload; 1303 } 1304 1305 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1306 return Ovl_Match; 1307 } 1308 1309 return Ovl_Overload; 1310 } 1311 1312 template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) { 1313 assert(D && "function decl should not be null"); 1314 if (auto *A = D->getAttr<AttrT>()) 1315 return !A->isImplicit(); 1316 return false; 1317 } 1318 1319 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, 1320 FunctionDecl *Old, 1321 bool UseMemberUsingDeclRules, 1322 bool ConsiderCudaAttrs, 1323 bool UseOverrideRules = false) { 1324 // C++ [basic.start.main]p2: This function shall not be overloaded. 1325 if (New->isMain()) 1326 return false; 1327 1328 // MSVCRT user defined entry points cannot be overloaded. 1329 if (New->isMSVCRTEntryPoint()) 1330 return false; 1331 1332 NamedDecl *OldDecl = Old; 1333 NamedDecl *NewDecl = New; 1334 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1335 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1336 1337 // C++ [temp.fct]p2: 1338 // A function template can be overloaded with other function templates 1339 // and with normal (non-template) functions. 1340 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1341 return true; 1342 1343 // Is the function New an overload of the function Old? 1344 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType()); 1345 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType()); 1346 1347 // Compare the signatures (C++ 1.3.10) of the two functions to 1348 // determine whether they are overloads. If we find any mismatch 1349 // in the signature, they are overloads. 1350 1351 // If either of these functions is a K&R-style function (no 1352 // prototype), then we consider them to have matching signatures. 1353 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1354 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1355 return false; 1356 1357 const auto *OldType = cast<FunctionProtoType>(OldQType); 1358 const auto *NewType = cast<FunctionProtoType>(NewQType); 1359 1360 // The signature of a function includes the types of its 1361 // parameters (C++ 1.3.10), which includes the presence or absence 1362 // of the ellipsis; see C++ DR 357). 1363 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic()) 1364 return true; 1365 1366 // For member-like friends, the enclosing class is part of the signature. 1367 if ((New->isMemberLikeConstrainedFriend() || 1368 Old->isMemberLikeConstrainedFriend()) && 1369 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext())) 1370 return true; 1371 1372 // Compare the parameter lists. 1373 // This can only be done once we have establish that friend functions 1374 // inhabit the same context, otherwise we might tried to instantiate 1375 // references to non-instantiated entities during constraint substitution. 1376 // GH78101. 1377 if (NewTemplate) { 1378 OldDecl = OldTemplate; 1379 NewDecl = NewTemplate; 1380 // C++ [temp.over.link]p4: 1381 // The signature of a function template consists of its function 1382 // signature, its return type and its template parameter list. The names 1383 // of the template parameters are significant only for establishing the 1384 // relationship between the template parameters and the rest of the 1385 // signature. 1386 // 1387 // We check the return type and template parameter lists for function 1388 // templates first; the remaining checks follow. 1389 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual( 1390 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate, 1391 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch); 1392 bool SameReturnType = SemaRef.Context.hasSameType( 1393 Old->getDeclaredReturnType(), New->getDeclaredReturnType()); 1394 // FIXME(GH58571): Match template parameter list even for non-constrained 1395 // template heads. This currently ensures that the code prior to C++20 is 1396 // not newly broken. 1397 bool ConstraintsInTemplateHead = 1398 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() || 1399 OldTemplate->getTemplateParameters()->hasAssociatedConstraints(); 1400 // C++ [namespace.udecl]p11: 1401 // The set of declarations named by a using-declarator that inhabits a 1402 // class C does not include member functions and member function 1403 // templates of a base class that "correspond" to (and thus would 1404 // conflict with) a declaration of a function or function template in 1405 // C. 1406 // Comparing return types is not required for the "correspond" check to 1407 // decide whether a member introduced by a shadow declaration is hidden. 1408 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead && 1409 !SameTemplateParameterList) 1410 return true; 1411 if (!UseMemberUsingDeclRules && 1412 (!SameTemplateParameterList || !SameReturnType)) 1413 return true; 1414 } 1415 1416 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1417 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New); 1418 1419 int OldParamsOffset = 0; 1420 int NewParamsOffset = 0; 1421 1422 // When determining if a method is an overload from a base class, act as if 1423 // the implicit object parameter are of the same type. 1424 1425 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) { 1426 if (M->isExplicitObjectMemberFunction()) { 1427 auto ThisType = M->getFunctionObjectParameterReferenceType(); 1428 if (ThisType.isConstQualified()) 1429 Q.removeConst(); 1430 return Q; 1431 } 1432 1433 // We do not allow overloading based off of '__restrict'. 1434 Q.removeRestrict(); 1435 1436 // We may not have applied the implicit const for a constexpr member 1437 // function yet (because we haven't yet resolved whether this is a static 1438 // or non-static member function). Add it now, on the assumption that this 1439 // is a redeclaration of OldMethod. 1440 if (!SemaRef.getLangOpts().CPlusPlus14 && 1441 (M->isConstexpr() || M->isConsteval()) && 1442 !isa<CXXConstructorDecl>(NewMethod)) 1443 Q.addConst(); 1444 return Q; 1445 }; 1446 1447 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) { 1448 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals); 1449 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals); 1450 1451 if (OldMethod->isExplicitObjectMemberFunction()) { 1452 BS.Quals.removeVolatile(); 1453 DS.Quals.removeVolatile(); 1454 } 1455 1456 return BS.Quals == DS.Quals; 1457 }; 1458 1459 auto CompareType = [&](QualType Base, QualType D) { 1460 auto BS = Base.getNonReferenceType().getCanonicalType().split(); 1461 auto DS = D.getNonReferenceType().getCanonicalType().split(); 1462 1463 if (!AreQualifiersEqual(BS, DS)) 1464 return false; 1465 1466 if (OldMethod->isImplicitObjectMemberFunction() && 1467 OldMethod->getParent() != NewMethod->getParent()) { 1468 QualType ParentType = 1469 SemaRef.Context.getTypeDeclType(OldMethod->getParent()) 1470 .getCanonicalType(); 1471 if (ParentType.getTypePtr() != BS.Ty) 1472 return false; 1473 BS.Ty = DS.Ty; 1474 } 1475 1476 // FIXME: should we ignore some type attributes here? 1477 if (BS.Ty != DS.Ty) 1478 return false; 1479 1480 if (Base->isLValueReferenceType()) 1481 return D->isLValueReferenceType(); 1482 return Base->isRValueReferenceType() == D->isRValueReferenceType(); 1483 }; 1484 1485 // If the function is a class member, its signature includes the 1486 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1487 auto DiagnoseInconsistentRefQualifiers = [&]() { 1488 if (SemaRef.LangOpts.CPlusPlus23) 1489 return false; 1490 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier()) 1491 return false; 1492 if (OldMethod->isExplicitObjectMemberFunction() || 1493 NewMethod->isExplicitObjectMemberFunction()) 1494 return false; 1495 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None || 1496 NewMethod->getRefQualifier() == RQ_None)) { 1497 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1498 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1499 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1500 return true; 1501 } 1502 return false; 1503 }; 1504 1505 if (OldMethod && OldMethod->isExplicitObjectMemberFunction()) 1506 OldParamsOffset++; 1507 if (NewMethod && NewMethod->isExplicitObjectMemberFunction()) 1508 NewParamsOffset++; 1509 1510 if (OldType->getNumParams() - OldParamsOffset != 1511 NewType->getNumParams() - NewParamsOffset || 1512 !SemaRef.FunctionParamTypesAreEqual( 1513 {OldType->param_type_begin() + OldParamsOffset, 1514 OldType->param_type_end()}, 1515 {NewType->param_type_begin() + NewParamsOffset, 1516 NewType->param_type_end()}, 1517 nullptr)) { 1518 return true; 1519 } 1520 1521 if (OldMethod && NewMethod && !OldMethod->isStatic() && 1522 !NewMethod->isStatic()) { 1523 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old, 1524 const CXXMethodDecl *New) { 1525 auto NewObjectType = New->getFunctionObjectParameterReferenceType(); 1526 auto OldObjectType = Old->getFunctionObjectParameterReferenceType(); 1527 1528 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) { 1529 return F->getRefQualifier() == RQ_None && 1530 !F->isExplicitObjectMemberFunction(); 1531 }; 1532 1533 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) && 1534 CompareType(OldObjectType.getNonReferenceType(), 1535 NewObjectType.getNonReferenceType())) 1536 return true; 1537 return CompareType(OldObjectType, NewObjectType); 1538 }(OldMethod, NewMethod); 1539 1540 if (!HaveCorrespondingObjectParameters) { 1541 if (DiagnoseInconsistentRefQualifiers()) 1542 return true; 1543 // CWG2554 1544 // and, if at least one is an explicit object member function, ignoring 1545 // object parameters 1546 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() && 1547 !OldMethod->isExplicitObjectMemberFunction())) 1548 return true; 1549 } 1550 } 1551 1552 if (!UseOverrideRules && 1553 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) { 1554 Expr *NewRC = New->getTrailingRequiresClause(), 1555 *OldRC = Old->getTrailingRequiresClause(); 1556 if ((NewRC != nullptr) != (OldRC != nullptr)) 1557 return true; 1558 if (NewRC && 1559 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC)) 1560 return true; 1561 } 1562 1563 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() && 1564 NewMethod->isImplicitObjectMemberFunction()) { 1565 if (DiagnoseInconsistentRefQualifiers()) 1566 return true; 1567 } 1568 1569 // Though pass_object_size is placed on parameters and takes an argument, we 1570 // consider it to be a function-level modifier for the sake of function 1571 // identity. Either the function has one or more parameters with 1572 // pass_object_size or it doesn't. 1573 if (functionHasPassObjectSizeParams(New) != 1574 functionHasPassObjectSizeParams(Old)) 1575 return true; 1576 1577 // enable_if attributes are an order-sensitive part of the signature. 1578 for (specific_attr_iterator<EnableIfAttr> 1579 NewI = New->specific_attr_begin<EnableIfAttr>(), 1580 NewE = New->specific_attr_end<EnableIfAttr>(), 1581 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1582 OldE = Old->specific_attr_end<EnableIfAttr>(); 1583 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1584 if (NewI == NewE || OldI == OldE) 1585 return true; 1586 llvm::FoldingSetNodeID NewID, OldID; 1587 NewI->getCond()->Profile(NewID, SemaRef.Context, true); 1588 OldI->getCond()->Profile(OldID, SemaRef.Context, true); 1589 if (NewID != OldID) 1590 return true; 1591 } 1592 1593 // At this point, it is known that the two functions have the same signature. 1594 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) { 1595 // Don't allow overloading of destructors. (In theory we could, but it 1596 // would be a giant change to clang.) 1597 if (!isa<CXXDestructorDecl>(New)) { 1598 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New), 1599 OldTarget = SemaRef.CUDA().IdentifyTarget(Old); 1600 if (NewTarget != CUDAFunctionTarget::InvalidTarget) { 1601 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) && 1602 "Unexpected invalid target."); 1603 1604 // Allow overloading of functions with same signature and different CUDA 1605 // target attributes. 1606 if (NewTarget != OldTarget) { 1607 // Special case: non-constexpr function is allowed to override 1608 // constexpr virtual function 1609 if (OldMethod && NewMethod && OldMethod->isVirtual() && 1610 OldMethod->isConstexpr() && !NewMethod->isConstexpr() && 1611 !hasExplicitAttr<CUDAHostAttr>(Old) && 1612 !hasExplicitAttr<CUDADeviceAttr>(Old) && 1613 !hasExplicitAttr<CUDAHostAttr>(New) && 1614 !hasExplicitAttr<CUDADeviceAttr>(New)) { 1615 return false; 1616 } 1617 return true; 1618 } 1619 } 1620 } 1621 } 1622 1623 // The signatures match; this is not an overload. 1624 return false; 1625 } 1626 1627 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1628 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1629 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules, 1630 ConsiderCudaAttrs); 1631 } 1632 1633 bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, 1634 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1635 return IsOverloadOrOverrideImpl(*this, MD, BaseMD, 1636 /*UseMemberUsingDeclRules=*/false, 1637 /*ConsiderCudaAttrs=*/true, 1638 /*UseOverrideRules=*/true); 1639 } 1640 1641 /// Tries a user-defined conversion from From to ToType. 1642 /// 1643 /// Produces an implicit conversion sequence for when a standard conversion 1644 /// is not an option. See TryImplicitConversion for more information. 1645 static ImplicitConversionSequence 1646 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1647 bool SuppressUserConversions, 1648 AllowedExplicit AllowExplicit, 1649 bool InOverloadResolution, 1650 bool CStyle, 1651 bool AllowObjCWritebackConversion, 1652 bool AllowObjCConversionOnExplicit) { 1653 ImplicitConversionSequence ICS; 1654 1655 if (SuppressUserConversions) { 1656 // We're not in the case above, so there is no conversion that 1657 // we can perform. 1658 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1659 return ICS; 1660 } 1661 1662 // Attempt user-defined conversion. 1663 OverloadCandidateSet Conversions(From->getExprLoc(), 1664 OverloadCandidateSet::CSK_Normal); 1665 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1666 Conversions, AllowExplicit, 1667 AllowObjCConversionOnExplicit)) { 1668 case OR_Success: 1669 case OR_Deleted: 1670 ICS.setUserDefined(); 1671 // C++ [over.ics.user]p4: 1672 // A conversion of an expression of class type to the same class 1673 // type is given Exact Match rank, and a conversion of an 1674 // expression of class type to a base class of that type is 1675 // given Conversion rank, in spite of the fact that a copy 1676 // constructor (i.e., a user-defined conversion function) is 1677 // called for those cases. 1678 if (CXXConstructorDecl *Constructor 1679 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1680 QualType FromType; 1681 SourceLocation FromLoc; 1682 // C++11 [over.ics.list]p6, per DR2137: 1683 // C++17 [over.ics.list]p6: 1684 // If C is not an initializer-list constructor and the initializer list 1685 // has a single element of type cv U, where U is X or a class derived 1686 // from X, the implicit conversion sequence has Exact Match rank if U is 1687 // X, or Conversion rank if U is derived from X. 1688 if (const auto *InitList = dyn_cast<InitListExpr>(From); 1689 InitList && InitList->getNumInits() == 1 && 1690 !S.isInitListConstructor(Constructor)) { 1691 const Expr *SingleInit = InitList->getInit(0); 1692 FromType = SingleInit->getType(); 1693 FromLoc = SingleInit->getBeginLoc(); 1694 } else { 1695 FromType = From->getType(); 1696 FromLoc = From->getBeginLoc(); 1697 } 1698 QualType FromCanon = 1699 S.Context.getCanonicalType(FromType.getUnqualifiedType()); 1700 QualType ToCanon 1701 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1702 if ((FromCanon == ToCanon || 1703 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) { 1704 // Turn this into a "standard" conversion sequence, so that it 1705 // gets ranked with standard conversion sequences. 1706 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1707 ICS.setStandard(); 1708 ICS.Standard.setAsIdentityConversion(); 1709 ICS.Standard.setFromType(FromType); 1710 ICS.Standard.setAllToTypes(ToType); 1711 ICS.Standard.CopyConstructor = Constructor; 1712 ICS.Standard.FoundCopyConstructor = Found; 1713 if (ToCanon != FromCanon) 1714 ICS.Standard.Second = ICK_Derived_To_Base; 1715 } 1716 } 1717 break; 1718 1719 case OR_Ambiguous: 1720 ICS.setAmbiguous(); 1721 ICS.Ambiguous.setFromType(From->getType()); 1722 ICS.Ambiguous.setToType(ToType); 1723 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1724 Cand != Conversions.end(); ++Cand) 1725 if (Cand->Best) 1726 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1727 break; 1728 1729 // Fall through. 1730 case OR_No_Viable_Function: 1731 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1732 break; 1733 } 1734 1735 return ICS; 1736 } 1737 1738 /// TryImplicitConversion - Attempt to perform an implicit conversion 1739 /// from the given expression (Expr) to the given type (ToType). This 1740 /// function returns an implicit conversion sequence that can be used 1741 /// to perform the initialization. Given 1742 /// 1743 /// void f(float f); 1744 /// void g(int i) { f(i); } 1745 /// 1746 /// this routine would produce an implicit conversion sequence to 1747 /// describe the initialization of f from i, which will be a standard 1748 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1749 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1750 // 1751 /// Note that this routine only determines how the conversion can be 1752 /// performed; it does not actually perform the conversion. As such, 1753 /// it will not produce any diagnostics if no conversion is available, 1754 /// but will instead return an implicit conversion sequence of kind 1755 /// "BadConversion". 1756 /// 1757 /// If @p SuppressUserConversions, then user-defined conversions are 1758 /// not permitted. 1759 /// If @p AllowExplicit, then explicit user-defined conversions are 1760 /// permitted. 1761 /// 1762 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1763 /// writeback conversion, which allows __autoreleasing id* parameters to 1764 /// be initialized with __strong id* or __weak id* arguments. 1765 static ImplicitConversionSequence 1766 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1767 bool SuppressUserConversions, 1768 AllowedExplicit AllowExplicit, 1769 bool InOverloadResolution, 1770 bool CStyle, 1771 bool AllowObjCWritebackConversion, 1772 bool AllowObjCConversionOnExplicit) { 1773 ImplicitConversionSequence ICS; 1774 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1775 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1776 ICS.setStandard(); 1777 return ICS; 1778 } 1779 1780 if (!S.getLangOpts().CPlusPlus) { 1781 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1782 return ICS; 1783 } 1784 1785 // C++ [over.ics.user]p4: 1786 // A conversion of an expression of class type to the same class 1787 // type is given Exact Match rank, and a conversion of an 1788 // expression of class type to a base class of that type is 1789 // given Conversion rank, in spite of the fact that a copy/move 1790 // constructor (i.e., a user-defined conversion function) is 1791 // called for those cases. 1792 QualType FromType = From->getType(); 1793 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1794 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1795 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1796 ICS.setStandard(); 1797 ICS.Standard.setAsIdentityConversion(); 1798 ICS.Standard.setFromType(FromType); 1799 ICS.Standard.setAllToTypes(ToType); 1800 1801 // We don't actually check at this point whether there is a valid 1802 // copy/move constructor, since overloading just assumes that it 1803 // exists. When we actually perform initialization, we'll find the 1804 // appropriate constructor to copy the returned object, if needed. 1805 ICS.Standard.CopyConstructor = nullptr; 1806 1807 // Determine whether this is considered a derived-to-base conversion. 1808 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1809 ICS.Standard.Second = ICK_Derived_To_Base; 1810 1811 return ICS; 1812 } 1813 1814 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() && 1815 FromType->isHLSLAttributedResourceType()) { 1816 auto *ToResType = cast<HLSLAttributedResourceType>(ToType); 1817 auto *FromResType = cast<HLSLAttributedResourceType>(FromType); 1818 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(), 1819 FromResType->getWrappedType()) && 1820 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(), 1821 FromResType->getContainedType()) && 1822 ToResType->getAttrs() == FromResType->getAttrs()) { 1823 ICS.setStandard(); 1824 ICS.Standard.setAsIdentityConversion(); 1825 ICS.Standard.setFromType(FromType); 1826 ICS.Standard.setAllToTypes(ToType); 1827 return ICS; 1828 } 1829 } 1830 1831 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1832 AllowExplicit, InOverloadResolution, CStyle, 1833 AllowObjCWritebackConversion, 1834 AllowObjCConversionOnExplicit); 1835 } 1836 1837 ImplicitConversionSequence 1838 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1839 bool SuppressUserConversions, 1840 AllowedExplicit AllowExplicit, 1841 bool InOverloadResolution, 1842 bool CStyle, 1843 bool AllowObjCWritebackConversion) { 1844 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1845 AllowExplicit, InOverloadResolution, CStyle, 1846 AllowObjCWritebackConversion, 1847 /*AllowObjCConversionOnExplicit=*/false); 1848 } 1849 1850 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1851 AssignmentAction Action, 1852 bool AllowExplicit) { 1853 if (checkPlaceholderForOverload(*this, From)) 1854 return ExprError(); 1855 1856 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1857 bool AllowObjCWritebackConversion = 1858 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing || 1859 Action == AssignmentAction::Sending); 1860 if (getLangOpts().ObjC) 1861 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1862 From->getType(), From); 1863 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1864 *this, From, ToType, 1865 /*SuppressUserConversions=*/false, 1866 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1867 /*InOverloadResolution=*/false, 1868 /*CStyle=*/false, AllowObjCWritebackConversion, 1869 /*AllowObjCConversionOnExplicit=*/false); 1870 return PerformImplicitConversion(From, ToType, ICS, Action); 1871 } 1872 1873 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1874 QualType &ResultTy) { 1875 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1876 return false; 1877 1878 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1879 // or F(t noexcept) -> F(t) 1880 // where F adds one of the following at most once: 1881 // - a pointer 1882 // - a member pointer 1883 // - a block pointer 1884 // Changes here need matching changes in FindCompositePointerType. 1885 CanQualType CanTo = Context.getCanonicalType(ToType); 1886 CanQualType CanFrom = Context.getCanonicalType(FromType); 1887 Type::TypeClass TyClass = CanTo->getTypeClass(); 1888 if (TyClass != CanFrom->getTypeClass()) return false; 1889 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1890 if (TyClass == Type::Pointer) { 1891 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1892 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1893 } else if (TyClass == Type::BlockPointer) { 1894 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1895 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1896 } else if (TyClass == Type::MemberPointer) { 1897 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1898 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1899 // A function pointer conversion cannot change the class of the function. 1900 if (ToMPT->getClass() != FromMPT->getClass()) 1901 return false; 1902 CanTo = ToMPT->getPointeeType(); 1903 CanFrom = FromMPT->getPointeeType(); 1904 } else { 1905 return false; 1906 } 1907 1908 TyClass = CanTo->getTypeClass(); 1909 if (TyClass != CanFrom->getTypeClass()) return false; 1910 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1911 return false; 1912 } 1913 1914 const auto *FromFn = cast<FunctionType>(CanFrom); 1915 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1916 1917 const auto *ToFn = cast<FunctionType>(CanTo); 1918 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1919 1920 bool Changed = false; 1921 1922 // Drop 'noreturn' if not present in target type. 1923 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1924 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1925 Changed = true; 1926 } 1927 1928 // Drop 'noexcept' if not present in target type. 1929 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1930 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1931 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1932 FromFn = cast<FunctionType>( 1933 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1934 EST_None) 1935 .getTypePtr()); 1936 Changed = true; 1937 } 1938 1939 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1940 // only if the ExtParameterInfo lists of the two function prototypes can be 1941 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1942 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1943 bool CanUseToFPT, CanUseFromFPT; 1944 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1945 CanUseFromFPT, NewParamInfos) && 1946 CanUseToFPT && !CanUseFromFPT) { 1947 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1948 ExtInfo.ExtParameterInfos = 1949 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1950 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1951 FromFPT->getParamTypes(), ExtInfo); 1952 FromFn = QT->getAs<FunctionType>(); 1953 Changed = true; 1954 } 1955 1956 // For C, when called from checkPointerTypesForAssignment, 1957 // we need to not alter FromFn, or else even an innocuous cast 1958 // like dropping effects will fail. In C++ however we do want to 1959 // alter FromFn (because of the way PerformImplicitConversion works). 1960 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) { 1961 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above 1962 1963 // Transparently add/drop effects; here we are concerned with 1964 // language rules/canonicalization. Adding/dropping effects is a warning. 1965 const auto FromFX = FromFPT->getFunctionEffects(); 1966 const auto ToFX = ToFPT->getFunctionEffects(); 1967 if (FromFX != ToFX) { 1968 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1969 ExtInfo.FunctionEffects = ToFX; 1970 QualType QT = Context.getFunctionType( 1971 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo); 1972 FromFn = QT->getAs<FunctionType>(); 1973 Changed = true; 1974 } 1975 } 1976 } 1977 1978 if (!Changed) 1979 return false; 1980 1981 assert(QualType(FromFn, 0).isCanonical()); 1982 if (QualType(FromFn, 0) != CanTo) return false; 1983 1984 ResultTy = ToType; 1985 return true; 1986 } 1987 1988 /// Determine whether the conversion from FromType to ToType is a valid 1989 /// floating point conversion. 1990 /// 1991 static bool IsFloatingPointConversion(Sema &S, QualType FromType, 1992 QualType ToType) { 1993 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType()) 1994 return false; 1995 // FIXME: disable conversions between long double, __ibm128 and __float128 1996 // if their representation is different until there is back end support 1997 // We of course allow this conversion if long double is really double. 1998 1999 // Conversions between bfloat16 and float16 are currently not supported. 2000 if ((FromType->isBFloat16Type() && 2001 (ToType->isFloat16Type() || ToType->isHalfType())) || 2002 (ToType->isBFloat16Type() && 2003 (FromType->isFloat16Type() || FromType->isHalfType()))) 2004 return false; 2005 2006 // Conversions between IEEE-quad and IBM-extended semantics are not 2007 // permitted. 2008 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType); 2009 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 2010 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 2011 &ToSem == &llvm::APFloat::IEEEquad()) || 2012 (&FromSem == &llvm::APFloat::IEEEquad() && 2013 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 2014 return false; 2015 return true; 2016 } 2017 2018 static bool IsVectorElementConversion(Sema &S, QualType FromType, 2019 QualType ToType, 2020 ImplicitConversionKind &ICK, Expr *From) { 2021 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 2022 return true; 2023 2024 if (S.IsFloatingPointPromotion(FromType, ToType)) { 2025 ICK = ICK_Floating_Promotion; 2026 return true; 2027 } 2028 2029 if (IsFloatingPointConversion(S, FromType, ToType)) { 2030 ICK = ICK_Floating_Conversion; 2031 return true; 2032 } 2033 2034 if (ToType->isBooleanType() && FromType->isArithmeticType()) { 2035 ICK = ICK_Boolean_Conversion; 2036 return true; 2037 } 2038 2039 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) || 2040 (FromType->isIntegralOrUnscopedEnumerationType() && 2041 ToType->isRealFloatingType())) { 2042 ICK = ICK_Floating_Integral; 2043 return true; 2044 } 2045 2046 if (S.IsIntegralPromotion(From, FromType, ToType)) { 2047 ICK = ICK_Integral_Promotion; 2048 return true; 2049 } 2050 2051 if (FromType->isIntegralOrUnscopedEnumerationType() && 2052 ToType->isIntegralType(S.Context)) { 2053 ICK = ICK_Integral_Conversion; 2054 return true; 2055 } 2056 2057 return false; 2058 } 2059 2060 /// Determine whether the conversion from FromType to ToType is a valid 2061 /// vector conversion. 2062 /// 2063 /// \param ICK Will be set to the vector conversion kind, if this is a vector 2064 /// conversion. 2065 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, 2066 ImplicitConversionKind &ICK, 2067 ImplicitConversionKind &ElConv, Expr *From, 2068 bool InOverloadResolution, bool CStyle) { 2069 // We need at least one of these types to be a vector type to have a vector 2070 // conversion. 2071 if (!ToType->isVectorType() && !FromType->isVectorType()) 2072 return false; 2073 2074 // Identical types require no conversions. 2075 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 2076 return false; 2077 2078 // HLSL allows implicit truncation of vector types. 2079 if (S.getLangOpts().HLSL) { 2080 auto *ToExtType = ToType->getAs<ExtVectorType>(); 2081 auto *FromExtType = FromType->getAs<ExtVectorType>(); 2082 2083 // If both arguments are vectors, handle possible vector truncation and 2084 // element conversion. 2085 if (ToExtType && FromExtType) { 2086 unsigned FromElts = FromExtType->getNumElements(); 2087 unsigned ToElts = ToExtType->getNumElements(); 2088 if (FromElts < ToElts) 2089 return false; 2090 if (FromElts == ToElts) 2091 ElConv = ICK_Identity; 2092 else 2093 ElConv = ICK_HLSL_Vector_Truncation; 2094 2095 QualType FromElTy = FromExtType->getElementType(); 2096 QualType ToElTy = ToExtType->getElementType(); 2097 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy)) 2098 return true; 2099 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From); 2100 } 2101 if (FromExtType && !ToExtType) { 2102 ElConv = ICK_HLSL_Vector_Truncation; 2103 QualType FromElTy = FromExtType->getElementType(); 2104 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType)) 2105 return true; 2106 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From); 2107 } 2108 // Fallthrough for the case where ToType is a vector and FromType is not. 2109 } 2110 2111 // There are no conversions between extended vector types, only identity. 2112 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) { 2113 if (FromType->getAs<ExtVectorType>()) { 2114 // There are no conversions between extended vector types other than the 2115 // identity conversion. 2116 return false; 2117 } 2118 2119 // Vector splat from any arithmetic type to a vector. 2120 if (FromType->isArithmeticType()) { 2121 if (S.getLangOpts().HLSL) { 2122 ElConv = ICK_HLSL_Vector_Splat; 2123 QualType ToElTy = ToExtType->getElementType(); 2124 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From); 2125 } 2126 ICK = ICK_Vector_Splat; 2127 return true; 2128 } 2129 } 2130 2131 if (ToType->isSVESizelessBuiltinType() || 2132 FromType->isSVESizelessBuiltinType()) 2133 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 2134 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 2135 ICK = ICK_SVE_Vector_Conversion; 2136 return true; 2137 } 2138 2139 if (ToType->isRVVSizelessBuiltinType() || 2140 FromType->isRVVSizelessBuiltinType()) 2141 if (S.Context.areCompatibleRVVTypes(FromType, ToType) || 2142 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) { 2143 ICK = ICK_RVV_Vector_Conversion; 2144 return true; 2145 } 2146 2147 // We can perform the conversion between vector types in the following cases: 2148 // 1)vector types are equivalent AltiVec and GCC vector types 2149 // 2)lax vector conversions are permitted and the vector types are of the 2150 // same size 2151 // 3)the destination type does not have the ARM MVE strict-polymorphism 2152 // attribute, which inhibits lax vector conversion for overload resolution 2153 // only 2154 if (ToType->isVectorType() && FromType->isVectorType()) { 2155 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 2156 (S.isLaxVectorConversion(FromType, ToType) && 2157 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 2158 if (S.getASTContext().getTargetInfo().getTriple().isPPC() && 2159 S.isLaxVectorConversion(FromType, ToType) && 2160 S.anyAltivecTypes(FromType, ToType) && 2161 !S.Context.areCompatibleVectorTypes(FromType, ToType) && 2162 !InOverloadResolution && !CStyle) { 2163 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) 2164 << FromType << ToType; 2165 } 2166 ICK = ICK_Vector_Conversion; 2167 return true; 2168 } 2169 } 2170 2171 return false; 2172 } 2173 2174 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2175 bool InOverloadResolution, 2176 StandardConversionSequence &SCS, 2177 bool CStyle); 2178 2179 /// IsStandardConversion - Determines whether there is a standard 2180 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 2181 /// expression From to the type ToType. Standard conversion sequences 2182 /// only consider non-class types; for conversions that involve class 2183 /// types, use TryImplicitConversion. If a conversion exists, SCS will 2184 /// contain the standard conversion sequence required to perform this 2185 /// conversion and this routine will return true. Otherwise, this 2186 /// routine will return false and the value of SCS is unspecified. 2187 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 2188 bool InOverloadResolution, 2189 StandardConversionSequence &SCS, 2190 bool CStyle, 2191 bool AllowObjCWritebackConversion) { 2192 QualType FromType = From->getType(); 2193 2194 // Standard conversions (C++ [conv]) 2195 SCS.setAsIdentityConversion(); 2196 SCS.IncompatibleObjC = false; 2197 SCS.setFromType(FromType); 2198 SCS.CopyConstructor = nullptr; 2199 2200 // There are no standard conversions for class types in C++, so 2201 // abort early. When overloading in C, however, we do permit them. 2202 if (S.getLangOpts().CPlusPlus && 2203 (FromType->isRecordType() || ToType->isRecordType())) 2204 return false; 2205 2206 // The first conversion can be an lvalue-to-rvalue conversion, 2207 // array-to-pointer conversion, or function-to-pointer conversion 2208 // (C++ 4p1). 2209 2210 if (FromType == S.Context.OverloadTy) { 2211 DeclAccessPair AccessPair; 2212 if (FunctionDecl *Fn 2213 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 2214 AccessPair)) { 2215 // We were able to resolve the address of the overloaded function, 2216 // so we can convert to the type of that function. 2217 FromType = Fn->getType(); 2218 SCS.setFromType(FromType); 2219 2220 // we can sometimes resolve &foo<int> regardless of ToType, so check 2221 // if the type matches (identity) or we are converting to bool 2222 if (!S.Context.hasSameUnqualifiedType( 2223 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 2224 QualType resultTy; 2225 // if the function type matches except for [[noreturn]], it's ok 2226 if (!S.IsFunctionConversion(FromType, 2227 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 2228 // otherwise, only a boolean conversion is standard 2229 if (!ToType->isBooleanType()) 2230 return false; 2231 } 2232 2233 // Check if the "from" expression is taking the address of an overloaded 2234 // function and recompute the FromType accordingly. Take advantage of the 2235 // fact that non-static member functions *must* have such an address-of 2236 // expression. 2237 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 2238 if (Method && !Method->isStatic() && 2239 !Method->isExplicitObjectMemberFunction()) { 2240 assert(isa<UnaryOperator>(From->IgnoreParens()) && 2241 "Non-unary operator on non-static member address"); 2242 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 2243 == UO_AddrOf && 2244 "Non-address-of operator on non-static member address"); 2245 const Type *ClassType 2246 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 2247 FromType = S.Context.getMemberPointerType(FromType, ClassType); 2248 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 2249 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 2250 UO_AddrOf && 2251 "Non-address-of operator for overloaded function expression"); 2252 FromType = S.Context.getPointerType(FromType); 2253 } 2254 } else { 2255 return false; 2256 } 2257 } 2258 2259 bool argIsLValue = From->isGLValue(); 2260 // To handle conversion from ArrayParameterType to ConstantArrayType 2261 // this block must be above the one below because Array parameters 2262 // do not decay and when handling HLSLOutArgExprs and 2263 // the From expression is an LValue. 2264 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() && 2265 ToType->isConstantArrayType()) { 2266 // HLSL constant array parameters do not decay, so if the argument is a 2267 // constant array and the parameter is an ArrayParameterType we have special 2268 // handling here. 2269 if (ToType->isArrayParameterType()) { 2270 FromType = S.Context.getArrayParameterType(FromType); 2271 SCS.First = ICK_HLSL_Array_RValue; 2272 } else if (FromType->isArrayParameterType()) { 2273 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType); 2274 FromType = APT->getConstantArrayType(S.Context); 2275 SCS.First = ICK_HLSL_Array_RValue; 2276 } else { 2277 SCS.First = ICK_Identity; 2278 } 2279 2280 if (S.Context.getCanonicalType(FromType) != 2281 S.Context.getCanonicalType(ToType)) 2282 return false; 2283 2284 SCS.setAllToTypes(ToType); 2285 return true; 2286 } else if (argIsLValue && !FromType->canDecayToPointerType() && 2287 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 2288 // Lvalue-to-rvalue conversion (C++11 4.1): 2289 // A glvalue (3.10) of a non-function, non-array type T can 2290 // be converted to a prvalue. 2291 2292 SCS.First = ICK_Lvalue_To_Rvalue; 2293 2294 // C11 6.3.2.1p2: 2295 // ... if the lvalue has atomic type, the value has the non-atomic version 2296 // of the type of the lvalue ... 2297 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 2298 FromType = Atomic->getValueType(); 2299 2300 // If T is a non-class type, the type of the rvalue is the 2301 // cv-unqualified version of T. Otherwise, the type of the rvalue 2302 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 2303 // just strip the qualifiers because they don't matter. 2304 FromType = FromType.getUnqualifiedType(); 2305 } else if (FromType->isArrayType()) { 2306 // Array-to-pointer conversion (C++ 4.2) 2307 SCS.First = ICK_Array_To_Pointer; 2308 2309 // An lvalue or rvalue of type "array of N T" or "array of unknown 2310 // bound of T" can be converted to an rvalue of type "pointer to 2311 // T" (C++ 4.2p1). 2312 FromType = S.Context.getArrayDecayedType(FromType); 2313 2314 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 2315 // This conversion is deprecated in C++03 (D.4) 2316 SCS.DeprecatedStringLiteralToCharPtr = true; 2317 2318 // For the purpose of ranking in overload resolution 2319 // (13.3.3.1.1), this conversion is considered an 2320 // array-to-pointer conversion followed by a qualification 2321 // conversion (4.4). (C++ 4.2p2) 2322 SCS.Second = ICK_Identity; 2323 SCS.Third = ICK_Qualification; 2324 SCS.QualificationIncludesObjCLifetime = false; 2325 SCS.setAllToTypes(FromType); 2326 return true; 2327 } 2328 } else if (FromType->isFunctionType() && argIsLValue) { 2329 // Function-to-pointer conversion (C++ 4.3). 2330 SCS.First = ICK_Function_To_Pointer; 2331 2332 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 2333 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 2334 if (!S.checkAddressOfFunctionIsAvailable(FD)) 2335 return false; 2336 2337 // An lvalue of function type T can be converted to an rvalue of 2338 // type "pointer to T." The result is a pointer to the 2339 // function. (C++ 4.3p1). 2340 FromType = S.Context.getPointerType(FromType); 2341 } else { 2342 // We don't require any conversions for the first step. 2343 SCS.First = ICK_Identity; 2344 } 2345 SCS.setToType(0, FromType); 2346 2347 // The second conversion can be an integral promotion, floating 2348 // point promotion, integral conversion, floating point conversion, 2349 // floating-integral conversion, pointer conversion, 2350 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 2351 // For overloading in C, this can also be a "compatible-type" 2352 // conversion. 2353 bool IncompatibleObjC = false; 2354 ImplicitConversionKind SecondICK = ICK_Identity; 2355 ImplicitConversionKind DimensionICK = ICK_Identity; 2356 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 2357 // The unqualified versions of the types are the same: there's no 2358 // conversion to do. 2359 SCS.Second = ICK_Identity; 2360 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 2361 // Integral promotion (C++ 4.5). 2362 SCS.Second = ICK_Integral_Promotion; 2363 FromType = ToType.getUnqualifiedType(); 2364 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 2365 // Floating point promotion (C++ 4.6). 2366 SCS.Second = ICK_Floating_Promotion; 2367 FromType = ToType.getUnqualifiedType(); 2368 } else if (S.IsComplexPromotion(FromType, ToType)) { 2369 // Complex promotion (Clang extension) 2370 SCS.Second = ICK_Complex_Promotion; 2371 FromType = ToType.getUnqualifiedType(); 2372 } else if (ToType->isBooleanType() && 2373 (FromType->isArithmeticType() || 2374 FromType->isAnyPointerType() || 2375 FromType->isBlockPointerType() || 2376 FromType->isMemberPointerType())) { 2377 // Boolean conversions (C++ 4.12). 2378 SCS.Second = ICK_Boolean_Conversion; 2379 FromType = S.Context.BoolTy; 2380 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 2381 ToType->isIntegralType(S.Context)) { 2382 // Integral conversions (C++ 4.7). 2383 SCS.Second = ICK_Integral_Conversion; 2384 FromType = ToType.getUnqualifiedType(); 2385 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 2386 // Complex conversions (C99 6.3.1.6) 2387 SCS.Second = ICK_Complex_Conversion; 2388 FromType = ToType.getUnqualifiedType(); 2389 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 2390 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 2391 // Complex-real conversions (C99 6.3.1.7) 2392 SCS.Second = ICK_Complex_Real; 2393 FromType = ToType.getUnqualifiedType(); 2394 } else if (IsFloatingPointConversion(S, FromType, ToType)) { 2395 // Floating point conversions (C++ 4.8). 2396 SCS.Second = ICK_Floating_Conversion; 2397 FromType = ToType.getUnqualifiedType(); 2398 } else if ((FromType->isRealFloatingType() && 2399 ToType->isIntegralType(S.Context)) || 2400 (FromType->isIntegralOrUnscopedEnumerationType() && 2401 ToType->isRealFloatingType())) { 2402 2403 // Floating-integral conversions (C++ 4.9). 2404 SCS.Second = ICK_Floating_Integral; 2405 FromType = ToType.getUnqualifiedType(); 2406 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 2407 SCS.Second = ICK_Block_Pointer_Conversion; 2408 } else if (AllowObjCWritebackConversion && 2409 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) { 2410 SCS.Second = ICK_Writeback_Conversion; 2411 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 2412 FromType, IncompatibleObjC)) { 2413 // Pointer conversions (C++ 4.10). 2414 SCS.Second = ICK_Pointer_Conversion; 2415 SCS.IncompatibleObjC = IncompatibleObjC; 2416 FromType = FromType.getUnqualifiedType(); 2417 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 2418 InOverloadResolution, FromType)) { 2419 // Pointer to member conversions (4.11). 2420 SCS.Second = ICK_Pointer_Member; 2421 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK, 2422 From, InOverloadResolution, CStyle)) { 2423 SCS.Second = SecondICK; 2424 SCS.Dimension = DimensionICK; 2425 FromType = ToType.getUnqualifiedType(); 2426 } else if (!S.getLangOpts().CPlusPlus && 2427 S.Context.typesAreCompatible(ToType, FromType)) { 2428 // Compatible conversions (Clang extension for C function overloading) 2429 SCS.Second = ICK_Compatible_Conversion; 2430 FromType = ToType.getUnqualifiedType(); 2431 } else if (IsTransparentUnionStandardConversion( 2432 S, From, ToType, InOverloadResolution, SCS, CStyle)) { 2433 SCS.Second = ICK_TransparentUnionConversion; 2434 FromType = ToType; 2435 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 2436 CStyle)) { 2437 // tryAtomicConversion has updated the standard conversion sequence 2438 // appropriately. 2439 return true; 2440 } else if (ToType->isEventT() && 2441 From->isIntegerConstantExpr(S.getASTContext()) && 2442 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 2443 SCS.Second = ICK_Zero_Event_Conversion; 2444 FromType = ToType; 2445 } else if (ToType->isQueueT() && 2446 From->isIntegerConstantExpr(S.getASTContext()) && 2447 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 2448 SCS.Second = ICK_Zero_Queue_Conversion; 2449 FromType = ToType; 2450 } else if (ToType->isSamplerT() && 2451 From->isIntegerConstantExpr(S.getASTContext())) { 2452 SCS.Second = ICK_Compatible_Conversion; 2453 FromType = ToType; 2454 } else if ((ToType->isFixedPointType() && 2455 FromType->isConvertibleToFixedPointType()) || 2456 (FromType->isFixedPointType() && 2457 ToType->isConvertibleToFixedPointType())) { 2458 SCS.Second = ICK_Fixed_Point_Conversion; 2459 FromType = ToType; 2460 } else { 2461 // No second conversion required. 2462 SCS.Second = ICK_Identity; 2463 } 2464 SCS.setToType(1, FromType); 2465 2466 // The third conversion can be a function pointer conversion or a 2467 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 2468 bool ObjCLifetimeConversion; 2469 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 2470 // Function pointer conversions (removing 'noexcept') including removal of 2471 // 'noreturn' (Clang extension). 2472 SCS.Third = ICK_Function_Conversion; 2473 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 2474 ObjCLifetimeConversion)) { 2475 SCS.Third = ICK_Qualification; 2476 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 2477 FromType = ToType; 2478 } else { 2479 // No conversion required 2480 SCS.Third = ICK_Identity; 2481 } 2482 2483 // C++ [over.best.ics]p6: 2484 // [...] Any difference in top-level cv-qualification is 2485 // subsumed by the initialization itself and does not constitute 2486 // a conversion. [...] 2487 QualType CanonFrom = S.Context.getCanonicalType(FromType); 2488 QualType CanonTo = S.Context.getCanonicalType(ToType); 2489 if (CanonFrom.getLocalUnqualifiedType() 2490 == CanonTo.getLocalUnqualifiedType() && 2491 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 2492 FromType = ToType; 2493 CanonFrom = CanonTo; 2494 } 2495 2496 SCS.setToType(2, FromType); 2497 2498 if (CanonFrom == CanonTo) 2499 return true; 2500 2501 // If we have not converted the argument type to the parameter type, 2502 // this is a bad conversion sequence, unless we're resolving an overload in C. 2503 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 2504 return false; 2505 2506 ExprResult ER = ExprResult{From}; 2507 Sema::AssignConvertType Conv = 2508 S.CheckSingleAssignmentConstraints(ToType, ER, 2509 /*Diagnose=*/false, 2510 /*DiagnoseCFAudited=*/false, 2511 /*ConvertRHS=*/false); 2512 ImplicitConversionKind SecondConv; 2513 switch (Conv) { 2514 case Sema::Compatible: 2515 SecondConv = ICK_C_Only_Conversion; 2516 break; 2517 // For our purposes, discarding qualifiers is just as bad as using an 2518 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2519 // qualifiers, as well. 2520 case Sema::CompatiblePointerDiscardsQualifiers: 2521 case Sema::IncompatiblePointer: 2522 case Sema::IncompatiblePointerSign: 2523 SecondConv = ICK_Incompatible_Pointer_Conversion; 2524 break; 2525 default: 2526 return false; 2527 } 2528 2529 // First can only be an lvalue conversion, so we pretend that this was the 2530 // second conversion. First should already be valid from earlier in the 2531 // function. 2532 SCS.Second = SecondConv; 2533 SCS.setToType(1, ToType); 2534 2535 // Third is Identity, because Second should rank us worse than any other 2536 // conversion. This could also be ICK_Qualification, but it's simpler to just 2537 // lump everything in with the second conversion, and we don't gain anything 2538 // from making this ICK_Qualification. 2539 SCS.Third = ICK_Identity; 2540 SCS.setToType(2, ToType); 2541 return true; 2542 } 2543 2544 static bool 2545 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2546 QualType &ToType, 2547 bool InOverloadResolution, 2548 StandardConversionSequence &SCS, 2549 bool CStyle) { 2550 2551 const RecordType *UT = ToType->getAsUnionType(); 2552 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2553 return false; 2554 // The field to initialize within the transparent union. 2555 RecordDecl *UD = UT->getDecl(); 2556 // It's compatible if the expression matches any of the fields. 2557 for (const auto *it : UD->fields()) { 2558 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2559 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2560 ToType = it->getType(); 2561 return true; 2562 } 2563 } 2564 return false; 2565 } 2566 2567 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2568 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2569 // All integers are built-in. 2570 if (!To) { 2571 return false; 2572 } 2573 2574 // An rvalue of type char, signed char, unsigned char, short int, or 2575 // unsigned short int can be converted to an rvalue of type int if 2576 // int can represent all the values of the source type; otherwise, 2577 // the source rvalue can be converted to an rvalue of type unsigned 2578 // int (C++ 4.5p1). 2579 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() && 2580 !FromType->isEnumeralType()) { 2581 if ( // We can promote any signed, promotable integer type to an int 2582 (FromType->isSignedIntegerType() || 2583 // We can promote any unsigned integer type whose size is 2584 // less than int to an int. 2585 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2586 return To->getKind() == BuiltinType::Int; 2587 } 2588 2589 return To->getKind() == BuiltinType::UInt; 2590 } 2591 2592 // C++11 [conv.prom]p3: 2593 // A prvalue of an unscoped enumeration type whose underlying type is not 2594 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2595 // following types that can represent all the values of the enumeration 2596 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2597 // unsigned int, long int, unsigned long int, long long int, or unsigned 2598 // long long int. If none of the types in that list can represent all the 2599 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2600 // type can be converted to an rvalue a prvalue of the extended integer type 2601 // with lowest integer conversion rank (4.13) greater than the rank of long 2602 // long in which all the values of the enumeration can be represented. If 2603 // there are two such extended types, the signed one is chosen. 2604 // C++11 [conv.prom]p4: 2605 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2606 // can be converted to a prvalue of its underlying type. Moreover, if 2607 // integral promotion can be applied to its underlying type, a prvalue of an 2608 // unscoped enumeration type whose underlying type is fixed can also be 2609 // converted to a prvalue of the promoted underlying type. 2610 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2611 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2612 // provided for a scoped enumeration. 2613 if (FromEnumType->getDecl()->isScoped()) 2614 return false; 2615 2616 // We can perform an integral promotion to the underlying type of the enum, 2617 // even if that's not the promoted type. Note that the check for promoting 2618 // the underlying type is based on the type alone, and does not consider 2619 // the bitfield-ness of the actual source expression. 2620 if (FromEnumType->getDecl()->isFixed()) { 2621 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2622 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2623 IsIntegralPromotion(nullptr, Underlying, ToType); 2624 } 2625 2626 // We have already pre-calculated the promotion type, so this is trivial. 2627 if (ToType->isIntegerType() && 2628 isCompleteType(From->getBeginLoc(), FromType)) 2629 return Context.hasSameUnqualifiedType( 2630 ToType, FromEnumType->getDecl()->getPromotionType()); 2631 2632 // C++ [conv.prom]p5: 2633 // If the bit-field has an enumerated type, it is treated as any other 2634 // value of that type for promotion purposes. 2635 // 2636 // ... so do not fall through into the bit-field checks below in C++. 2637 if (getLangOpts().CPlusPlus) 2638 return false; 2639 } 2640 2641 // C++0x [conv.prom]p2: 2642 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2643 // to an rvalue a prvalue of the first of the following types that can 2644 // represent all the values of its underlying type: int, unsigned int, 2645 // long int, unsigned long int, long long int, or unsigned long long int. 2646 // If none of the types in that list can represent all the values of its 2647 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2648 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2649 // type. 2650 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2651 ToType->isIntegerType()) { 2652 // Determine whether the type we're converting from is signed or 2653 // unsigned. 2654 bool FromIsSigned = FromType->isSignedIntegerType(); 2655 uint64_t FromSize = Context.getTypeSize(FromType); 2656 2657 // The types we'll try to promote to, in the appropriate 2658 // order. Try each of these types. 2659 QualType PromoteTypes[6] = { 2660 Context.IntTy, Context.UnsignedIntTy, 2661 Context.LongTy, Context.UnsignedLongTy , 2662 Context.LongLongTy, Context.UnsignedLongLongTy 2663 }; 2664 for (int Idx = 0; Idx < 6; ++Idx) { 2665 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2666 if (FromSize < ToSize || 2667 (FromSize == ToSize && 2668 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2669 // We found the type that we can promote to. If this is the 2670 // type we wanted, we have a promotion. Otherwise, no 2671 // promotion. 2672 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2673 } 2674 } 2675 } 2676 2677 // An rvalue for an integral bit-field (9.6) can be converted to an 2678 // rvalue of type int if int can represent all the values of the 2679 // bit-field; otherwise, it can be converted to unsigned int if 2680 // unsigned int can represent all the values of the bit-field. If 2681 // the bit-field is larger yet, no integral promotion applies to 2682 // it. If the bit-field has an enumerated type, it is treated as any 2683 // other value of that type for promotion purposes (C++ 4.5p3). 2684 // FIXME: We should delay checking of bit-fields until we actually perform the 2685 // conversion. 2686 // 2687 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2688 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2689 // bit-fields and those whose underlying type is larger than int) for GCC 2690 // compatibility. 2691 if (From) { 2692 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2693 std::optional<llvm::APSInt> BitWidth; 2694 if (FromType->isIntegralType(Context) && 2695 (BitWidth = 2696 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2697 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2698 ToSize = Context.getTypeSize(ToType); 2699 2700 // Are we promoting to an int from a bitfield that fits in an int? 2701 if (*BitWidth < ToSize || 2702 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2703 return To->getKind() == BuiltinType::Int; 2704 } 2705 2706 // Are we promoting to an unsigned int from an unsigned bitfield 2707 // that fits into an unsigned int? 2708 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2709 return To->getKind() == BuiltinType::UInt; 2710 } 2711 2712 return false; 2713 } 2714 } 2715 } 2716 2717 // An rvalue of type bool can be converted to an rvalue of type int, 2718 // with false becoming zero and true becoming one (C++ 4.5p4). 2719 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2720 return true; 2721 } 2722 2723 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger 2724 // integral type. 2725 if (Context.getLangOpts().HLSL && FromType->isIntegerType() && 2726 ToType->isIntegerType()) 2727 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType); 2728 2729 return false; 2730 } 2731 2732 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2733 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2734 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2735 /// An rvalue of type float can be converted to an rvalue of type 2736 /// double. (C++ 4.6p1). 2737 if (FromBuiltin->getKind() == BuiltinType::Float && 2738 ToBuiltin->getKind() == BuiltinType::Double) 2739 return true; 2740 2741 // C99 6.3.1.5p1: 2742 // When a float is promoted to double or long double, or a 2743 // double is promoted to long double [...]. 2744 if (!getLangOpts().CPlusPlus && 2745 (FromBuiltin->getKind() == BuiltinType::Float || 2746 FromBuiltin->getKind() == BuiltinType::Double) && 2747 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2748 ToBuiltin->getKind() == BuiltinType::Float128 || 2749 ToBuiltin->getKind() == BuiltinType::Ibm128)) 2750 return true; 2751 2752 // In HLSL, `half` promotes to `float` or `double`, regardless of whether 2753 // or not native half types are enabled. 2754 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half && 2755 (ToBuiltin->getKind() == BuiltinType::Float || 2756 ToBuiltin->getKind() == BuiltinType::Double)) 2757 return true; 2758 2759 // Half can be promoted to float. 2760 if (!getLangOpts().NativeHalfType && 2761 FromBuiltin->getKind() == BuiltinType::Half && 2762 ToBuiltin->getKind() == BuiltinType::Float) 2763 return true; 2764 } 2765 2766 return false; 2767 } 2768 2769 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2770 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2771 if (!FromComplex) 2772 return false; 2773 2774 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2775 if (!ToComplex) 2776 return false; 2777 2778 return IsFloatingPointPromotion(FromComplex->getElementType(), 2779 ToComplex->getElementType()) || 2780 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2781 ToComplex->getElementType()); 2782 } 2783 2784 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2785 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2786 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2787 /// if non-empty, will be a pointer to ToType that may or may not have 2788 /// the right set of qualifiers on its pointee. 2789 /// 2790 static QualType 2791 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2792 QualType ToPointee, QualType ToType, 2793 ASTContext &Context, 2794 bool StripObjCLifetime = false) { 2795 assert((FromPtr->getTypeClass() == Type::Pointer || 2796 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2797 "Invalid similarly-qualified pointer type"); 2798 2799 /// Conversions to 'id' subsume cv-qualifier conversions. 2800 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2801 return ToType.getUnqualifiedType(); 2802 2803 QualType CanonFromPointee 2804 = Context.getCanonicalType(FromPtr->getPointeeType()); 2805 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2806 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2807 2808 if (StripObjCLifetime) 2809 Quals.removeObjCLifetime(); 2810 2811 // Exact qualifier match -> return the pointer type we're converting to. 2812 if (CanonToPointee.getLocalQualifiers() == Quals) { 2813 // ToType is exactly what we need. Return it. 2814 if (!ToType.isNull()) 2815 return ToType.getUnqualifiedType(); 2816 2817 // Build a pointer to ToPointee. It has the right qualifiers 2818 // already. 2819 if (isa<ObjCObjectPointerType>(ToType)) 2820 return Context.getObjCObjectPointerType(ToPointee); 2821 return Context.getPointerType(ToPointee); 2822 } 2823 2824 // Just build a canonical type that has the right qualifiers. 2825 QualType QualifiedCanonToPointee 2826 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2827 2828 if (isa<ObjCObjectPointerType>(ToType)) 2829 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2830 return Context.getPointerType(QualifiedCanonToPointee); 2831 } 2832 2833 static bool isNullPointerConstantForConversion(Expr *Expr, 2834 bool InOverloadResolution, 2835 ASTContext &Context) { 2836 // Handle value-dependent integral null pointer constants correctly. 2837 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2838 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2839 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2840 return !InOverloadResolution; 2841 2842 return Expr->isNullPointerConstant(Context, 2843 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2844 : Expr::NPC_ValueDependentIsNull); 2845 } 2846 2847 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2848 bool InOverloadResolution, 2849 QualType& ConvertedType, 2850 bool &IncompatibleObjC) { 2851 IncompatibleObjC = false; 2852 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2853 IncompatibleObjC)) 2854 return true; 2855 2856 // Conversion from a null pointer constant to any Objective-C pointer type. 2857 if (ToType->isObjCObjectPointerType() && 2858 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2859 ConvertedType = ToType; 2860 return true; 2861 } 2862 2863 // Blocks: Block pointers can be converted to void*. 2864 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2865 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2866 ConvertedType = ToType; 2867 return true; 2868 } 2869 // Blocks: A null pointer constant can be converted to a block 2870 // pointer type. 2871 if (ToType->isBlockPointerType() && 2872 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2873 ConvertedType = ToType; 2874 return true; 2875 } 2876 2877 // If the left-hand-side is nullptr_t, the right side can be a null 2878 // pointer constant. 2879 if (ToType->isNullPtrType() && 2880 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2881 ConvertedType = ToType; 2882 return true; 2883 } 2884 2885 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2886 if (!ToTypePtr) 2887 return false; 2888 2889 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2890 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2891 ConvertedType = ToType; 2892 return true; 2893 } 2894 2895 // Beyond this point, both types need to be pointers 2896 // , including objective-c pointers. 2897 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2898 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2899 !getLangOpts().ObjCAutoRefCount) { 2900 ConvertedType = BuildSimilarlyQualifiedPointerType( 2901 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, 2902 Context); 2903 return true; 2904 } 2905 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2906 if (!FromTypePtr) 2907 return false; 2908 2909 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2910 2911 // If the unqualified pointee types are the same, this can't be a 2912 // pointer conversion, so don't do all of the work below. 2913 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2914 return false; 2915 2916 // An rvalue of type "pointer to cv T," where T is an object type, 2917 // can be converted to an rvalue of type "pointer to cv void" (C++ 2918 // 4.10p2). 2919 if (FromPointeeType->isIncompleteOrObjectType() && 2920 ToPointeeType->isVoidType()) { 2921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2922 ToPointeeType, 2923 ToType, Context, 2924 /*StripObjCLifetime=*/true); 2925 return true; 2926 } 2927 2928 // MSVC allows implicit function to void* type conversion. 2929 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2930 ToPointeeType->isVoidType()) { 2931 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2932 ToPointeeType, 2933 ToType, Context); 2934 return true; 2935 } 2936 2937 // When we're overloading in C, we allow a special kind of pointer 2938 // conversion for compatible-but-not-identical pointee types. 2939 if (!getLangOpts().CPlusPlus && 2940 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2941 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2942 ToPointeeType, 2943 ToType, Context); 2944 return true; 2945 } 2946 2947 // C++ [conv.ptr]p3: 2948 // 2949 // An rvalue of type "pointer to cv D," where D is a class type, 2950 // can be converted to an rvalue of type "pointer to cv B," where 2951 // B is a base class (clause 10) of D. If B is an inaccessible 2952 // (clause 11) or ambiguous (10.2) base class of D, a program that 2953 // necessitates this conversion is ill-formed. The result of the 2954 // conversion is a pointer to the base class sub-object of the 2955 // derived class object. The null pointer value is converted to 2956 // the null pointer value of the destination type. 2957 // 2958 // Note that we do not check for ambiguity or inaccessibility 2959 // here. That is handled by CheckPointerConversion. 2960 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2961 ToPointeeType->isRecordType() && 2962 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2963 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2964 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2965 ToPointeeType, 2966 ToType, Context); 2967 return true; 2968 } 2969 2970 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2971 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2972 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2973 ToPointeeType, 2974 ToType, Context); 2975 return true; 2976 } 2977 2978 return false; 2979 } 2980 2981 /// Adopt the given qualifiers for the given type. 2982 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2983 Qualifiers TQs = T.getQualifiers(); 2984 2985 // Check whether qualifiers already match. 2986 if (TQs == Qs) 2987 return T; 2988 2989 if (Qs.compatiblyIncludes(TQs, Context)) 2990 return Context.getQualifiedType(T, Qs); 2991 2992 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2993 } 2994 2995 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2996 QualType& ConvertedType, 2997 bool &IncompatibleObjC) { 2998 if (!getLangOpts().ObjC) 2999 return false; 3000 3001 // The set of qualifiers on the type we're converting from. 3002 Qualifiers FromQualifiers = FromType.getQualifiers(); 3003 3004 // First, we handle all conversions on ObjC object pointer types. 3005 const ObjCObjectPointerType* ToObjCPtr = 3006 ToType->getAs<ObjCObjectPointerType>(); 3007 const ObjCObjectPointerType *FromObjCPtr = 3008 FromType->getAs<ObjCObjectPointerType>(); 3009 3010 if (ToObjCPtr && FromObjCPtr) { 3011 // If the pointee types are the same (ignoring qualifications), 3012 // then this is not a pointer conversion. 3013 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 3014 FromObjCPtr->getPointeeType())) 3015 return false; 3016 3017 // Conversion between Objective-C pointers. 3018 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 3019 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 3020 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 3021 if (getLangOpts().CPlusPlus && LHS && RHS && 3022 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 3023 FromObjCPtr->getPointeeType(), getASTContext())) 3024 return false; 3025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 3026 ToObjCPtr->getPointeeType(), 3027 ToType, Context); 3028 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 3029 return true; 3030 } 3031 3032 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 3033 // Okay: this is some kind of implicit downcast of Objective-C 3034 // interfaces, which is permitted. However, we're going to 3035 // complain about it. 3036 IncompatibleObjC = true; 3037 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 3038 ToObjCPtr->getPointeeType(), 3039 ToType, Context); 3040 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 3041 return true; 3042 } 3043 } 3044 // Beyond this point, both types need to be C pointers or block pointers. 3045 QualType ToPointeeType; 3046 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 3047 ToPointeeType = ToCPtr->getPointeeType(); 3048 else if (const BlockPointerType *ToBlockPtr = 3049 ToType->getAs<BlockPointerType>()) { 3050 // Objective C++: We're able to convert from a pointer to any object 3051 // to a block pointer type. 3052 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 3053 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 3054 return true; 3055 } 3056 ToPointeeType = ToBlockPtr->getPointeeType(); 3057 } 3058 else if (FromType->getAs<BlockPointerType>() && 3059 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 3060 // Objective C++: We're able to convert from a block pointer type to a 3061 // pointer to any object. 3062 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 3063 return true; 3064 } 3065 else 3066 return false; 3067 3068 QualType FromPointeeType; 3069 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 3070 FromPointeeType = FromCPtr->getPointeeType(); 3071 else if (const BlockPointerType *FromBlockPtr = 3072 FromType->getAs<BlockPointerType>()) 3073 FromPointeeType = FromBlockPtr->getPointeeType(); 3074 else 3075 return false; 3076 3077 // If we have pointers to pointers, recursively check whether this 3078 // is an Objective-C conversion. 3079 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 3080 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 3081 IncompatibleObjC)) { 3082 // We always complain about this conversion. 3083 IncompatibleObjC = true; 3084 ConvertedType = Context.getPointerType(ConvertedType); 3085 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 3086 return true; 3087 } 3088 // Allow conversion of pointee being objective-c pointer to another one; 3089 // as in I* to id. 3090 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 3091 ToPointeeType->getAs<ObjCObjectPointerType>() && 3092 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 3093 IncompatibleObjC)) { 3094 3095 ConvertedType = Context.getPointerType(ConvertedType); 3096 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 3097 return true; 3098 } 3099 3100 // If we have pointers to functions or blocks, check whether the only 3101 // differences in the argument and result types are in Objective-C 3102 // pointer conversions. If so, we permit the conversion (but 3103 // complain about it). 3104 const FunctionProtoType *FromFunctionType 3105 = FromPointeeType->getAs<FunctionProtoType>(); 3106 const FunctionProtoType *ToFunctionType 3107 = ToPointeeType->getAs<FunctionProtoType>(); 3108 if (FromFunctionType && ToFunctionType) { 3109 // If the function types are exactly the same, this isn't an 3110 // Objective-C pointer conversion. 3111 if (Context.getCanonicalType(FromPointeeType) 3112 == Context.getCanonicalType(ToPointeeType)) 3113 return false; 3114 3115 // Perform the quick checks that will tell us whether these 3116 // function types are obviously different. 3117 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 3118 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 3119 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 3120 return false; 3121 3122 bool HasObjCConversion = false; 3123 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 3124 Context.getCanonicalType(ToFunctionType->getReturnType())) { 3125 // Okay, the types match exactly. Nothing to do. 3126 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 3127 ToFunctionType->getReturnType(), 3128 ConvertedType, IncompatibleObjC)) { 3129 // Okay, we have an Objective-C pointer conversion. 3130 HasObjCConversion = true; 3131 } else { 3132 // Function types are too different. Abort. 3133 return false; 3134 } 3135 3136 // Check argument types. 3137 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 3138 ArgIdx != NumArgs; ++ArgIdx) { 3139 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 3140 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 3141 if (Context.getCanonicalType(FromArgType) 3142 == Context.getCanonicalType(ToArgType)) { 3143 // Okay, the types match exactly. Nothing to do. 3144 } else if (isObjCPointerConversion(FromArgType, ToArgType, 3145 ConvertedType, IncompatibleObjC)) { 3146 // Okay, we have an Objective-C pointer conversion. 3147 HasObjCConversion = true; 3148 } else { 3149 // Argument types are too different. Abort. 3150 return false; 3151 } 3152 } 3153 3154 if (HasObjCConversion) { 3155 // We had an Objective-C conversion. Allow this pointer 3156 // conversion, but complain about it. 3157 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 3158 IncompatibleObjC = true; 3159 return true; 3160 } 3161 } 3162 3163 return false; 3164 } 3165 3166 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 3167 QualType& ConvertedType) { 3168 QualType ToPointeeType; 3169 if (const BlockPointerType *ToBlockPtr = 3170 ToType->getAs<BlockPointerType>()) 3171 ToPointeeType = ToBlockPtr->getPointeeType(); 3172 else 3173 return false; 3174 3175 QualType FromPointeeType; 3176 if (const BlockPointerType *FromBlockPtr = 3177 FromType->getAs<BlockPointerType>()) 3178 FromPointeeType = FromBlockPtr->getPointeeType(); 3179 else 3180 return false; 3181 // We have pointer to blocks, check whether the only 3182 // differences in the argument and result types are in Objective-C 3183 // pointer conversions. If so, we permit the conversion. 3184 3185 const FunctionProtoType *FromFunctionType 3186 = FromPointeeType->getAs<FunctionProtoType>(); 3187 const FunctionProtoType *ToFunctionType 3188 = ToPointeeType->getAs<FunctionProtoType>(); 3189 3190 if (!FromFunctionType || !ToFunctionType) 3191 return false; 3192 3193 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 3194 return true; 3195 3196 // Perform the quick checks that will tell us whether these 3197 // function types are obviously different. 3198 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 3199 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 3200 return false; 3201 3202 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 3203 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 3204 if (FromEInfo != ToEInfo) 3205 return false; 3206 3207 bool IncompatibleObjC = false; 3208 if (Context.hasSameType(FromFunctionType->getReturnType(), 3209 ToFunctionType->getReturnType())) { 3210 // Okay, the types match exactly. Nothing to do. 3211 } else { 3212 QualType RHS = FromFunctionType->getReturnType(); 3213 QualType LHS = ToFunctionType->getReturnType(); 3214 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 3215 !RHS.hasQualifiers() && LHS.hasQualifiers()) 3216 LHS = LHS.getUnqualifiedType(); 3217 3218 if (Context.hasSameType(RHS,LHS)) { 3219 // OK exact match. 3220 } else if (isObjCPointerConversion(RHS, LHS, 3221 ConvertedType, IncompatibleObjC)) { 3222 if (IncompatibleObjC) 3223 return false; 3224 // Okay, we have an Objective-C pointer conversion. 3225 } 3226 else 3227 return false; 3228 } 3229 3230 // Check argument types. 3231 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 3232 ArgIdx != NumArgs; ++ArgIdx) { 3233 IncompatibleObjC = false; 3234 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 3235 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 3236 if (Context.hasSameType(FromArgType, ToArgType)) { 3237 // Okay, the types match exactly. Nothing to do. 3238 } else if (isObjCPointerConversion(ToArgType, FromArgType, 3239 ConvertedType, IncompatibleObjC)) { 3240 if (IncompatibleObjC) 3241 return false; 3242 // Okay, we have an Objective-C pointer conversion. 3243 } else 3244 // Argument types are too different. Abort. 3245 return false; 3246 } 3247 3248 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 3249 bool CanUseToFPT, CanUseFromFPT; 3250 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 3251 CanUseToFPT, CanUseFromFPT, 3252 NewParamInfos)) 3253 return false; 3254 3255 ConvertedType = ToType; 3256 return true; 3257 } 3258 3259 enum { 3260 ft_default, 3261 ft_different_class, 3262 ft_parameter_arity, 3263 ft_parameter_mismatch, 3264 ft_return_type, 3265 ft_qualifer_mismatch, 3266 ft_noexcept 3267 }; 3268 3269 /// Attempts to get the FunctionProtoType from a Type. Handles 3270 /// MemberFunctionPointers properly. 3271 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 3272 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 3273 return FPT; 3274 3275 if (auto *MPT = FromType->getAs<MemberPointerType>()) 3276 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 3277 3278 return nullptr; 3279 } 3280 3281 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 3282 QualType FromType, QualType ToType) { 3283 // If either type is not valid, include no extra info. 3284 if (FromType.isNull() || ToType.isNull()) { 3285 PDiag << ft_default; 3286 return; 3287 } 3288 3289 // Get the function type from the pointers. 3290 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 3291 const auto *FromMember = FromType->castAs<MemberPointerType>(), 3292 *ToMember = ToType->castAs<MemberPointerType>(); 3293 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 3294 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 3295 << QualType(FromMember->getClass(), 0); 3296 return; 3297 } 3298 FromType = FromMember->getPointeeType(); 3299 ToType = ToMember->getPointeeType(); 3300 } 3301 3302 if (FromType->isPointerType()) 3303 FromType = FromType->getPointeeType(); 3304 if (ToType->isPointerType()) 3305 ToType = ToType->getPointeeType(); 3306 3307 // Remove references. 3308 FromType = FromType.getNonReferenceType(); 3309 ToType = ToType.getNonReferenceType(); 3310 3311 // Don't print extra info for non-specialized template functions. 3312 if (FromType->isInstantiationDependentType() && 3313 !FromType->getAs<TemplateSpecializationType>()) { 3314 PDiag << ft_default; 3315 return; 3316 } 3317 3318 // No extra info for same types. 3319 if (Context.hasSameType(FromType, ToType)) { 3320 PDiag << ft_default; 3321 return; 3322 } 3323 3324 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 3325 *ToFunction = tryGetFunctionProtoType(ToType); 3326 3327 // Both types need to be function types. 3328 if (!FromFunction || !ToFunction) { 3329 PDiag << ft_default; 3330 return; 3331 } 3332 3333 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 3334 PDiag << ft_parameter_arity << ToFunction->getNumParams() 3335 << FromFunction->getNumParams(); 3336 return; 3337 } 3338 3339 // Handle different parameter types. 3340 unsigned ArgPos; 3341 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 3342 PDiag << ft_parameter_mismatch << ArgPos + 1 3343 << ToFunction->getParamType(ArgPos) 3344 << FromFunction->getParamType(ArgPos); 3345 return; 3346 } 3347 3348 // Handle different return type. 3349 if (!Context.hasSameType(FromFunction->getReturnType(), 3350 ToFunction->getReturnType())) { 3351 PDiag << ft_return_type << ToFunction->getReturnType() 3352 << FromFunction->getReturnType(); 3353 return; 3354 } 3355 3356 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 3357 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 3358 << FromFunction->getMethodQuals(); 3359 return; 3360 } 3361 3362 // Handle exception specification differences on canonical type (in C++17 3363 // onwards). 3364 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 3365 ->isNothrow() != 3366 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 3367 ->isNothrow()) { 3368 PDiag << ft_noexcept; 3369 return; 3370 } 3371 3372 // Unable to find a difference, so add no extra info. 3373 PDiag << ft_default; 3374 } 3375 3376 bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old, 3377 ArrayRef<QualType> New, unsigned *ArgPos, 3378 bool Reversed) { 3379 assert(llvm::size(Old) == llvm::size(New) && 3380 "Can't compare parameters of functions with different number of " 3381 "parameters!"); 3382 3383 for (auto &&[Idx, Type] : llvm::enumerate(Old)) { 3384 // Reverse iterate over the parameters of `OldType` if `Reversed` is true. 3385 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx; 3386 3387 // Ignore address spaces in pointee type. This is to disallow overloading 3388 // on __ptr32/__ptr64 address spaces. 3389 QualType OldType = 3390 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType()); 3391 QualType NewType = 3392 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType()); 3393 3394 if (!Context.hasSameType(OldType, NewType)) { 3395 if (ArgPos) 3396 *ArgPos = Idx; 3397 return false; 3398 } 3399 } 3400 return true; 3401 } 3402 3403 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3404 const FunctionProtoType *NewType, 3405 unsigned *ArgPos, bool Reversed) { 3406 return FunctionParamTypesAreEqual(OldType->param_types(), 3407 NewType->param_types(), ArgPos, Reversed); 3408 } 3409 3410 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, 3411 const FunctionDecl *NewFunction, 3412 unsigned *ArgPos, 3413 bool Reversed) { 3414 3415 if (OldFunction->getNumNonObjectParams() != 3416 NewFunction->getNumNonObjectParams()) 3417 return false; 3418 3419 unsigned OldIgnore = 3420 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter()); 3421 unsigned NewIgnore = 3422 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter()); 3423 3424 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType()); 3425 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType()); 3426 3427 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore), 3428 NewPT->param_types().slice(NewIgnore), 3429 ArgPos, Reversed); 3430 } 3431 3432 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 3433 CastKind &Kind, 3434 CXXCastPath& BasePath, 3435 bool IgnoreBaseAccess, 3436 bool Diagnose) { 3437 QualType FromType = From->getType(); 3438 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 3439 3440 Kind = CK_BitCast; 3441 3442 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 3443 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 3444 Expr::NPCK_ZeroExpression) { 3445 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3446 DiagRuntimeBehavior(From->getExprLoc(), From, 3447 PDiag(diag::warn_impcast_bool_to_null_pointer) 3448 << ToType << From->getSourceRange()); 3449 else if (!isUnevaluatedContext()) 3450 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3451 << ToType << From->getSourceRange(); 3452 } 3453 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3454 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3455 QualType FromPointeeType = FromPtrType->getPointeeType(), 3456 ToPointeeType = ToPtrType->getPointeeType(); 3457 3458 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3459 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3460 // We must have a derived-to-base conversion. Check an 3461 // ambiguous or inaccessible conversion. 3462 unsigned InaccessibleID = 0; 3463 unsigned AmbiguousID = 0; 3464 if (Diagnose) { 3465 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3466 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3467 } 3468 if (CheckDerivedToBaseConversion( 3469 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3470 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3471 &BasePath, IgnoreBaseAccess)) 3472 return true; 3473 3474 // The conversion was successful. 3475 Kind = CK_DerivedToBase; 3476 } 3477 3478 if (Diagnose && !IsCStyleOrFunctionalCast && 3479 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3480 assert(getLangOpts().MSVCCompat && 3481 "this should only be possible with MSVCCompat!"); 3482 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3483 << From->getSourceRange(); 3484 } 3485 } 3486 } else if (const ObjCObjectPointerType *ToPtrType = 3487 ToType->getAs<ObjCObjectPointerType>()) { 3488 if (const ObjCObjectPointerType *FromPtrType = 3489 FromType->getAs<ObjCObjectPointerType>()) { 3490 // Objective-C++ conversions are always okay. 3491 // FIXME: We should have a different class of conversions for the 3492 // Objective-C++ implicit conversions. 3493 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3494 return false; 3495 } else if (FromType->isBlockPointerType()) { 3496 Kind = CK_BlockPointerToObjCPointerCast; 3497 } else { 3498 Kind = CK_CPointerToObjCPointerCast; 3499 } 3500 } else if (ToType->isBlockPointerType()) { 3501 if (!FromType->isBlockPointerType()) 3502 Kind = CK_AnyPointerToBlockPointerCast; 3503 } 3504 3505 // We shouldn't fall into this case unless it's valid for other 3506 // reasons. 3507 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3508 Kind = CK_NullToPointer; 3509 3510 return false; 3511 } 3512 3513 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3514 QualType ToType, 3515 bool InOverloadResolution, 3516 QualType &ConvertedType) { 3517 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3518 if (!ToTypePtr) 3519 return false; 3520 3521 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3522 if (From->isNullPointerConstant(Context, 3523 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3524 : Expr::NPC_ValueDependentIsNull)) { 3525 ConvertedType = ToType; 3526 return true; 3527 } 3528 3529 // Otherwise, both types have to be member pointers. 3530 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3531 if (!FromTypePtr) 3532 return false; 3533 3534 // A pointer to member of B can be converted to a pointer to member of D, 3535 // where D is derived from B (C++ 4.11p2). 3536 QualType FromClass(FromTypePtr->getClass(), 0); 3537 QualType ToClass(ToTypePtr->getClass(), 0); 3538 3539 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3540 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3541 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3542 ToClass.getTypePtr()); 3543 return true; 3544 } 3545 3546 return false; 3547 } 3548 3549 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3550 CastKind &Kind, 3551 CXXCastPath &BasePath, 3552 bool IgnoreBaseAccess) { 3553 QualType FromType = From->getType(); 3554 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3555 if (!FromPtrType) { 3556 // This must be a null pointer to member pointer conversion 3557 assert(From->isNullPointerConstant(Context, 3558 Expr::NPC_ValueDependentIsNull) && 3559 "Expr must be null pointer constant!"); 3560 Kind = CK_NullToMemberPointer; 3561 return false; 3562 } 3563 3564 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3565 assert(ToPtrType && "No member pointer cast has a target type " 3566 "that is not a member pointer."); 3567 3568 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3569 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3570 3571 // FIXME: What about dependent types? 3572 assert(FromClass->isRecordType() && "Pointer into non-class."); 3573 assert(ToClass->isRecordType() && "Pointer into non-class."); 3574 3575 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3576 /*DetectVirtual=*/true); 3577 bool DerivationOkay = 3578 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3579 assert(DerivationOkay && 3580 "Should not have been called if derivation isn't OK."); 3581 (void)DerivationOkay; 3582 3583 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3584 getUnqualifiedType())) { 3585 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3586 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3587 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3588 return true; 3589 } 3590 3591 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3592 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3593 << FromClass << ToClass << QualType(VBase, 0) 3594 << From->getSourceRange(); 3595 return true; 3596 } 3597 3598 if (!IgnoreBaseAccess) 3599 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3600 Paths.front(), 3601 diag::err_downcast_from_inaccessible_base); 3602 3603 // Must be a base to derived member conversion. 3604 BuildBasePathArray(Paths, BasePath); 3605 Kind = CK_BaseToDerivedMemberPointer; 3606 return false; 3607 } 3608 3609 /// Determine whether the lifetime conversion between the two given 3610 /// qualifiers sets is nontrivial. 3611 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3612 Qualifiers ToQuals) { 3613 // Converting anything to const __unsafe_unretained is trivial. 3614 if (ToQuals.hasConst() && 3615 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3616 return false; 3617 3618 return true; 3619 } 3620 3621 /// Perform a single iteration of the loop for checking if a qualification 3622 /// conversion is valid. 3623 /// 3624 /// Specifically, check whether any change between the qualifiers of \p 3625 /// FromType and \p ToType is permissible, given knowledge about whether every 3626 /// outer layer is const-qualified. 3627 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3628 bool CStyle, bool IsTopLevel, 3629 bool &PreviousToQualsIncludeConst, 3630 bool &ObjCLifetimeConversion, 3631 const ASTContext &Ctx) { 3632 Qualifiers FromQuals = FromType.getQualifiers(); 3633 Qualifiers ToQuals = ToType.getQualifiers(); 3634 3635 // Ignore __unaligned qualifier. 3636 FromQuals.removeUnaligned(); 3637 3638 // Objective-C ARC: 3639 // Check Objective-C lifetime conversions. 3640 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3641 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3642 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3643 ObjCLifetimeConversion = true; 3644 FromQuals.removeObjCLifetime(); 3645 ToQuals.removeObjCLifetime(); 3646 } else { 3647 // Qualification conversions cannot cast between different 3648 // Objective-C lifetime qualifiers. 3649 return false; 3650 } 3651 } 3652 3653 // Allow addition/removal of GC attributes but not changing GC attributes. 3654 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3655 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3656 FromQuals.removeObjCGCAttr(); 3657 ToQuals.removeObjCGCAttr(); 3658 } 3659 3660 // -- for every j > 0, if const is in cv 1,j then const is in cv 3661 // 2,j, and similarly for volatile. 3662 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx)) 3663 return false; 3664 3665 // If address spaces mismatch: 3666 // - in top level it is only valid to convert to addr space that is a 3667 // superset in all cases apart from C-style casts where we allow 3668 // conversions between overlapping address spaces. 3669 // - in non-top levels it is not a valid conversion. 3670 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3671 (!IsTopLevel || 3672 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) || 3673 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx))))) 3674 return false; 3675 3676 // -- if the cv 1,j and cv 2,j are different, then const is in 3677 // every cv for 0 < k < j. 3678 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3679 !PreviousToQualsIncludeConst) 3680 return false; 3681 3682 // The following wording is from C++20, where the result of the conversion 3683 // is T3, not T2. 3684 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is 3685 // "array of unknown bound of" 3686 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) 3687 return false; 3688 3689 // -- if the resulting P3,i is different from P1,i [...], then const is 3690 // added to every cv 3_k for 0 < k < i. 3691 if (!CStyle && FromType->isConstantArrayType() && 3692 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) 3693 return false; 3694 3695 // Keep track of whether all prior cv-qualifiers in the "to" type 3696 // include const. 3697 PreviousToQualsIncludeConst = 3698 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3699 return true; 3700 } 3701 3702 bool 3703 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3704 bool CStyle, bool &ObjCLifetimeConversion) { 3705 FromType = Context.getCanonicalType(FromType); 3706 ToType = Context.getCanonicalType(ToType); 3707 ObjCLifetimeConversion = false; 3708 3709 // If FromType and ToType are the same type, this is not a 3710 // qualification conversion. 3711 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3712 return false; 3713 3714 // (C++ 4.4p4): 3715 // A conversion can add cv-qualifiers at levels other than the first 3716 // in multi-level pointers, subject to the following rules: [...] 3717 bool PreviousToQualsIncludeConst = true; 3718 bool UnwrappedAnyPointer = false; 3719 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3720 if (!isQualificationConversionStep(FromType, ToType, CStyle, 3721 !UnwrappedAnyPointer, 3722 PreviousToQualsIncludeConst, 3723 ObjCLifetimeConversion, getASTContext())) 3724 return false; 3725 UnwrappedAnyPointer = true; 3726 } 3727 3728 // We are left with FromType and ToType being the pointee types 3729 // after unwrapping the original FromType and ToType the same number 3730 // of times. If we unwrapped any pointers, and if FromType and 3731 // ToType have the same unqualified type (since we checked 3732 // qualifiers above), then this is a qualification conversion. 3733 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3734 } 3735 3736 /// - Determine whether this is a conversion from a scalar type to an 3737 /// atomic type. 3738 /// 3739 /// If successful, updates \c SCS's second and third steps in the conversion 3740 /// sequence to finish the conversion. 3741 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3742 bool InOverloadResolution, 3743 StandardConversionSequence &SCS, 3744 bool CStyle) { 3745 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3746 if (!ToAtomic) 3747 return false; 3748 3749 StandardConversionSequence InnerSCS; 3750 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3751 InOverloadResolution, InnerSCS, 3752 CStyle, /*AllowObjCWritebackConversion=*/false)) 3753 return false; 3754 3755 SCS.Second = InnerSCS.Second; 3756 SCS.setToType(1, InnerSCS.getToType(1)); 3757 SCS.Third = InnerSCS.Third; 3758 SCS.QualificationIncludesObjCLifetime 3759 = InnerSCS.QualificationIncludesObjCLifetime; 3760 SCS.setToType(2, InnerSCS.getToType(2)); 3761 return true; 3762 } 3763 3764 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3765 CXXConstructorDecl *Constructor, 3766 QualType Type) { 3767 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3768 if (CtorType->getNumParams() > 0) { 3769 QualType FirstArg = CtorType->getParamType(0); 3770 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3771 return true; 3772 } 3773 return false; 3774 } 3775 3776 static OverloadingResult 3777 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3778 CXXRecordDecl *To, 3779 UserDefinedConversionSequence &User, 3780 OverloadCandidateSet &CandidateSet, 3781 bool AllowExplicit) { 3782 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3783 for (auto *D : S.LookupConstructors(To)) { 3784 auto Info = getConstructorInfo(D); 3785 if (!Info) 3786 continue; 3787 3788 bool Usable = !Info.Constructor->isInvalidDecl() && 3789 S.isInitListConstructor(Info.Constructor); 3790 if (Usable) { 3791 bool SuppressUserConversions = false; 3792 if (Info.ConstructorTmpl) 3793 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3794 /*ExplicitArgs*/ nullptr, From, 3795 CandidateSet, SuppressUserConversions, 3796 /*PartialOverloading*/ false, 3797 AllowExplicit); 3798 else 3799 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3800 CandidateSet, SuppressUserConversions, 3801 /*PartialOverloading*/ false, AllowExplicit); 3802 } 3803 } 3804 3805 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3806 3807 OverloadCandidateSet::iterator Best; 3808 switch (auto Result = 3809 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3810 case OR_Deleted: 3811 case OR_Success: { 3812 // Record the standard conversion we used and the conversion function. 3813 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3814 QualType ThisType = Constructor->getFunctionObjectParameterType(); 3815 // Initializer lists don't have conversions as such. 3816 User.Before.setAsIdentityConversion(); 3817 User.HadMultipleCandidates = HadMultipleCandidates; 3818 User.ConversionFunction = Constructor; 3819 User.FoundConversionFunction = Best->FoundDecl; 3820 User.After.setAsIdentityConversion(); 3821 User.After.setFromType(ThisType); 3822 User.After.setAllToTypes(ToType); 3823 return Result; 3824 } 3825 3826 case OR_No_Viable_Function: 3827 return OR_No_Viable_Function; 3828 case OR_Ambiguous: 3829 return OR_Ambiguous; 3830 } 3831 3832 llvm_unreachable("Invalid OverloadResult!"); 3833 } 3834 3835 /// Determines whether there is a user-defined conversion sequence 3836 /// (C++ [over.ics.user]) that converts expression From to the type 3837 /// ToType. If such a conversion exists, User will contain the 3838 /// user-defined conversion sequence that performs such a conversion 3839 /// and this routine will return true. Otherwise, this routine returns 3840 /// false and User is unspecified. 3841 /// 3842 /// \param AllowExplicit true if the conversion should consider C++0x 3843 /// "explicit" conversion functions as well as non-explicit conversion 3844 /// functions (C++0x [class.conv.fct]p2). 3845 /// 3846 /// \param AllowObjCConversionOnExplicit true if the conversion should 3847 /// allow an extra Objective-C pointer conversion on uses of explicit 3848 /// constructors. Requires \c AllowExplicit to also be set. 3849 static OverloadingResult 3850 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3851 UserDefinedConversionSequence &User, 3852 OverloadCandidateSet &CandidateSet, 3853 AllowedExplicit AllowExplicit, 3854 bool AllowObjCConversionOnExplicit) { 3855 assert(AllowExplicit != AllowedExplicit::None || 3856 !AllowObjCConversionOnExplicit); 3857 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3858 3859 // Whether we will only visit constructors. 3860 bool ConstructorsOnly = false; 3861 3862 // If the type we are conversion to is a class type, enumerate its 3863 // constructors. 3864 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3865 // C++ [over.match.ctor]p1: 3866 // When objects of class type are direct-initialized (8.5), or 3867 // copy-initialized from an expression of the same or a 3868 // derived class type (8.5), overload resolution selects the 3869 // constructor. [...] For copy-initialization, the candidate 3870 // functions are all the converting constructors (12.3.1) of 3871 // that class. The argument list is the expression-list within 3872 // the parentheses of the initializer. 3873 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3874 (From->getType()->getAs<RecordType>() && 3875 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3876 ConstructorsOnly = true; 3877 3878 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3879 // We're not going to find any constructors. 3880 } else if (CXXRecordDecl *ToRecordDecl 3881 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3882 3883 Expr **Args = &From; 3884 unsigned NumArgs = 1; 3885 bool ListInitializing = false; 3886 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3887 // But first, see if there is an init-list-constructor that will work. 3888 OverloadingResult Result = IsInitializerListConstructorConversion( 3889 S, From, ToType, ToRecordDecl, User, CandidateSet, 3890 AllowExplicit == AllowedExplicit::All); 3891 if (Result != OR_No_Viable_Function) 3892 return Result; 3893 // Never mind. 3894 CandidateSet.clear( 3895 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3896 3897 // If we're list-initializing, we pass the individual elements as 3898 // arguments, not the entire list. 3899 Args = InitList->getInits(); 3900 NumArgs = InitList->getNumInits(); 3901 ListInitializing = true; 3902 } 3903 3904 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3905 auto Info = getConstructorInfo(D); 3906 if (!Info) 3907 continue; 3908 3909 bool Usable = !Info.Constructor->isInvalidDecl(); 3910 if (!ListInitializing) 3911 Usable = Usable && Info.Constructor->isConvertingConstructor( 3912 /*AllowExplicit*/ true); 3913 if (Usable) { 3914 bool SuppressUserConversions = !ConstructorsOnly; 3915 // C++20 [over.best.ics.general]/4.5: 3916 // if the target is the first parameter of a constructor [of class 3917 // X] and the constructor [...] is a candidate by [...] the second 3918 // phase of [over.match.list] when the initializer list has exactly 3919 // one element that is itself an initializer list, [...] and the 3920 // conversion is to X or reference to cv X, user-defined conversion 3921 // sequences are not cnosidered. 3922 if (SuppressUserConversions && ListInitializing) { 3923 SuppressUserConversions = 3924 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3925 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3926 ToType); 3927 } 3928 if (Info.ConstructorTmpl) 3929 S.AddTemplateOverloadCandidate( 3930 Info.ConstructorTmpl, Info.FoundDecl, 3931 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs), 3932 CandidateSet, SuppressUserConversions, 3933 /*PartialOverloading*/ false, 3934 AllowExplicit == AllowedExplicit::All); 3935 else 3936 // Allow one user-defined conversion when user specifies a 3937 // From->ToType conversion via an static cast (c-style, etc). 3938 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3939 llvm::ArrayRef(Args, NumArgs), CandidateSet, 3940 SuppressUserConversions, 3941 /*PartialOverloading*/ false, 3942 AllowExplicit == AllowedExplicit::All); 3943 } 3944 } 3945 } 3946 } 3947 3948 // Enumerate conversion functions, if we're allowed to. 3949 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3950 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3951 // No conversion functions from incomplete types. 3952 } else if (const RecordType *FromRecordType = 3953 From->getType()->getAs<RecordType>()) { 3954 if (CXXRecordDecl *FromRecordDecl 3955 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3956 // Add all of the conversion functions as candidates. 3957 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3958 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3959 DeclAccessPair FoundDecl = I.getPair(); 3960 NamedDecl *D = FoundDecl.getDecl(); 3961 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3962 if (isa<UsingShadowDecl>(D)) 3963 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3964 3965 CXXConversionDecl *Conv; 3966 FunctionTemplateDecl *ConvTemplate; 3967 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3968 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3969 else 3970 Conv = cast<CXXConversionDecl>(D); 3971 3972 if (ConvTemplate) 3973 S.AddTemplateConversionCandidate( 3974 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3975 CandidateSet, AllowObjCConversionOnExplicit, 3976 AllowExplicit != AllowedExplicit::None); 3977 else 3978 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3979 CandidateSet, AllowObjCConversionOnExplicit, 3980 AllowExplicit != AllowedExplicit::None); 3981 } 3982 } 3983 } 3984 3985 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3986 3987 OverloadCandidateSet::iterator Best; 3988 switch (auto Result = 3989 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3990 case OR_Success: 3991 case OR_Deleted: 3992 // Record the standard conversion we used and the conversion function. 3993 if (CXXConstructorDecl *Constructor 3994 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3995 // C++ [over.ics.user]p1: 3996 // If the user-defined conversion is specified by a 3997 // constructor (12.3.1), the initial standard conversion 3998 // sequence converts the source type to the type required by 3999 // the argument of the constructor. 4000 // 4001 if (isa<InitListExpr>(From)) { 4002 // Initializer lists don't have conversions as such. 4003 User.Before.setAsIdentityConversion(); 4004 } else { 4005 if (Best->Conversions[0].isEllipsis()) 4006 User.EllipsisConversion = true; 4007 else { 4008 User.Before = Best->Conversions[0].Standard; 4009 User.EllipsisConversion = false; 4010 } 4011 } 4012 User.HadMultipleCandidates = HadMultipleCandidates; 4013 User.ConversionFunction = Constructor; 4014 User.FoundConversionFunction = Best->FoundDecl; 4015 User.After.setAsIdentityConversion(); 4016 User.After.setFromType(Constructor->getFunctionObjectParameterType()); 4017 User.After.setAllToTypes(ToType); 4018 return Result; 4019 } 4020 if (CXXConversionDecl *Conversion 4021 = dyn_cast<CXXConversionDecl>(Best->Function)) { 4022 // C++ [over.ics.user]p1: 4023 // 4024 // [...] If the user-defined conversion is specified by a 4025 // conversion function (12.3.2), the initial standard 4026 // conversion sequence converts the source type to the 4027 // implicit object parameter of the conversion function. 4028 User.Before = Best->Conversions[0].Standard; 4029 User.HadMultipleCandidates = HadMultipleCandidates; 4030 User.ConversionFunction = Conversion; 4031 User.FoundConversionFunction = Best->FoundDecl; 4032 User.EllipsisConversion = false; 4033 4034 // C++ [over.ics.user]p2: 4035 // The second standard conversion sequence converts the 4036 // result of the user-defined conversion to the target type 4037 // for the sequence. Since an implicit conversion sequence 4038 // is an initialization, the special rules for 4039 // initialization by user-defined conversion apply when 4040 // selecting the best user-defined conversion for a 4041 // user-defined conversion sequence (see 13.3.3 and 4042 // 13.3.3.1). 4043 User.After = Best->FinalConversion; 4044 return Result; 4045 } 4046 llvm_unreachable("Not a constructor or conversion function?"); 4047 4048 case OR_No_Viable_Function: 4049 return OR_No_Viable_Function; 4050 4051 case OR_Ambiguous: 4052 return OR_Ambiguous; 4053 } 4054 4055 llvm_unreachable("Invalid OverloadResult!"); 4056 } 4057 4058 bool 4059 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 4060 ImplicitConversionSequence ICS; 4061 OverloadCandidateSet CandidateSet(From->getExprLoc(), 4062 OverloadCandidateSet::CSK_Normal); 4063 OverloadingResult OvResult = 4064 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 4065 CandidateSet, AllowedExplicit::None, false); 4066 4067 if (!(OvResult == OR_Ambiguous || 4068 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 4069 return false; 4070 4071 auto Cands = CandidateSet.CompleteCandidates( 4072 *this, 4073 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 4074 From); 4075 if (OvResult == OR_Ambiguous) 4076 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 4077 << From->getType() << ToType << From->getSourceRange(); 4078 else { // OR_No_Viable_Function && !CandidateSet.empty() 4079 if (!RequireCompleteType(From->getBeginLoc(), ToType, 4080 diag::err_typecheck_nonviable_condition_incomplete, 4081 From->getType(), From->getSourceRange())) 4082 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 4083 << false << From->getType() << From->getSourceRange() << ToType; 4084 } 4085 4086 CandidateSet.NoteCandidates( 4087 *this, From, Cands); 4088 return true; 4089 } 4090 4091 // Helper for compareConversionFunctions that gets the FunctionType that the 4092 // conversion-operator return value 'points' to, or nullptr. 4093 static const FunctionType * 4094 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 4095 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 4096 const PointerType *RetPtrTy = 4097 ConvFuncTy->getReturnType()->getAs<PointerType>(); 4098 4099 if (!RetPtrTy) 4100 return nullptr; 4101 4102 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 4103 } 4104 4105 /// Compare the user-defined conversion functions or constructors 4106 /// of two user-defined conversion sequences to determine whether any ordering 4107 /// is possible. 4108 static ImplicitConversionSequence::CompareKind 4109 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 4110 FunctionDecl *Function2) { 4111 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 4112 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 4113 if (!Conv1 || !Conv2) 4114 return ImplicitConversionSequence::Indistinguishable; 4115 4116 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 4117 return ImplicitConversionSequence::Indistinguishable; 4118 4119 // Objective-C++: 4120 // If both conversion functions are implicitly-declared conversions from 4121 // a lambda closure type to a function pointer and a block pointer, 4122 // respectively, always prefer the conversion to a function pointer, 4123 // because the function pointer is more lightweight and is more likely 4124 // to keep code working. 4125 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 4126 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 4127 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 4128 if (Block1 != Block2) 4129 return Block1 ? ImplicitConversionSequence::Worse 4130 : ImplicitConversionSequence::Better; 4131 } 4132 4133 // In order to support multiple calling conventions for the lambda conversion 4134 // operator (such as when the free and member function calling convention is 4135 // different), prefer the 'free' mechanism, followed by the calling-convention 4136 // of operator(). The latter is in place to support the MSVC-like solution of 4137 // defining ALL of the possible conversions in regards to calling-convention. 4138 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 4139 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 4140 4141 if (Conv1FuncRet && Conv2FuncRet && 4142 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 4143 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 4144 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 4145 4146 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 4147 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); 4148 4149 CallingConv CallOpCC = 4150 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 4151 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 4152 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 4153 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 4154 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 4155 4156 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 4157 for (CallingConv CC : PrefOrder) { 4158 if (Conv1CC == CC) 4159 return ImplicitConversionSequence::Better; 4160 if (Conv2CC == CC) 4161 return ImplicitConversionSequence::Worse; 4162 } 4163 } 4164 4165 return ImplicitConversionSequence::Indistinguishable; 4166 } 4167 4168 static bool hasDeprecatedStringLiteralToCharPtrConversion( 4169 const ImplicitConversionSequence &ICS) { 4170 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 4171 (ICS.isUserDefined() && 4172 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 4173 } 4174 4175 /// CompareImplicitConversionSequences - Compare two implicit 4176 /// conversion sequences to determine whether one is better than the 4177 /// other or if they are indistinguishable (C++ 13.3.3.2). 4178 static ImplicitConversionSequence::CompareKind 4179 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 4180 const ImplicitConversionSequence& ICS1, 4181 const ImplicitConversionSequence& ICS2) 4182 { 4183 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 4184 // conversion sequences (as defined in 13.3.3.1) 4185 // -- a standard conversion sequence (13.3.3.1.1) is a better 4186 // conversion sequence than a user-defined conversion sequence or 4187 // an ellipsis conversion sequence, and 4188 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 4189 // conversion sequence than an ellipsis conversion sequence 4190 // (13.3.3.1.3). 4191 // 4192 // C++0x [over.best.ics]p10: 4193 // For the purpose of ranking implicit conversion sequences as 4194 // described in 13.3.3.2, the ambiguous conversion sequence is 4195 // treated as a user-defined sequence that is indistinguishable 4196 // from any other user-defined conversion sequence. 4197 4198 // String literal to 'char *' conversion has been deprecated in C++03. It has 4199 // been removed from C++11. We still accept this conversion, if it happens at 4200 // the best viable function. Otherwise, this conversion is considered worse 4201 // than ellipsis conversion. Consider this as an extension; this is not in the 4202 // standard. For example: 4203 // 4204 // int &f(...); // #1 4205 // void f(char*); // #2 4206 // void g() { int &r = f("foo"); } 4207 // 4208 // In C++03, we pick #2 as the best viable function. 4209 // In C++11, we pick #1 as the best viable function, because ellipsis 4210 // conversion is better than string-literal to char* conversion (since there 4211 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 4212 // convert arguments, #2 would be the best viable function in C++11. 4213 // If the best viable function has this conversion, a warning will be issued 4214 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 4215 4216 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 4217 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 4218 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && 4219 // Ill-formedness must not differ 4220 ICS1.isBad() == ICS2.isBad()) 4221 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 4222 ? ImplicitConversionSequence::Worse 4223 : ImplicitConversionSequence::Better; 4224 4225 if (ICS1.getKindRank() < ICS2.getKindRank()) 4226 return ImplicitConversionSequence::Better; 4227 if (ICS2.getKindRank() < ICS1.getKindRank()) 4228 return ImplicitConversionSequence::Worse; 4229 4230 // The following checks require both conversion sequences to be of 4231 // the same kind. 4232 if (ICS1.getKind() != ICS2.getKind()) 4233 return ImplicitConversionSequence::Indistinguishable; 4234 4235 ImplicitConversionSequence::CompareKind Result = 4236 ImplicitConversionSequence::Indistinguishable; 4237 4238 // Two implicit conversion sequences of the same form are 4239 // indistinguishable conversion sequences unless one of the 4240 // following rules apply: (C++ 13.3.3.2p3): 4241 4242 // List-initialization sequence L1 is a better conversion sequence than 4243 // list-initialization sequence L2 if: 4244 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 4245 // if not that, 4246 // — L1 and L2 convert to arrays of the same element type, and either the 4247 // number of elements n_1 initialized by L1 is less than the number of 4248 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to 4249 // an array of unknown bound and L1 does not, 4250 // even if one of the other rules in this paragraph would otherwise apply. 4251 if (!ICS1.isBad()) { 4252 bool StdInit1 = false, StdInit2 = false; 4253 if (ICS1.hasInitializerListContainerType()) 4254 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), 4255 nullptr); 4256 if (ICS2.hasInitializerListContainerType()) 4257 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), 4258 nullptr); 4259 if (StdInit1 != StdInit2) 4260 return StdInit1 ? ImplicitConversionSequence::Better 4261 : ImplicitConversionSequence::Worse; 4262 4263 if (ICS1.hasInitializerListContainerType() && 4264 ICS2.hasInitializerListContainerType()) 4265 if (auto *CAT1 = S.Context.getAsConstantArrayType( 4266 ICS1.getInitializerListContainerType())) 4267 if (auto *CAT2 = S.Context.getAsConstantArrayType( 4268 ICS2.getInitializerListContainerType())) { 4269 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), 4270 CAT2->getElementType())) { 4271 // Both to arrays of the same element type 4272 if (CAT1->getSize() != CAT2->getSize()) 4273 // Different sized, the smaller wins 4274 return CAT1->getSize().ult(CAT2->getSize()) 4275 ? ImplicitConversionSequence::Better 4276 : ImplicitConversionSequence::Worse; 4277 if (ICS1.isInitializerListOfIncompleteArray() != 4278 ICS2.isInitializerListOfIncompleteArray()) 4279 // One is incomplete, it loses 4280 return ICS2.isInitializerListOfIncompleteArray() 4281 ? ImplicitConversionSequence::Better 4282 : ImplicitConversionSequence::Worse; 4283 } 4284 } 4285 } 4286 4287 if (ICS1.isStandard()) 4288 // Standard conversion sequence S1 is a better conversion sequence than 4289 // standard conversion sequence S2 if [...] 4290 Result = CompareStandardConversionSequences(S, Loc, 4291 ICS1.Standard, ICS2.Standard); 4292 else if (ICS1.isUserDefined()) { 4293 // User-defined conversion sequence U1 is a better conversion 4294 // sequence than another user-defined conversion sequence U2 if 4295 // they contain the same user-defined conversion function or 4296 // constructor and if the second standard conversion sequence of 4297 // U1 is better than the second standard conversion sequence of 4298 // U2 (C++ 13.3.3.2p3). 4299 if (ICS1.UserDefined.ConversionFunction == 4300 ICS2.UserDefined.ConversionFunction) 4301 Result = CompareStandardConversionSequences(S, Loc, 4302 ICS1.UserDefined.After, 4303 ICS2.UserDefined.After); 4304 else 4305 Result = compareConversionFunctions(S, 4306 ICS1.UserDefined.ConversionFunction, 4307 ICS2.UserDefined.ConversionFunction); 4308 } 4309 4310 return Result; 4311 } 4312 4313 // Per 13.3.3.2p3, compare the given standard conversion sequences to 4314 // determine if one is a proper subset of the other. 4315 static ImplicitConversionSequence::CompareKind 4316 compareStandardConversionSubsets(ASTContext &Context, 4317 const StandardConversionSequence& SCS1, 4318 const StandardConversionSequence& SCS2) { 4319 ImplicitConversionSequence::CompareKind Result 4320 = ImplicitConversionSequence::Indistinguishable; 4321 4322 // the identity conversion sequence is considered to be a subsequence of 4323 // any non-identity conversion sequence 4324 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 4325 return ImplicitConversionSequence::Better; 4326 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 4327 return ImplicitConversionSequence::Worse; 4328 4329 if (SCS1.Second != SCS2.Second) { 4330 if (SCS1.Second == ICK_Identity) 4331 Result = ImplicitConversionSequence::Better; 4332 else if (SCS2.Second == ICK_Identity) 4333 Result = ImplicitConversionSequence::Worse; 4334 else 4335 return ImplicitConversionSequence::Indistinguishable; 4336 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 4337 return ImplicitConversionSequence::Indistinguishable; 4338 4339 if (SCS1.Third == SCS2.Third) { 4340 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 4341 : ImplicitConversionSequence::Indistinguishable; 4342 } 4343 4344 if (SCS1.Third == ICK_Identity) 4345 return Result == ImplicitConversionSequence::Worse 4346 ? ImplicitConversionSequence::Indistinguishable 4347 : ImplicitConversionSequence::Better; 4348 4349 if (SCS2.Third == ICK_Identity) 4350 return Result == ImplicitConversionSequence::Better 4351 ? ImplicitConversionSequence::Indistinguishable 4352 : ImplicitConversionSequence::Worse; 4353 4354 return ImplicitConversionSequence::Indistinguishable; 4355 } 4356 4357 /// Determine whether one of the given reference bindings is better 4358 /// than the other based on what kind of bindings they are. 4359 static bool 4360 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 4361 const StandardConversionSequence &SCS2) { 4362 // C++0x [over.ics.rank]p3b4: 4363 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 4364 // implicit object parameter of a non-static member function declared 4365 // without a ref-qualifier, and *either* S1 binds an rvalue reference 4366 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 4367 // lvalue reference to a function lvalue and S2 binds an rvalue 4368 // reference*. 4369 // 4370 // FIXME: Rvalue references. We're going rogue with the above edits, 4371 // because the semantics in the current C++0x working paper (N3225 at the 4372 // time of this writing) break the standard definition of std::forward 4373 // and std::reference_wrapper when dealing with references to functions. 4374 // Proposed wording changes submitted to CWG for consideration. 4375 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 4376 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 4377 return false; 4378 4379 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 4380 SCS2.IsLvalueReference) || 4381 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 4382 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 4383 } 4384 4385 enum class FixedEnumPromotion { 4386 None, 4387 ToUnderlyingType, 4388 ToPromotedUnderlyingType 4389 }; 4390 4391 /// Returns kind of fixed enum promotion the \a SCS uses. 4392 static FixedEnumPromotion 4393 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 4394 4395 if (SCS.Second != ICK_Integral_Promotion) 4396 return FixedEnumPromotion::None; 4397 4398 QualType FromType = SCS.getFromType(); 4399 if (!FromType->isEnumeralType()) 4400 return FixedEnumPromotion::None; 4401 4402 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 4403 if (!Enum->isFixed()) 4404 return FixedEnumPromotion::None; 4405 4406 QualType UnderlyingType = Enum->getIntegerType(); 4407 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 4408 return FixedEnumPromotion::ToUnderlyingType; 4409 4410 return FixedEnumPromotion::ToPromotedUnderlyingType; 4411 } 4412 4413 /// CompareStandardConversionSequences - Compare two standard 4414 /// conversion sequences to determine whether one is better than the 4415 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 4416 static ImplicitConversionSequence::CompareKind 4417 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 4418 const StandardConversionSequence& SCS1, 4419 const StandardConversionSequence& SCS2) 4420 { 4421 // Standard conversion sequence S1 is a better conversion sequence 4422 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 4423 4424 // -- S1 is a proper subsequence of S2 (comparing the conversion 4425 // sequences in the canonical form defined by 13.3.3.1.1, 4426 // excluding any Lvalue Transformation; the identity conversion 4427 // sequence is considered to be a subsequence of any 4428 // non-identity conversion sequence) or, if not that, 4429 if (ImplicitConversionSequence::CompareKind CK 4430 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 4431 return CK; 4432 4433 // -- the rank of S1 is better than the rank of S2 (by the rules 4434 // defined below), or, if not that, 4435 ImplicitConversionRank Rank1 = SCS1.getRank(); 4436 ImplicitConversionRank Rank2 = SCS2.getRank(); 4437 if (Rank1 < Rank2) 4438 return ImplicitConversionSequence::Better; 4439 else if (Rank2 < Rank1) 4440 return ImplicitConversionSequence::Worse; 4441 4442 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 4443 // are indistinguishable unless one of the following rules 4444 // applies: 4445 4446 // A conversion that is not a conversion of a pointer, or 4447 // pointer to member, to bool is better than another conversion 4448 // that is such a conversion. 4449 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 4450 return SCS2.isPointerConversionToBool() 4451 ? ImplicitConversionSequence::Better 4452 : ImplicitConversionSequence::Worse; 4453 4454 // C++14 [over.ics.rank]p4b2: 4455 // This is retroactively applied to C++11 by CWG 1601. 4456 // 4457 // A conversion that promotes an enumeration whose underlying type is fixed 4458 // to its underlying type is better than one that promotes to the promoted 4459 // underlying type, if the two are different. 4460 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 4461 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 4462 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 4463 FEP1 != FEP2) 4464 return FEP1 == FixedEnumPromotion::ToUnderlyingType 4465 ? ImplicitConversionSequence::Better 4466 : ImplicitConversionSequence::Worse; 4467 4468 // C++ [over.ics.rank]p4b2: 4469 // 4470 // If class B is derived directly or indirectly from class A, 4471 // conversion of B* to A* is better than conversion of B* to 4472 // void*, and conversion of A* to void* is better than conversion 4473 // of B* to void*. 4474 bool SCS1ConvertsToVoid 4475 = SCS1.isPointerConversionToVoidPointer(S.Context); 4476 bool SCS2ConvertsToVoid 4477 = SCS2.isPointerConversionToVoidPointer(S.Context); 4478 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4479 // Exactly one of the conversion sequences is a conversion to 4480 // a void pointer; it's the worse conversion. 4481 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4482 : ImplicitConversionSequence::Worse; 4483 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4484 // Neither conversion sequence converts to a void pointer; compare 4485 // their derived-to-base conversions. 4486 if (ImplicitConversionSequence::CompareKind DerivedCK 4487 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4488 return DerivedCK; 4489 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4490 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4491 // Both conversion sequences are conversions to void 4492 // pointers. Compare the source types to determine if there's an 4493 // inheritance relationship in their sources. 4494 QualType FromType1 = SCS1.getFromType(); 4495 QualType FromType2 = SCS2.getFromType(); 4496 4497 // Adjust the types we're converting from via the array-to-pointer 4498 // conversion, if we need to. 4499 if (SCS1.First == ICK_Array_To_Pointer) 4500 FromType1 = S.Context.getArrayDecayedType(FromType1); 4501 if (SCS2.First == ICK_Array_To_Pointer) 4502 FromType2 = S.Context.getArrayDecayedType(FromType2); 4503 4504 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4505 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4506 4507 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4508 return ImplicitConversionSequence::Better; 4509 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4510 return ImplicitConversionSequence::Worse; 4511 4512 // Objective-C++: If one interface is more specific than the 4513 // other, it is the better one. 4514 const ObjCObjectPointerType* FromObjCPtr1 4515 = FromType1->getAs<ObjCObjectPointerType>(); 4516 const ObjCObjectPointerType* FromObjCPtr2 4517 = FromType2->getAs<ObjCObjectPointerType>(); 4518 if (FromObjCPtr1 && FromObjCPtr2) { 4519 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4520 FromObjCPtr2); 4521 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4522 FromObjCPtr1); 4523 if (AssignLeft != AssignRight) { 4524 return AssignLeft? ImplicitConversionSequence::Better 4525 : ImplicitConversionSequence::Worse; 4526 } 4527 } 4528 } 4529 4530 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4531 // Check for a better reference binding based on the kind of bindings. 4532 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4533 return ImplicitConversionSequence::Better; 4534 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4535 return ImplicitConversionSequence::Worse; 4536 } 4537 4538 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4539 // bullet 3). 4540 if (ImplicitConversionSequence::CompareKind QualCK 4541 = CompareQualificationConversions(S, SCS1, SCS2)) 4542 return QualCK; 4543 4544 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4545 // C++ [over.ics.rank]p3b4: 4546 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4547 // which the references refer are the same type except for 4548 // top-level cv-qualifiers, and the type to which the reference 4549 // initialized by S2 refers is more cv-qualified than the type 4550 // to which the reference initialized by S1 refers. 4551 QualType T1 = SCS1.getToType(2); 4552 QualType T2 = SCS2.getToType(2); 4553 T1 = S.Context.getCanonicalType(T1); 4554 T2 = S.Context.getCanonicalType(T2); 4555 Qualifiers T1Quals, T2Quals; 4556 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4557 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4558 if (UnqualT1 == UnqualT2) { 4559 // Objective-C++ ARC: If the references refer to objects with different 4560 // lifetimes, prefer bindings that don't change lifetime. 4561 if (SCS1.ObjCLifetimeConversionBinding != 4562 SCS2.ObjCLifetimeConversionBinding) { 4563 return SCS1.ObjCLifetimeConversionBinding 4564 ? ImplicitConversionSequence::Worse 4565 : ImplicitConversionSequence::Better; 4566 } 4567 4568 // If the type is an array type, promote the element qualifiers to the 4569 // type for comparison. 4570 if (isa<ArrayType>(T1) && T1Quals) 4571 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4572 if (isa<ArrayType>(T2) && T2Quals) 4573 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4574 if (T2.isMoreQualifiedThan(T1, S.getASTContext())) 4575 return ImplicitConversionSequence::Better; 4576 if (T1.isMoreQualifiedThan(T2, S.getASTContext())) 4577 return ImplicitConversionSequence::Worse; 4578 } 4579 } 4580 4581 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4582 // floating-to-integral conversion if the integral conversion 4583 // is between types of the same size. 4584 // For example: 4585 // void f(float); 4586 // void f(int); 4587 // int main { 4588 // long a; 4589 // f(a); 4590 // } 4591 // Here, MSVC will call f(int) instead of generating a compile error 4592 // as clang will do in standard mode. 4593 if (S.getLangOpts().MSVCCompat && 4594 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4595 SCS1.Second == ICK_Integral_Conversion && 4596 SCS2.Second == ICK_Floating_Integral && 4597 S.Context.getTypeSize(SCS1.getFromType()) == 4598 S.Context.getTypeSize(SCS1.getToType(2))) 4599 return ImplicitConversionSequence::Better; 4600 4601 // Prefer a compatible vector conversion over a lax vector conversion 4602 // For example: 4603 // 4604 // typedef float __v4sf __attribute__((__vector_size__(16))); 4605 // void f(vector float); 4606 // void f(vector signed int); 4607 // int main() { 4608 // __v4sf a; 4609 // f(a); 4610 // } 4611 // Here, we'd like to choose f(vector float) and not 4612 // report an ambiguous call error 4613 if (SCS1.Second == ICK_Vector_Conversion && 4614 SCS2.Second == ICK_Vector_Conversion) { 4615 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4616 SCS1.getFromType(), SCS1.getToType(2)); 4617 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4618 SCS2.getFromType(), SCS2.getToType(2)); 4619 4620 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4621 return SCS1IsCompatibleVectorConversion 4622 ? ImplicitConversionSequence::Better 4623 : ImplicitConversionSequence::Worse; 4624 } 4625 4626 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4627 SCS2.Second == ICK_SVE_Vector_Conversion) { 4628 bool SCS1IsCompatibleSVEVectorConversion = 4629 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4630 bool SCS2IsCompatibleSVEVectorConversion = 4631 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4632 4633 if (SCS1IsCompatibleSVEVectorConversion != 4634 SCS2IsCompatibleSVEVectorConversion) 4635 return SCS1IsCompatibleSVEVectorConversion 4636 ? ImplicitConversionSequence::Better 4637 : ImplicitConversionSequence::Worse; 4638 } 4639 4640 if (SCS1.Second == ICK_RVV_Vector_Conversion && 4641 SCS2.Second == ICK_RVV_Vector_Conversion) { 4642 bool SCS1IsCompatibleRVVVectorConversion = 4643 S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2)); 4644 bool SCS2IsCompatibleRVVVectorConversion = 4645 S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2)); 4646 4647 if (SCS1IsCompatibleRVVVectorConversion != 4648 SCS2IsCompatibleRVVVectorConversion) 4649 return SCS1IsCompatibleRVVVectorConversion 4650 ? ImplicitConversionSequence::Better 4651 : ImplicitConversionSequence::Worse; 4652 } 4653 return ImplicitConversionSequence::Indistinguishable; 4654 } 4655 4656 /// CompareQualificationConversions - Compares two standard conversion 4657 /// sequences to determine whether they can be ranked based on their 4658 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4659 static ImplicitConversionSequence::CompareKind 4660 CompareQualificationConversions(Sema &S, 4661 const StandardConversionSequence& SCS1, 4662 const StandardConversionSequence& SCS2) { 4663 // C++ [over.ics.rank]p3: 4664 // -- S1 and S2 differ only in their qualification conversion and 4665 // yield similar types T1 and T2 (C++ 4.4), respectively, [...] 4666 // [C++98] 4667 // [...] and the cv-qualification signature of type T1 is a proper subset 4668 // of the cv-qualification signature of type T2, and S1 is not the 4669 // deprecated string literal array-to-pointer conversion (4.2). 4670 // [C++2a] 4671 // [...] where T1 can be converted to T2 by a qualification conversion. 4672 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4673 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4674 return ImplicitConversionSequence::Indistinguishable; 4675 4676 // FIXME: the example in the standard doesn't use a qualification 4677 // conversion (!) 4678 QualType T1 = SCS1.getToType(2); 4679 QualType T2 = SCS2.getToType(2); 4680 T1 = S.Context.getCanonicalType(T1); 4681 T2 = S.Context.getCanonicalType(T2); 4682 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4683 Qualifiers T1Quals, T2Quals; 4684 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4685 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4686 4687 // If the types are the same, we won't learn anything by unwrapping 4688 // them. 4689 if (UnqualT1 == UnqualT2) 4690 return ImplicitConversionSequence::Indistinguishable; 4691 4692 // Don't ever prefer a standard conversion sequence that uses the deprecated 4693 // string literal array to pointer conversion. 4694 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; 4695 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; 4696 4697 // Objective-C++ ARC: 4698 // Prefer qualification conversions not involving a change in lifetime 4699 // to qualification conversions that do change lifetime. 4700 if (SCS1.QualificationIncludesObjCLifetime && 4701 !SCS2.QualificationIncludesObjCLifetime) 4702 CanPick1 = false; 4703 if (SCS2.QualificationIncludesObjCLifetime && 4704 !SCS1.QualificationIncludesObjCLifetime) 4705 CanPick2 = false; 4706 4707 bool ObjCLifetimeConversion; 4708 if (CanPick1 && 4709 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) 4710 CanPick1 = false; 4711 // FIXME: In Objective-C ARC, we can have qualification conversions in both 4712 // directions, so we can't short-cut this second check in general. 4713 if (CanPick2 && 4714 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) 4715 CanPick2 = false; 4716 4717 if (CanPick1 != CanPick2) 4718 return CanPick1 ? ImplicitConversionSequence::Better 4719 : ImplicitConversionSequence::Worse; 4720 return ImplicitConversionSequence::Indistinguishable; 4721 } 4722 4723 /// CompareDerivedToBaseConversions - Compares two standard conversion 4724 /// sequences to determine whether they can be ranked based on their 4725 /// various kinds of derived-to-base conversions (C++ 4726 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4727 /// conversions between Objective-C interface types. 4728 static ImplicitConversionSequence::CompareKind 4729 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4730 const StandardConversionSequence& SCS1, 4731 const StandardConversionSequence& SCS2) { 4732 QualType FromType1 = SCS1.getFromType(); 4733 QualType ToType1 = SCS1.getToType(1); 4734 QualType FromType2 = SCS2.getFromType(); 4735 QualType ToType2 = SCS2.getToType(1); 4736 4737 // Adjust the types we're converting from via the array-to-pointer 4738 // conversion, if we need to. 4739 if (SCS1.First == ICK_Array_To_Pointer) 4740 FromType1 = S.Context.getArrayDecayedType(FromType1); 4741 if (SCS2.First == ICK_Array_To_Pointer) 4742 FromType2 = S.Context.getArrayDecayedType(FromType2); 4743 4744 // Canonicalize all of the types. 4745 FromType1 = S.Context.getCanonicalType(FromType1); 4746 ToType1 = S.Context.getCanonicalType(ToType1); 4747 FromType2 = S.Context.getCanonicalType(FromType2); 4748 ToType2 = S.Context.getCanonicalType(ToType2); 4749 4750 // C++ [over.ics.rank]p4b3: 4751 // 4752 // If class B is derived directly or indirectly from class A and 4753 // class C is derived directly or indirectly from B, 4754 // 4755 // Compare based on pointer conversions. 4756 if (SCS1.Second == ICK_Pointer_Conversion && 4757 SCS2.Second == ICK_Pointer_Conversion && 4758 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4759 FromType1->isPointerType() && FromType2->isPointerType() && 4760 ToType1->isPointerType() && ToType2->isPointerType()) { 4761 QualType FromPointee1 = 4762 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4763 QualType ToPointee1 = 4764 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4765 QualType FromPointee2 = 4766 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4767 QualType ToPointee2 = 4768 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4769 4770 // -- conversion of C* to B* is better than conversion of C* to A*, 4771 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4772 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4773 return ImplicitConversionSequence::Better; 4774 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4775 return ImplicitConversionSequence::Worse; 4776 } 4777 4778 // -- conversion of B* to A* is better than conversion of C* to A*, 4779 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4780 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4781 return ImplicitConversionSequence::Better; 4782 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4783 return ImplicitConversionSequence::Worse; 4784 } 4785 } else if (SCS1.Second == ICK_Pointer_Conversion && 4786 SCS2.Second == ICK_Pointer_Conversion) { 4787 const ObjCObjectPointerType *FromPtr1 4788 = FromType1->getAs<ObjCObjectPointerType>(); 4789 const ObjCObjectPointerType *FromPtr2 4790 = FromType2->getAs<ObjCObjectPointerType>(); 4791 const ObjCObjectPointerType *ToPtr1 4792 = ToType1->getAs<ObjCObjectPointerType>(); 4793 const ObjCObjectPointerType *ToPtr2 4794 = ToType2->getAs<ObjCObjectPointerType>(); 4795 4796 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4797 // Apply the same conversion ranking rules for Objective-C pointer types 4798 // that we do for C++ pointers to class types. However, we employ the 4799 // Objective-C pseudo-subtyping relationship used for assignment of 4800 // Objective-C pointer types. 4801 bool FromAssignLeft 4802 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4803 bool FromAssignRight 4804 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4805 bool ToAssignLeft 4806 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4807 bool ToAssignRight 4808 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4809 4810 // A conversion to an a non-id object pointer type or qualified 'id' 4811 // type is better than a conversion to 'id'. 4812 if (ToPtr1->isObjCIdType() && 4813 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4814 return ImplicitConversionSequence::Worse; 4815 if (ToPtr2->isObjCIdType() && 4816 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4817 return ImplicitConversionSequence::Better; 4818 4819 // A conversion to a non-id object pointer type is better than a 4820 // conversion to a qualified 'id' type 4821 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4822 return ImplicitConversionSequence::Worse; 4823 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4824 return ImplicitConversionSequence::Better; 4825 4826 // A conversion to an a non-Class object pointer type or qualified 'Class' 4827 // type is better than a conversion to 'Class'. 4828 if (ToPtr1->isObjCClassType() && 4829 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4830 return ImplicitConversionSequence::Worse; 4831 if (ToPtr2->isObjCClassType() && 4832 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4833 return ImplicitConversionSequence::Better; 4834 4835 // A conversion to a non-Class object pointer type is better than a 4836 // conversion to a qualified 'Class' type. 4837 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4838 return ImplicitConversionSequence::Worse; 4839 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4840 return ImplicitConversionSequence::Better; 4841 4842 // -- "conversion of C* to B* is better than conversion of C* to A*," 4843 if (S.Context.hasSameType(FromType1, FromType2) && 4844 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4845 (ToAssignLeft != ToAssignRight)) { 4846 if (FromPtr1->isSpecialized()) { 4847 // "conversion of B<A> * to B * is better than conversion of B * to 4848 // C *. 4849 bool IsFirstSame = 4850 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4851 bool IsSecondSame = 4852 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4853 if (IsFirstSame) { 4854 if (!IsSecondSame) 4855 return ImplicitConversionSequence::Better; 4856 } else if (IsSecondSame) 4857 return ImplicitConversionSequence::Worse; 4858 } 4859 return ToAssignLeft? ImplicitConversionSequence::Worse 4860 : ImplicitConversionSequence::Better; 4861 } 4862 4863 // -- "conversion of B* to A* is better than conversion of C* to A*," 4864 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4865 (FromAssignLeft != FromAssignRight)) 4866 return FromAssignLeft? ImplicitConversionSequence::Better 4867 : ImplicitConversionSequence::Worse; 4868 } 4869 } 4870 4871 // Ranking of member-pointer types. 4872 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4873 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4874 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4875 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4876 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4877 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4878 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4879 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4880 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4881 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4882 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4883 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4884 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4885 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4886 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4887 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4888 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4889 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4890 return ImplicitConversionSequence::Worse; 4891 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4892 return ImplicitConversionSequence::Better; 4893 } 4894 // conversion of B::* to C::* is better than conversion of A::* to C::* 4895 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4896 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4897 return ImplicitConversionSequence::Better; 4898 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4899 return ImplicitConversionSequence::Worse; 4900 } 4901 } 4902 4903 if (SCS1.Second == ICK_Derived_To_Base) { 4904 // -- conversion of C to B is better than conversion of C to A, 4905 // -- binding of an expression of type C to a reference of type 4906 // B& is better than binding an expression of type C to a 4907 // reference of type A&, 4908 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4909 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4910 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4911 return ImplicitConversionSequence::Better; 4912 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4913 return ImplicitConversionSequence::Worse; 4914 } 4915 4916 // -- conversion of B to A is better than conversion of C to A. 4917 // -- binding of an expression of type B to a reference of type 4918 // A& is better than binding an expression of type C to a 4919 // reference of type A&, 4920 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4921 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4922 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4923 return ImplicitConversionSequence::Better; 4924 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4925 return ImplicitConversionSequence::Worse; 4926 } 4927 } 4928 4929 return ImplicitConversionSequence::Indistinguishable; 4930 } 4931 4932 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4933 if (!T.getQualifiers().hasUnaligned()) 4934 return T; 4935 4936 Qualifiers Q; 4937 T = Ctx.getUnqualifiedArrayType(T, Q); 4938 Q.removeUnaligned(); 4939 return Ctx.getQualifiedType(T, Q); 4940 } 4941 4942 Sema::ReferenceCompareResult 4943 Sema::CompareReferenceRelationship(SourceLocation Loc, 4944 QualType OrigT1, QualType OrigT2, 4945 ReferenceConversions *ConvOut) { 4946 assert(!OrigT1->isReferenceType() && 4947 "T1 must be the pointee type of the reference type"); 4948 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4949 4950 QualType T1 = Context.getCanonicalType(OrigT1); 4951 QualType T2 = Context.getCanonicalType(OrigT2); 4952 Qualifiers T1Quals, T2Quals; 4953 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4954 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4955 4956 ReferenceConversions ConvTmp; 4957 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4958 Conv = ReferenceConversions(); 4959 4960 // C++2a [dcl.init.ref]p4: 4961 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4962 // reference-related to "cv2 T2" if T1 is similar to T2, or 4963 // T1 is a base class of T2. 4964 // "cv1 T1" is reference-compatible with "cv2 T2" if 4965 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4966 // "pointer to cv1 T1" via a standard conversion sequence. 4967 4968 // Check for standard conversions we can apply to pointers: derived-to-base 4969 // conversions, ObjC pointer conversions, and function pointer conversions. 4970 // (Qualification conversions are checked last.) 4971 QualType ConvertedT2; 4972 if (UnqualT1 == UnqualT2) { 4973 // Nothing to do. 4974 } else if (isCompleteType(Loc, OrigT2) && 4975 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4976 Conv |= ReferenceConversions::DerivedToBase; 4977 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4978 UnqualT2->isObjCObjectOrInterfaceType() && 4979 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4980 Conv |= ReferenceConversions::ObjC; 4981 else if (UnqualT2->isFunctionType() && 4982 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4983 Conv |= ReferenceConversions::Function; 4984 // No need to check qualifiers; function types don't have them. 4985 return Ref_Compatible; 4986 } 4987 bool ConvertedReferent = Conv != 0; 4988 4989 // We can have a qualification conversion. Compute whether the types are 4990 // similar at the same time. 4991 bool PreviousToQualsIncludeConst = true; 4992 bool TopLevel = true; 4993 do { 4994 if (T1 == T2) 4995 break; 4996 4997 // We will need a qualification conversion. 4998 Conv |= ReferenceConversions::Qualification; 4999 5000 // Track whether we performed a qualification conversion anywhere other 5001 // than the top level. This matters for ranking reference bindings in 5002 // overload resolution. 5003 if (!TopLevel) 5004 Conv |= ReferenceConversions::NestedQualification; 5005 5006 // MS compiler ignores __unaligned qualifier for references; do the same. 5007 T1 = withoutUnaligned(Context, T1); 5008 T2 = withoutUnaligned(Context, T2); 5009 5010 // If we find a qualifier mismatch, the types are not reference-compatible, 5011 // but are still be reference-related if they're similar. 5012 bool ObjCLifetimeConversion = false; 5013 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 5014 PreviousToQualsIncludeConst, 5015 ObjCLifetimeConversion, getASTContext())) 5016 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 5017 ? Ref_Related 5018 : Ref_Incompatible; 5019 5020 // FIXME: Should we track this for any level other than the first? 5021 if (ObjCLifetimeConversion) 5022 Conv |= ReferenceConversions::ObjCLifetime; 5023 5024 TopLevel = false; 5025 } while (Context.UnwrapSimilarTypes(T1, T2)); 5026 5027 // At this point, if the types are reference-related, we must either have the 5028 // same inner type (ignoring qualifiers), or must have already worked out how 5029 // to convert the referent. 5030 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 5031 ? Ref_Compatible 5032 : Ref_Incompatible; 5033 } 5034 5035 /// Look for a user-defined conversion to a value reference-compatible 5036 /// with DeclType. Return true if something definite is found. 5037 static bool 5038 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 5039 QualType DeclType, SourceLocation DeclLoc, 5040 Expr *Init, QualType T2, bool AllowRvalues, 5041 bool AllowExplicit) { 5042 assert(T2->isRecordType() && "Can only find conversions of record types."); 5043 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 5044 5045 OverloadCandidateSet CandidateSet( 5046 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 5047 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 5048 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5049 NamedDecl *D = *I; 5050 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 5051 if (isa<UsingShadowDecl>(D)) 5052 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5053 5054 FunctionTemplateDecl *ConvTemplate 5055 = dyn_cast<FunctionTemplateDecl>(D); 5056 CXXConversionDecl *Conv; 5057 if (ConvTemplate) 5058 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5059 else 5060 Conv = cast<CXXConversionDecl>(D); 5061 5062 if (AllowRvalues) { 5063 // If we are initializing an rvalue reference, don't permit conversion 5064 // functions that return lvalues. 5065 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 5066 const ReferenceType *RefType 5067 = Conv->getConversionType()->getAs<LValueReferenceType>(); 5068 if (RefType && !RefType->getPointeeType()->isFunctionType()) 5069 continue; 5070 } 5071 5072 if (!ConvTemplate && 5073 S.CompareReferenceRelationship( 5074 DeclLoc, 5075 Conv->getConversionType() 5076 .getNonReferenceType() 5077 .getUnqualifiedType(), 5078 DeclType.getNonReferenceType().getUnqualifiedType()) == 5079 Sema::Ref_Incompatible) 5080 continue; 5081 } else { 5082 // If the conversion function doesn't return a reference type, 5083 // it can't be considered for this conversion. An rvalue reference 5084 // is only acceptable if its referencee is a function type. 5085 5086 const ReferenceType *RefType = 5087 Conv->getConversionType()->getAs<ReferenceType>(); 5088 if (!RefType || 5089 (!RefType->isLValueReferenceType() && 5090 !RefType->getPointeeType()->isFunctionType())) 5091 continue; 5092 } 5093 5094 if (ConvTemplate) 5095 S.AddTemplateConversionCandidate( 5096 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 5097 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 5098 else 5099 S.AddConversionCandidate( 5100 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 5101 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 5102 } 5103 5104 bool HadMultipleCandidates = (CandidateSet.size() > 1); 5105 5106 OverloadCandidateSet::iterator Best; 5107 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 5108 case OR_Success: 5109 // C++ [over.ics.ref]p1: 5110 // 5111 // [...] If the parameter binds directly to the result of 5112 // applying a conversion function to the argument 5113 // expression, the implicit conversion sequence is a 5114 // user-defined conversion sequence (13.3.3.1.2), with the 5115 // second standard conversion sequence either an identity 5116 // conversion or, if the conversion function returns an 5117 // entity of a type that is a derived class of the parameter 5118 // type, a derived-to-base Conversion. 5119 if (!Best->FinalConversion.DirectBinding) 5120 return false; 5121 5122 ICS.setUserDefined(); 5123 ICS.UserDefined.Before = Best->Conversions[0].Standard; 5124 ICS.UserDefined.After = Best->FinalConversion; 5125 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 5126 ICS.UserDefined.ConversionFunction = Best->Function; 5127 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 5128 ICS.UserDefined.EllipsisConversion = false; 5129 assert(ICS.UserDefined.After.ReferenceBinding && 5130 ICS.UserDefined.After.DirectBinding && 5131 "Expected a direct reference binding!"); 5132 return true; 5133 5134 case OR_Ambiguous: 5135 ICS.setAmbiguous(); 5136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 5137 Cand != CandidateSet.end(); ++Cand) 5138 if (Cand->Best) 5139 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 5140 return true; 5141 5142 case OR_No_Viable_Function: 5143 case OR_Deleted: 5144 // There was no suitable conversion, or we found a deleted 5145 // conversion; continue with other checks. 5146 return false; 5147 } 5148 5149 llvm_unreachable("Invalid OverloadResult!"); 5150 } 5151 5152 /// Compute an implicit conversion sequence for reference 5153 /// initialization. 5154 static ImplicitConversionSequence 5155 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 5156 SourceLocation DeclLoc, 5157 bool SuppressUserConversions, 5158 bool AllowExplicit) { 5159 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 5160 5161 // Most paths end in a failed conversion. 5162 ImplicitConversionSequence ICS; 5163 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5164 5165 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 5166 QualType T2 = Init->getType(); 5167 5168 // If the initializer is the address of an overloaded function, try 5169 // to resolve the overloaded function. If all goes well, T2 is the 5170 // type of the resulting function. 5171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5172 DeclAccessPair Found; 5173 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 5174 false, Found)) 5175 T2 = Fn->getType(); 5176 } 5177 5178 // Compute some basic properties of the types and the initializer. 5179 bool isRValRef = DeclType->isRValueReferenceType(); 5180 Expr::Classification InitCategory = Init->Classify(S.Context); 5181 5182 Sema::ReferenceConversions RefConv; 5183 Sema::ReferenceCompareResult RefRelationship = 5184 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 5185 5186 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 5187 ICS.setStandard(); 5188 ICS.Standard.First = ICK_Identity; 5189 // FIXME: A reference binding can be a function conversion too. We should 5190 // consider that when ordering reference-to-function bindings. 5191 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 5192 ? ICK_Derived_To_Base 5193 : (RefConv & Sema::ReferenceConversions::ObjC) 5194 ? ICK_Compatible_Conversion 5195 : ICK_Identity; 5196 ICS.Standard.Dimension = ICK_Identity; 5197 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 5198 // a reference binding that performs a non-top-level qualification 5199 // conversion as a qualification conversion, not as an identity conversion. 5200 ICS.Standard.Third = (RefConv & 5201 Sema::ReferenceConversions::NestedQualification) 5202 ? ICK_Qualification 5203 : ICK_Identity; 5204 ICS.Standard.setFromType(T2); 5205 ICS.Standard.setToType(0, T2); 5206 ICS.Standard.setToType(1, T1); 5207 ICS.Standard.setToType(2, T1); 5208 ICS.Standard.ReferenceBinding = true; 5209 ICS.Standard.DirectBinding = BindsDirectly; 5210 ICS.Standard.IsLvalueReference = !isRValRef; 5211 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 5212 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 5213 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5214 ICS.Standard.ObjCLifetimeConversionBinding = 5215 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 5216 ICS.Standard.CopyConstructor = nullptr; 5217 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 5218 }; 5219 5220 // C++0x [dcl.init.ref]p5: 5221 // A reference to type "cv1 T1" is initialized by an expression 5222 // of type "cv2 T2" as follows: 5223 5224 // -- If reference is an lvalue reference and the initializer expression 5225 if (!isRValRef) { 5226 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 5227 // reference-compatible with "cv2 T2," or 5228 // 5229 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 5230 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 5231 // C++ [over.ics.ref]p1: 5232 // When a parameter of reference type binds directly (8.5.3) 5233 // to an argument expression, the implicit conversion sequence 5234 // is the identity conversion, unless the argument expression 5235 // has a type that is a derived class of the parameter type, 5236 // in which case the implicit conversion sequence is a 5237 // derived-to-base Conversion (13.3.3.1). 5238 SetAsReferenceBinding(/*BindsDirectly=*/true); 5239 5240 // Nothing more to do: the inaccessibility/ambiguity check for 5241 // derived-to-base conversions is suppressed when we're 5242 // computing the implicit conversion sequence (C++ 5243 // [over.best.ics]p2). 5244 return ICS; 5245 } 5246 5247 // -- has a class type (i.e., T2 is a class type), where T1 is 5248 // not reference-related to T2, and can be implicitly 5249 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 5250 // is reference-compatible with "cv3 T3" 92) (this 5251 // conversion is selected by enumerating the applicable 5252 // conversion functions (13.3.1.6) and choosing the best 5253 // one through overload resolution (13.3)), 5254 if (!SuppressUserConversions && T2->isRecordType() && 5255 S.isCompleteType(DeclLoc, T2) && 5256 RefRelationship == Sema::Ref_Incompatible) { 5257 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 5258 Init, T2, /*AllowRvalues=*/false, 5259 AllowExplicit)) 5260 return ICS; 5261 } 5262 } 5263 5264 // -- Otherwise, the reference shall be an lvalue reference to a 5265 // non-volatile const type (i.e., cv1 shall be const), or the reference 5266 // shall be an rvalue reference. 5267 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 5268 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 5269 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 5270 return ICS; 5271 } 5272 5273 // -- If the initializer expression 5274 // 5275 // -- is an xvalue, class prvalue, array prvalue or function 5276 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 5277 if (RefRelationship == Sema::Ref_Compatible && 5278 (InitCategory.isXValue() || 5279 (InitCategory.isPRValue() && 5280 (T2->isRecordType() || T2->isArrayType())) || 5281 (InitCategory.isLValue() && T2->isFunctionType()))) { 5282 // In C++11, this is always a direct binding. In C++98/03, it's a direct 5283 // binding unless we're binding to a class prvalue. 5284 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 5285 // allow the use of rvalue references in C++98/03 for the benefit of 5286 // standard library implementors; therefore, we need the xvalue check here. 5287 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 5288 !(InitCategory.isPRValue() || T2->isRecordType())); 5289 return ICS; 5290 } 5291 5292 // -- has a class type (i.e., T2 is a class type), where T1 is not 5293 // reference-related to T2, and can be implicitly converted to 5294 // an xvalue, class prvalue, or function lvalue of type 5295 // "cv3 T3", where "cv1 T1" is reference-compatible with 5296 // "cv3 T3", 5297 // 5298 // then the reference is bound to the value of the initializer 5299 // expression in the first case and to the result of the conversion 5300 // in the second case (or, in either case, to an appropriate base 5301 // class subobject). 5302 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 5303 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 5304 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 5305 Init, T2, /*AllowRvalues=*/true, 5306 AllowExplicit)) { 5307 // In the second case, if the reference is an rvalue reference 5308 // and the second standard conversion sequence of the 5309 // user-defined conversion sequence includes an lvalue-to-rvalue 5310 // conversion, the program is ill-formed. 5311 if (ICS.isUserDefined() && isRValRef && 5312 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 5313 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5314 5315 return ICS; 5316 } 5317 5318 // A temporary of function type cannot be created; don't even try. 5319 if (T1->isFunctionType()) 5320 return ICS; 5321 5322 // -- Otherwise, a temporary of type "cv1 T1" is created and 5323 // initialized from the initializer expression using the 5324 // rules for a non-reference copy initialization (8.5). The 5325 // reference is then bound to the temporary. If T1 is 5326 // reference-related to T2, cv1 must be the same 5327 // cv-qualification as, or greater cv-qualification than, 5328 // cv2; otherwise, the program is ill-formed. 5329 if (RefRelationship == Sema::Ref_Related) { 5330 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 5331 // we would be reference-compatible or reference-compatible with 5332 // added qualification. But that wasn't the case, so the reference 5333 // initialization fails. 5334 // 5335 // Note that we only want to check address spaces and cvr-qualifiers here. 5336 // ObjC GC, lifetime and unaligned qualifiers aren't important. 5337 Qualifiers T1Quals = T1.getQualifiers(); 5338 Qualifiers T2Quals = T2.getQualifiers(); 5339 T1Quals.removeObjCGCAttr(); 5340 T1Quals.removeObjCLifetime(); 5341 T2Quals.removeObjCGCAttr(); 5342 T2Quals.removeObjCLifetime(); 5343 // MS compiler ignores __unaligned qualifier for references; do the same. 5344 T1Quals.removeUnaligned(); 5345 T2Quals.removeUnaligned(); 5346 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext())) 5347 return ICS; 5348 } 5349 5350 // If at least one of the types is a class type, the types are not 5351 // related, and we aren't allowed any user conversions, the 5352 // reference binding fails. This case is important for breaking 5353 // recursion, since TryImplicitConversion below will attempt to 5354 // create a temporary through the use of a copy constructor. 5355 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 5356 (T1->isRecordType() || T2->isRecordType())) 5357 return ICS; 5358 5359 // If T1 is reference-related to T2 and the reference is an rvalue 5360 // reference, the initializer expression shall not be an lvalue. 5361 if (RefRelationship >= Sema::Ref_Related && isRValRef && 5362 Init->Classify(S.Context).isLValue()) { 5363 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 5364 return ICS; 5365 } 5366 5367 // C++ [over.ics.ref]p2: 5368 // When a parameter of reference type is not bound directly to 5369 // an argument expression, the conversion sequence is the one 5370 // required to convert the argument expression to the 5371 // underlying type of the reference according to 5372 // 13.3.3.1. Conceptually, this conversion sequence corresponds 5373 // to copy-initializing a temporary of the underlying type with 5374 // the argument expression. Any difference in top-level 5375 // cv-qualification is subsumed by the initialization itself 5376 // and does not constitute a conversion. 5377 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 5378 AllowedExplicit::None, 5379 /*InOverloadResolution=*/false, 5380 /*CStyle=*/false, 5381 /*AllowObjCWritebackConversion=*/false, 5382 /*AllowObjCConversionOnExplicit=*/false); 5383 5384 // Of course, that's still a reference binding. 5385 if (ICS.isStandard()) { 5386 ICS.Standard.ReferenceBinding = true; 5387 ICS.Standard.IsLvalueReference = !isRValRef; 5388 ICS.Standard.BindsToFunctionLvalue = false; 5389 ICS.Standard.BindsToRvalue = true; 5390 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5391 ICS.Standard.ObjCLifetimeConversionBinding = false; 5392 } else if (ICS.isUserDefined()) { 5393 const ReferenceType *LValRefType = 5394 ICS.UserDefined.ConversionFunction->getReturnType() 5395 ->getAs<LValueReferenceType>(); 5396 5397 // C++ [over.ics.ref]p3: 5398 // Except for an implicit object parameter, for which see 13.3.1, a 5399 // standard conversion sequence cannot be formed if it requires [...] 5400 // binding an rvalue reference to an lvalue other than a function 5401 // lvalue. 5402 // Note that the function case is not possible here. 5403 if (isRValRef && LValRefType) { 5404 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5405 return ICS; 5406 } 5407 5408 ICS.UserDefined.After.ReferenceBinding = true; 5409 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 5410 ICS.UserDefined.After.BindsToFunctionLvalue = false; 5411 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 5412 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5413 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 5414 } 5415 5416 return ICS; 5417 } 5418 5419 static ImplicitConversionSequence 5420 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5421 bool SuppressUserConversions, 5422 bool InOverloadResolution, 5423 bool AllowObjCWritebackConversion, 5424 bool AllowExplicit = false); 5425 5426 /// TryListConversion - Try to copy-initialize a value of type ToType from the 5427 /// initializer list From. 5428 static ImplicitConversionSequence 5429 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5430 bool SuppressUserConversions, 5431 bool InOverloadResolution, 5432 bool AllowObjCWritebackConversion) { 5433 // C++11 [over.ics.list]p1: 5434 // When an argument is an initializer list, it is not an expression and 5435 // special rules apply for converting it to a parameter type. 5436 5437 ImplicitConversionSequence Result; 5438 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5439 5440 // We need a complete type for what follows. With one C++20 exception, 5441 // incomplete types can never be initialized from init lists. 5442 QualType InitTy = ToType; 5443 const ArrayType *AT = S.Context.getAsArrayType(ToType); 5444 if (AT && S.getLangOpts().CPlusPlus20) 5445 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) 5446 // C++20 allows list initialization of an incomplete array type. 5447 InitTy = IAT->getElementType(); 5448 if (!S.isCompleteType(From->getBeginLoc(), InitTy)) 5449 return Result; 5450 5451 // C++20 [over.ics.list]/2: 5452 // If the initializer list is a designated-initializer-list, a conversion 5453 // is only possible if the parameter has an aggregate type 5454 // 5455 // FIXME: The exception for reference initialization here is not part of the 5456 // language rules, but follow other compilers in adding it as a tentative DR 5457 // resolution. 5458 bool IsDesignatedInit = From->hasDesignatedInit(); 5459 if (!ToType->isAggregateType() && !ToType->isReferenceType() && 5460 IsDesignatedInit) 5461 return Result; 5462 5463 // Per DR1467 and DR2137: 5464 // If the parameter type is an aggregate class X and the initializer list 5465 // has a single element of type cv U, where U is X or a class derived from 5466 // X, the implicit conversion sequence is the one required to convert the 5467 // element to the parameter type. 5468 // 5469 // Otherwise, if the parameter type is a character array [... ] 5470 // and the initializer list has a single element that is an 5471 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5472 // implicit conversion sequence is the identity conversion. 5473 if (From->getNumInits() == 1 && !IsDesignatedInit) { 5474 if (ToType->isRecordType() && ToType->isAggregateType()) { 5475 QualType InitType = From->getInit(0)->getType(); 5476 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5477 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5478 return TryCopyInitialization(S, From->getInit(0), ToType, 5479 SuppressUserConversions, 5480 InOverloadResolution, 5481 AllowObjCWritebackConversion); 5482 } 5483 5484 if (AT && S.IsStringInit(From->getInit(0), AT)) { 5485 InitializedEntity Entity = 5486 InitializedEntity::InitializeParameter(S.Context, ToType, 5487 /*Consumed=*/false); 5488 if (S.CanPerformCopyInitialization(Entity, From)) { 5489 Result.setStandard(); 5490 Result.Standard.setAsIdentityConversion(); 5491 Result.Standard.setFromType(ToType); 5492 Result.Standard.setAllToTypes(ToType); 5493 return Result; 5494 } 5495 } 5496 } 5497 5498 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5499 // C++11 [over.ics.list]p2: 5500 // If the parameter type is std::initializer_list<X> or "array of X" and 5501 // all the elements can be implicitly converted to X, the implicit 5502 // conversion sequence is the worst conversion necessary to convert an 5503 // element of the list to X. 5504 // 5505 // C++14 [over.ics.list]p3: 5506 // Otherwise, if the parameter type is "array of N X", if the initializer 5507 // list has exactly N elements or if it has fewer than N elements and X is 5508 // default-constructible, and if all the elements of the initializer list 5509 // can be implicitly converted to X, the implicit conversion sequence is 5510 // the worst conversion necessary to convert an element of the list to X. 5511 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) { 5512 unsigned e = From->getNumInits(); 5513 ImplicitConversionSequence DfltElt; 5514 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), 5515 QualType()); 5516 QualType ContTy = ToType; 5517 bool IsUnbounded = false; 5518 if (AT) { 5519 InitTy = AT->getElementType(); 5520 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { 5521 if (CT->getSize().ult(e)) { 5522 // Too many inits, fatally bad 5523 Result.setBad(BadConversionSequence::too_many_initializers, From, 5524 ToType); 5525 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5526 return Result; 5527 } 5528 if (CT->getSize().ugt(e)) { 5529 // Need an init from empty {}, is there one? 5530 InitListExpr EmptyList(S.Context, From->getEndLoc(), {}, 5531 From->getEndLoc()); 5532 EmptyList.setType(S.Context.VoidTy); 5533 DfltElt = TryListConversion( 5534 S, &EmptyList, InitTy, SuppressUserConversions, 5535 InOverloadResolution, AllowObjCWritebackConversion); 5536 if (DfltElt.isBad()) { 5537 // No {} init, fatally bad 5538 Result.setBad(BadConversionSequence::too_few_initializers, From, 5539 ToType); 5540 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5541 return Result; 5542 } 5543 } 5544 } else { 5545 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); 5546 IsUnbounded = true; 5547 if (!e) { 5548 // Cannot convert to zero-sized. 5549 Result.setBad(BadConversionSequence::too_few_initializers, From, 5550 ToType); 5551 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5552 return Result; 5553 } 5554 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); 5555 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, 5556 ArraySizeModifier::Normal, 0); 5557 } 5558 } 5559 5560 Result.setStandard(); 5561 Result.Standard.setAsIdentityConversion(); 5562 Result.Standard.setFromType(InitTy); 5563 Result.Standard.setAllToTypes(InitTy); 5564 for (unsigned i = 0; i < e; ++i) { 5565 Expr *Init = From->getInit(i); 5566 ImplicitConversionSequence ICS = TryCopyInitialization( 5567 S, Init, InitTy, SuppressUserConversions, InOverloadResolution, 5568 AllowObjCWritebackConversion); 5569 5570 // Keep the worse conversion seen so far. 5571 // FIXME: Sequences are not totally ordered, so 'worse' can be 5572 // ambiguous. CWG has been informed. 5573 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, 5574 Result) == 5575 ImplicitConversionSequence::Worse) { 5576 Result = ICS; 5577 // Bail as soon as we find something unconvertible. 5578 if (Result.isBad()) { 5579 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5580 return Result; 5581 } 5582 } 5583 } 5584 5585 // If we needed any implicit {} initialization, compare that now. 5586 // over.ics.list/6 indicates we should compare that conversion. Again CWG 5587 // has been informed that this might not be the best thing. 5588 if (!DfltElt.isBad() && CompareImplicitConversionSequences( 5589 S, From->getEndLoc(), DfltElt, Result) == 5590 ImplicitConversionSequence::Worse) 5591 Result = DfltElt; 5592 // Record the type being initialized so that we may compare sequences 5593 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5594 return Result; 5595 } 5596 5597 // C++14 [over.ics.list]p4: 5598 // C++11 [over.ics.list]p3: 5599 // Otherwise, if the parameter is a non-aggregate class X and overload 5600 // resolution chooses a single best constructor [...] the implicit 5601 // conversion sequence is a user-defined conversion sequence. If multiple 5602 // constructors are viable but none is better than the others, the 5603 // implicit conversion sequence is a user-defined conversion sequence. 5604 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5605 // This function can deal with initializer lists. 5606 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5607 AllowedExplicit::None, 5608 InOverloadResolution, /*CStyle=*/false, 5609 AllowObjCWritebackConversion, 5610 /*AllowObjCConversionOnExplicit=*/false); 5611 } 5612 5613 // C++14 [over.ics.list]p5: 5614 // C++11 [over.ics.list]p4: 5615 // Otherwise, if the parameter has an aggregate type which can be 5616 // initialized from the initializer list [...] the implicit conversion 5617 // sequence is a user-defined conversion sequence. 5618 if (ToType->isAggregateType()) { 5619 // Type is an aggregate, argument is an init list. At this point it comes 5620 // down to checking whether the initialization works. 5621 // FIXME: Find out whether this parameter is consumed or not. 5622 InitializedEntity Entity = 5623 InitializedEntity::InitializeParameter(S.Context, ToType, 5624 /*Consumed=*/false); 5625 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5626 From)) { 5627 Result.setUserDefined(); 5628 Result.UserDefined.Before.setAsIdentityConversion(); 5629 // Initializer lists don't have a type. 5630 Result.UserDefined.Before.setFromType(QualType()); 5631 Result.UserDefined.Before.setAllToTypes(QualType()); 5632 5633 Result.UserDefined.After.setAsIdentityConversion(); 5634 Result.UserDefined.After.setFromType(ToType); 5635 Result.UserDefined.After.setAllToTypes(ToType); 5636 Result.UserDefined.ConversionFunction = nullptr; 5637 } 5638 return Result; 5639 } 5640 5641 // C++14 [over.ics.list]p6: 5642 // C++11 [over.ics.list]p5: 5643 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5644 if (ToType->isReferenceType()) { 5645 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5646 // mention initializer lists in any way. So we go by what list- 5647 // initialization would do and try to extrapolate from that. 5648 5649 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5650 5651 // If the initializer list has a single element that is reference-related 5652 // to the parameter type, we initialize the reference from that. 5653 if (From->getNumInits() == 1 && !IsDesignatedInit) { 5654 Expr *Init = From->getInit(0); 5655 5656 QualType T2 = Init->getType(); 5657 5658 // If the initializer is the address of an overloaded function, try 5659 // to resolve the overloaded function. If all goes well, T2 is the 5660 // type of the resulting function. 5661 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5662 DeclAccessPair Found; 5663 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5664 Init, ToType, false, Found)) 5665 T2 = Fn->getType(); 5666 } 5667 5668 // Compute some basic properties of the types and the initializer. 5669 Sema::ReferenceCompareResult RefRelationship = 5670 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5671 5672 if (RefRelationship >= Sema::Ref_Related) { 5673 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5674 SuppressUserConversions, 5675 /*AllowExplicit=*/false); 5676 } 5677 } 5678 5679 // Otherwise, we bind the reference to a temporary created from the 5680 // initializer list. 5681 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5682 InOverloadResolution, 5683 AllowObjCWritebackConversion); 5684 if (Result.isFailure()) 5685 return Result; 5686 assert(!Result.isEllipsis() && 5687 "Sub-initialization cannot result in ellipsis conversion."); 5688 5689 // Can we even bind to a temporary? 5690 if (ToType->isRValueReferenceType() || 5691 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5692 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5693 Result.UserDefined.After; 5694 SCS.ReferenceBinding = true; 5695 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5696 SCS.BindsToRvalue = true; 5697 SCS.BindsToFunctionLvalue = false; 5698 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5699 SCS.ObjCLifetimeConversionBinding = false; 5700 } else 5701 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5702 From, ToType); 5703 return Result; 5704 } 5705 5706 // C++14 [over.ics.list]p7: 5707 // C++11 [over.ics.list]p6: 5708 // Otherwise, if the parameter type is not a class: 5709 if (!ToType->isRecordType()) { 5710 // - if the initializer list has one element that is not itself an 5711 // initializer list, the implicit conversion sequence is the one 5712 // required to convert the element to the parameter type. 5713 unsigned NumInits = From->getNumInits(); 5714 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5715 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5716 SuppressUserConversions, 5717 InOverloadResolution, 5718 AllowObjCWritebackConversion); 5719 // - if the initializer list has no elements, the implicit conversion 5720 // sequence is the identity conversion. 5721 else if (NumInits == 0) { 5722 Result.setStandard(); 5723 Result.Standard.setAsIdentityConversion(); 5724 Result.Standard.setFromType(ToType); 5725 Result.Standard.setAllToTypes(ToType); 5726 } 5727 return Result; 5728 } 5729 5730 // C++14 [over.ics.list]p8: 5731 // C++11 [over.ics.list]p7: 5732 // In all cases other than those enumerated above, no conversion is possible 5733 return Result; 5734 } 5735 5736 /// TryCopyInitialization - Try to copy-initialize a value of type 5737 /// ToType from the expression From. Return the implicit conversion 5738 /// sequence required to pass this argument, which may be a bad 5739 /// conversion sequence (meaning that the argument cannot be passed to 5740 /// a parameter of this type). If @p SuppressUserConversions, then we 5741 /// do not permit any user-defined conversion sequences. 5742 static ImplicitConversionSequence 5743 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5744 bool SuppressUserConversions, 5745 bool InOverloadResolution, 5746 bool AllowObjCWritebackConversion, 5747 bool AllowExplicit) { 5748 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5749 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5750 InOverloadResolution,AllowObjCWritebackConversion); 5751 5752 if (ToType->isReferenceType()) 5753 return TryReferenceInit(S, From, ToType, 5754 /*FIXME:*/ From->getBeginLoc(), 5755 SuppressUserConversions, AllowExplicit); 5756 5757 return TryImplicitConversion(S, From, ToType, 5758 SuppressUserConversions, 5759 AllowedExplicit::None, 5760 InOverloadResolution, 5761 /*CStyle=*/false, 5762 AllowObjCWritebackConversion, 5763 /*AllowObjCConversionOnExplicit=*/false); 5764 } 5765 5766 static bool TryCopyInitialization(const CanQualType FromQTy, 5767 const CanQualType ToQTy, 5768 Sema &S, 5769 SourceLocation Loc, 5770 ExprValueKind FromVK) { 5771 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5772 ImplicitConversionSequence ICS = 5773 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5774 5775 return !ICS.isBad(); 5776 } 5777 5778 /// TryObjectArgumentInitialization - Try to initialize the object 5779 /// parameter of the given member function (@c Method) from the 5780 /// expression @p From. 5781 static ImplicitConversionSequence TryObjectArgumentInitialization( 5782 Sema &S, SourceLocation Loc, QualType FromType, 5783 Expr::Classification FromClassification, CXXMethodDecl *Method, 5784 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false, 5785 QualType ExplicitParameterType = QualType(), 5786 bool SuppressUserConversion = false) { 5787 5788 // We need to have an object of class type. 5789 if (const auto *PT = FromType->getAs<PointerType>()) { 5790 FromType = PT->getPointeeType(); 5791 5792 // When we had a pointer, it's implicitly dereferenced, so we 5793 // better have an lvalue. 5794 assert(FromClassification.isLValue()); 5795 } 5796 5797 auto ValueKindFromClassification = [](Expr::Classification C) { 5798 if (C.isPRValue()) 5799 return clang::VK_PRValue; 5800 if (C.isXValue()) 5801 return VK_XValue; 5802 return clang::VK_LValue; 5803 }; 5804 5805 if (Method->isExplicitObjectMemberFunction()) { 5806 if (ExplicitParameterType.isNull()) 5807 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType(); 5808 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(), 5809 ValueKindFromClassification(FromClassification)); 5810 ImplicitConversionSequence ICS = TryCopyInitialization( 5811 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion, 5812 /*InOverloadResolution=*/true, false); 5813 if (ICS.isBad()) 5814 ICS.Bad.FromExpr = nullptr; 5815 return ICS; 5816 } 5817 5818 assert(FromType->isRecordType()); 5819 5820 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5821 // C++98 [class.dtor]p2: 5822 // A destructor can be invoked for a const, volatile or const volatile 5823 // object. 5824 // C++98 [over.match.funcs]p4: 5825 // For static member functions, the implicit object parameter is considered 5826 // to match any object (since if the function is selected, the object is 5827 // discarded). 5828 Qualifiers Quals = Method->getMethodQualifiers(); 5829 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) { 5830 Quals.addConst(); 5831 Quals.addVolatile(); 5832 } 5833 5834 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5835 5836 // Set up the conversion sequence as a "bad" conversion, to allow us 5837 // to exit early. 5838 ImplicitConversionSequence ICS; 5839 5840 // C++0x [over.match.funcs]p4: 5841 // For non-static member functions, the type of the implicit object 5842 // parameter is 5843 // 5844 // - "lvalue reference to cv X" for functions declared without a 5845 // ref-qualifier or with the & ref-qualifier 5846 // - "rvalue reference to cv X" for functions declared with the && 5847 // ref-qualifier 5848 // 5849 // where X is the class of which the function is a member and cv is the 5850 // cv-qualification on the member function declaration. 5851 // 5852 // However, when finding an implicit conversion sequence for the argument, we 5853 // are not allowed to perform user-defined conversions 5854 // (C++ [over.match.funcs]p5). We perform a simplified version of 5855 // reference binding here, that allows class rvalues to bind to 5856 // non-constant references. 5857 5858 // First check the qualifiers. 5859 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5860 // MSVC ignores __unaligned qualifier for overload candidates; do the same. 5861 if (ImplicitParamType.getCVRQualifiers() != 5862 FromTypeCanon.getLocalCVRQualifiers() && 5863 !ImplicitParamType.isAtLeastAsQualifiedAs( 5864 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) { 5865 ICS.setBad(BadConversionSequence::bad_qualifiers, 5866 FromType, ImplicitParamType); 5867 return ICS; 5868 } 5869 5870 if (FromTypeCanon.hasAddressSpace()) { 5871 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5872 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5873 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType, 5874 S.getASTContext())) { 5875 ICS.setBad(BadConversionSequence::bad_qualifiers, 5876 FromType, ImplicitParamType); 5877 return ICS; 5878 } 5879 } 5880 5881 // Check that we have either the same type or a derived type. It 5882 // affects the conversion rank. 5883 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5884 ImplicitConversionKind SecondKind; 5885 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5886 SecondKind = ICK_Identity; 5887 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) { 5888 SecondKind = ICK_Derived_To_Base; 5889 } else if (!Method->isExplicitObjectMemberFunction()) { 5890 ICS.setBad(BadConversionSequence::unrelated_class, 5891 FromType, ImplicitParamType); 5892 return ICS; 5893 } 5894 5895 // Check the ref-qualifier. 5896 switch (Method->getRefQualifier()) { 5897 case RQ_None: 5898 // Do nothing; we don't care about lvalueness or rvalueness. 5899 break; 5900 5901 case RQ_LValue: 5902 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5903 // non-const lvalue reference cannot bind to an rvalue 5904 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5905 ImplicitParamType); 5906 return ICS; 5907 } 5908 break; 5909 5910 case RQ_RValue: 5911 if (!FromClassification.isRValue()) { 5912 // rvalue reference cannot bind to an lvalue 5913 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5914 ImplicitParamType); 5915 return ICS; 5916 } 5917 break; 5918 } 5919 5920 // Success. Mark this as a reference binding. 5921 ICS.setStandard(); 5922 ICS.Standard.setAsIdentityConversion(); 5923 ICS.Standard.Second = SecondKind; 5924 ICS.Standard.setFromType(FromType); 5925 ICS.Standard.setAllToTypes(ImplicitParamType); 5926 ICS.Standard.ReferenceBinding = true; 5927 ICS.Standard.DirectBinding = true; 5928 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5929 ICS.Standard.BindsToFunctionLvalue = false; 5930 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5931 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5932 = (Method->getRefQualifier() == RQ_None); 5933 return ICS; 5934 } 5935 5936 /// PerformObjectArgumentInitialization - Perform initialization of 5937 /// the implicit object parameter for the given Method with the given 5938 /// expression. 5939 ExprResult Sema::PerformImplicitObjectArgumentInitialization( 5940 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, 5941 CXXMethodDecl *Method) { 5942 QualType FromRecordType, DestType; 5943 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType(); 5944 5945 Expr::Classification FromClassification; 5946 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5947 FromRecordType = PT->getPointeeType(); 5948 DestType = Method->getThisType(); 5949 FromClassification = Expr::Classification::makeSimpleLValue(); 5950 } else { 5951 FromRecordType = From->getType(); 5952 DestType = ImplicitParamRecordType; 5953 FromClassification = From->Classify(Context); 5954 5955 // CWG2813 [expr.call]p6: 5956 // If the function is an implicit object member function, the object 5957 // expression of the class member access shall be a glvalue [...] 5958 if (From->isPRValue()) { 5959 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5960 Method->getRefQualifier() != 5961 RefQualifierKind::RQ_RValue); 5962 } 5963 } 5964 5965 // Note that we always use the true parent context when performing 5966 // the actual argument initialization. 5967 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5968 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5969 Method->getParent()); 5970 if (ICS.isBad()) { 5971 switch (ICS.Bad.Kind) { 5972 case BadConversionSequence::bad_qualifiers: { 5973 Qualifiers FromQs = FromRecordType.getQualifiers(); 5974 Qualifiers ToQs = DestType.getQualifiers(); 5975 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5976 if (CVR) { 5977 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5978 << Method->getDeclName() << FromRecordType << (CVR - 1) 5979 << From->getSourceRange(); 5980 Diag(Method->getLocation(), diag::note_previous_decl) 5981 << Method->getDeclName(); 5982 return ExprError(); 5983 } 5984 break; 5985 } 5986 5987 case BadConversionSequence::lvalue_ref_to_rvalue: 5988 case BadConversionSequence::rvalue_ref_to_lvalue: { 5989 bool IsRValueQualified = 5990 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5991 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5992 << Method->getDeclName() << FromClassification.isRValue() 5993 << IsRValueQualified; 5994 Diag(Method->getLocation(), diag::note_previous_decl) 5995 << Method->getDeclName(); 5996 return ExprError(); 5997 } 5998 5999 case BadConversionSequence::no_conversion: 6000 case BadConversionSequence::unrelated_class: 6001 break; 6002 6003 case BadConversionSequence::too_few_initializers: 6004 case BadConversionSequence::too_many_initializers: 6005 llvm_unreachable("Lists are not objects"); 6006 } 6007 6008 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 6009 << ImplicitParamRecordType << FromRecordType 6010 << From->getSourceRange(); 6011 } 6012 6013 if (ICS.Standard.Second == ICK_Derived_To_Base) { 6014 ExprResult FromRes = 6015 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 6016 if (FromRes.isInvalid()) 6017 return ExprError(); 6018 From = FromRes.get(); 6019 } 6020 6021 if (!Context.hasSameType(From->getType(), DestType)) { 6022 CastKind CK; 6023 QualType PteeTy = DestType->getPointeeType(); 6024 LangAS DestAS = 6025 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 6026 if (FromRecordType.getAddressSpace() != DestAS) 6027 CK = CK_AddressSpaceConversion; 6028 else 6029 CK = CK_NoOp; 6030 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 6031 } 6032 return From; 6033 } 6034 6035 /// TryContextuallyConvertToBool - Attempt to contextually convert the 6036 /// expression From to bool (C++0x [conv]p3). 6037 static ImplicitConversionSequence 6038 TryContextuallyConvertToBool(Sema &S, Expr *From) { 6039 // C++ [dcl.init]/17.8: 6040 // - Otherwise, if the initialization is direct-initialization, the source 6041 // type is std::nullptr_t, and the destination type is bool, the initial 6042 // value of the object being initialized is false. 6043 if (From->getType()->isNullPtrType()) 6044 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 6045 S.Context.BoolTy, 6046 From->isGLValue()); 6047 6048 // All other direct-initialization of bool is equivalent to an implicit 6049 // conversion to bool in which explicit conversions are permitted. 6050 return TryImplicitConversion(S, From, S.Context.BoolTy, 6051 /*SuppressUserConversions=*/false, 6052 AllowedExplicit::Conversions, 6053 /*InOverloadResolution=*/false, 6054 /*CStyle=*/false, 6055 /*AllowObjCWritebackConversion=*/false, 6056 /*AllowObjCConversionOnExplicit=*/false); 6057 } 6058 6059 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 6060 if (checkPlaceholderForOverload(*this, From)) 6061 return ExprError(); 6062 6063 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 6064 if (!ICS.isBad()) 6065 return PerformImplicitConversion(From, Context.BoolTy, ICS, 6066 AssignmentAction::Converting); 6067 6068 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 6069 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 6070 << From->getType() << From->getSourceRange(); 6071 return ExprError(); 6072 } 6073 6074 /// Check that the specified conversion is permitted in a converted constant 6075 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 6076 /// is acceptable. 6077 static bool CheckConvertedConstantConversions(Sema &S, 6078 StandardConversionSequence &SCS) { 6079 // Since we know that the target type is an integral or unscoped enumeration 6080 // type, most conversion kinds are impossible. All possible First and Third 6081 // conversions are fine. 6082 switch (SCS.Second) { 6083 case ICK_Identity: 6084 case ICK_Integral_Promotion: 6085 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 6086 case ICK_Zero_Queue_Conversion: 6087 return true; 6088 6089 case ICK_Boolean_Conversion: 6090 // Conversion from an integral or unscoped enumeration type to bool is 6091 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 6092 // conversion, so we allow it in a converted constant expression. 6093 // 6094 // FIXME: Per core issue 1407, we should not allow this, but that breaks 6095 // a lot of popular code. We should at least add a warning for this 6096 // (non-conforming) extension. 6097 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 6098 SCS.getToType(2)->isBooleanType(); 6099 6100 case ICK_Pointer_Conversion: 6101 case ICK_Pointer_Member: 6102 // C++1z: null pointer conversions and null member pointer conversions are 6103 // only permitted if the source type is std::nullptr_t. 6104 return SCS.getFromType()->isNullPtrType(); 6105 6106 case ICK_Floating_Promotion: 6107 case ICK_Complex_Promotion: 6108 case ICK_Floating_Conversion: 6109 case ICK_Complex_Conversion: 6110 case ICK_Floating_Integral: 6111 case ICK_Compatible_Conversion: 6112 case ICK_Derived_To_Base: 6113 case ICK_Vector_Conversion: 6114 case ICK_SVE_Vector_Conversion: 6115 case ICK_RVV_Vector_Conversion: 6116 case ICK_HLSL_Vector_Splat: 6117 case ICK_Vector_Splat: 6118 case ICK_Complex_Real: 6119 case ICK_Block_Pointer_Conversion: 6120 case ICK_TransparentUnionConversion: 6121 case ICK_Writeback_Conversion: 6122 case ICK_Zero_Event_Conversion: 6123 case ICK_C_Only_Conversion: 6124 case ICK_Incompatible_Pointer_Conversion: 6125 case ICK_Fixed_Point_Conversion: 6126 case ICK_HLSL_Vector_Truncation: 6127 return false; 6128 6129 case ICK_Lvalue_To_Rvalue: 6130 case ICK_Array_To_Pointer: 6131 case ICK_Function_To_Pointer: 6132 case ICK_HLSL_Array_RValue: 6133 llvm_unreachable("found a first conversion kind in Second"); 6134 6135 case ICK_Function_Conversion: 6136 case ICK_Qualification: 6137 llvm_unreachable("found a third conversion kind in Second"); 6138 6139 case ICK_Num_Conversion_Kinds: 6140 break; 6141 } 6142 6143 llvm_unreachable("unknown conversion kind"); 6144 } 6145 6146 /// BuildConvertedConstantExpression - Check that the expression From is a 6147 /// converted constant expression of type T, perform the conversion but 6148 /// does not evaluate the expression 6149 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, 6150 QualType T, 6151 Sema::CCEKind CCE, 6152 NamedDecl *Dest, 6153 APValue &PreNarrowingValue) { 6154 assert((S.getLangOpts().CPlusPlus11 || CCE == Sema::CCEK_InjectedTTP) && 6155 "converted constant expression outside C++11 or TTP matching"); 6156 6157 if (checkPlaceholderForOverload(S, From)) 6158 return ExprError(); 6159 6160 // C++1z [expr.const]p3: 6161 // A converted constant expression of type T is an expression, 6162 // implicitly converted to type T, where the converted 6163 // expression is a constant expression and the implicit conversion 6164 // sequence contains only [... list of conversions ...]. 6165 ImplicitConversionSequence ICS = 6166 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 6167 ? TryContextuallyConvertToBool(S, From) 6168 : TryCopyInitialization(S, From, T, 6169 /*SuppressUserConversions=*/false, 6170 /*InOverloadResolution=*/false, 6171 /*AllowObjCWritebackConversion=*/false, 6172 /*AllowExplicit=*/false); 6173 StandardConversionSequence *SCS = nullptr; 6174 switch (ICS.getKind()) { 6175 case ImplicitConversionSequence::StandardConversion: 6176 SCS = &ICS.Standard; 6177 break; 6178 case ImplicitConversionSequence::UserDefinedConversion: 6179 if (T->isRecordType()) 6180 SCS = &ICS.UserDefined.Before; 6181 else 6182 SCS = &ICS.UserDefined.After; 6183 break; 6184 case ImplicitConversionSequence::AmbiguousConversion: 6185 case ImplicitConversionSequence::BadConversion: 6186 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 6187 return S.Diag(From->getBeginLoc(), 6188 diag::err_typecheck_converted_constant_expression) 6189 << From->getType() << From->getSourceRange() << T; 6190 return ExprError(); 6191 6192 case ImplicitConversionSequence::EllipsisConversion: 6193 case ImplicitConversionSequence::StaticObjectArgumentConversion: 6194 llvm_unreachable("bad conversion in converted constant expression"); 6195 } 6196 6197 // Check that we would only use permitted conversions. 6198 if (!CheckConvertedConstantConversions(S, *SCS)) { 6199 return S.Diag(From->getBeginLoc(), 6200 diag::err_typecheck_converted_constant_expression_disallowed) 6201 << From->getType() << From->getSourceRange() << T; 6202 } 6203 // [...] and where the reference binding (if any) binds directly. 6204 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 6205 return S.Diag(From->getBeginLoc(), 6206 diag::err_typecheck_converted_constant_expression_indirect) 6207 << From->getType() << From->getSourceRange() << T; 6208 } 6209 // 'TryCopyInitialization' returns incorrect info for attempts to bind 6210 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely, 6211 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not 6212 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this 6213 // case explicitly. 6214 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) { 6215 return S.Diag(From->getBeginLoc(), 6216 diag::err_reference_bind_to_bitfield_in_cce) 6217 << From->getSourceRange(); 6218 } 6219 6220 // Usually we can simply apply the ImplicitConversionSequence we formed 6221 // earlier, but that's not guaranteed to work when initializing an object of 6222 // class type. 6223 ExprResult Result; 6224 bool IsTemplateArgument = 6225 CCE == Sema::CCEK_TemplateArg || CCE == Sema::CCEK_InjectedTTP; 6226 if (T->isRecordType()) { 6227 assert(IsTemplateArgument && 6228 "unexpected class type converted constant expr"); 6229 Result = S.PerformCopyInitialization( 6230 InitializedEntity::InitializeTemplateParameter( 6231 T, cast<NonTypeTemplateParmDecl>(Dest)), 6232 SourceLocation(), From); 6233 } else { 6234 Result = 6235 S.PerformImplicitConversion(From, T, ICS, AssignmentAction::Converting); 6236 } 6237 if (Result.isInvalid()) 6238 return Result; 6239 6240 // C++2a [intro.execution]p5: 6241 // A full-expression is [...] a constant-expression [...] 6242 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 6243 /*DiscardedValue=*/false, /*IsConstexpr=*/true, 6244 IsTemplateArgument); 6245 if (Result.isInvalid()) 6246 return Result; 6247 6248 // Check for a narrowing implicit conversion. 6249 bool ReturnPreNarrowingValue = false; 6250 QualType PreNarrowingType; 6251 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 6252 PreNarrowingType)) { 6253 case NK_Variable_Narrowing: 6254 // Implicit conversion to a narrower type, and the value is not a constant 6255 // expression. We'll diagnose this in a moment. 6256 case NK_Not_Narrowing: 6257 break; 6258 6259 case NK_Constant_Narrowing: 6260 if (CCE == Sema::CCEK_ArrayBound && 6261 PreNarrowingType->isIntegralOrEnumerationType() && 6262 PreNarrowingValue.isInt()) { 6263 // Don't diagnose array bound narrowing here; we produce more precise 6264 // errors by allowing the un-narrowed value through. 6265 ReturnPreNarrowingValue = true; 6266 break; 6267 } 6268 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 6269 << CCE << /*Constant*/ 1 6270 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 6271 break; 6272 6273 case NK_Dependent_Narrowing: 6274 // Implicit conversion to a narrower type, but the expression is 6275 // value-dependent so we can't tell whether it's actually narrowing. 6276 // For matching the parameters of a TTP, the conversion is ill-formed 6277 // if it may narrow. 6278 if (CCE != Sema::CCEK_InjectedTTP) 6279 break; 6280 [[fallthrough]]; 6281 case NK_Type_Narrowing: 6282 // FIXME: It would be better to diagnose that the expression is not a 6283 // constant expression. 6284 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 6285 << CCE << /*Constant*/ 0 << From->getType() << T; 6286 break; 6287 } 6288 if (!ReturnPreNarrowingValue) 6289 PreNarrowingValue = {}; 6290 6291 return Result; 6292 } 6293 6294 /// CheckConvertedConstantExpression - Check that the expression From is a 6295 /// converted constant expression of type T, perform the conversion and produce 6296 /// the converted expression, per C++11 [expr.const]p3. 6297 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 6298 QualType T, APValue &Value, 6299 Sema::CCEKind CCE, 6300 bool RequireInt, 6301 NamedDecl *Dest) { 6302 6303 APValue PreNarrowingValue; 6304 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest, 6305 PreNarrowingValue); 6306 if (Result.isInvalid() || Result.get()->isValueDependent()) { 6307 Value = APValue(); 6308 return Result; 6309 } 6310 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE, 6311 RequireInt, PreNarrowingValue); 6312 } 6313 6314 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T, 6315 CCEKind CCE, 6316 NamedDecl *Dest) { 6317 APValue PreNarrowingValue; 6318 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest, 6319 PreNarrowingValue); 6320 } 6321 6322 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 6323 APValue &Value, CCEKind CCE, 6324 NamedDecl *Dest) { 6325 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 6326 Dest); 6327 } 6328 6329 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 6330 llvm::APSInt &Value, 6331 CCEKind CCE) { 6332 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 6333 6334 APValue V; 6335 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 6336 /*Dest=*/nullptr); 6337 if (!R.isInvalid() && !R.get()->isValueDependent()) 6338 Value = V.getInt(); 6339 return R; 6340 } 6341 6342 ExprResult 6343 Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, 6344 Sema::CCEKind CCE, bool RequireInt, 6345 const APValue &PreNarrowingValue) { 6346 6347 ExprResult Result = E; 6348 // Check the expression is a constant expression. 6349 SmallVector<PartialDiagnosticAt, 8> Notes; 6350 Expr::EvalResult Eval; 6351 Eval.Diag = &Notes; 6352 6353 assert(CCE != Sema::CCEK_InjectedTTP && "unnexpected CCE Kind"); 6354 6355 ConstantExprKind Kind; 6356 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 6357 Kind = ConstantExprKind::ClassTemplateArgument; 6358 else if (CCE == Sema::CCEK_TemplateArg) 6359 Kind = ConstantExprKind::NonClassTemplateArgument; 6360 else 6361 Kind = ConstantExprKind::Normal; 6362 6363 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) || 6364 (RequireInt && !Eval.Val.isInt())) { 6365 // The expression can't be folded, so we can't keep it at this position in 6366 // the AST. 6367 Result = ExprError(); 6368 } else { 6369 Value = Eval.Val; 6370 6371 if (Notes.empty()) { 6372 // It's a constant expression. 6373 Expr *E = Result.get(); 6374 if (const auto *CE = dyn_cast<ConstantExpr>(E)) { 6375 // We expect a ConstantExpr to have a value associated with it 6376 // by this point. 6377 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None && 6378 "ConstantExpr has no value associated with it"); 6379 (void)CE; 6380 } else { 6381 E = ConstantExpr::Create(Context, Result.get(), Value); 6382 } 6383 if (!PreNarrowingValue.isAbsent()) 6384 Value = std::move(PreNarrowingValue); 6385 return E; 6386 } 6387 } 6388 6389 // It's not a constant expression. Produce an appropriate diagnostic. 6390 if (Notes.size() == 1 && 6391 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 6392 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 6393 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 6394 diag::note_constexpr_invalid_template_arg) { 6395 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 6396 for (unsigned I = 0; I < Notes.size(); ++I) 6397 Diag(Notes[I].first, Notes[I].second); 6398 } else { 6399 Diag(E->getBeginLoc(), diag::err_expr_not_cce) 6400 << CCE << E->getSourceRange(); 6401 for (unsigned I = 0; I < Notes.size(); ++I) 6402 Diag(Notes[I].first, Notes[I].second); 6403 } 6404 return ExprError(); 6405 } 6406 6407 /// dropPointerConversions - If the given standard conversion sequence 6408 /// involves any pointer conversions, remove them. This may change 6409 /// the result type of the conversion sequence. 6410 static void dropPointerConversion(StandardConversionSequence &SCS) { 6411 if (SCS.Second == ICK_Pointer_Conversion) { 6412 SCS.Second = ICK_Identity; 6413 SCS.Dimension = ICK_Identity; 6414 SCS.Third = ICK_Identity; 6415 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 6416 } 6417 } 6418 6419 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 6420 /// convert the expression From to an Objective-C pointer type. 6421 static ImplicitConversionSequence 6422 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 6423 // Do an implicit conversion to 'id'. 6424 QualType Ty = S.Context.getObjCIdType(); 6425 ImplicitConversionSequence ICS 6426 = TryImplicitConversion(S, From, Ty, 6427 // FIXME: Are these flags correct? 6428 /*SuppressUserConversions=*/false, 6429 AllowedExplicit::Conversions, 6430 /*InOverloadResolution=*/false, 6431 /*CStyle=*/false, 6432 /*AllowObjCWritebackConversion=*/false, 6433 /*AllowObjCConversionOnExplicit=*/true); 6434 6435 // Strip off any final conversions to 'id'. 6436 switch (ICS.getKind()) { 6437 case ImplicitConversionSequence::BadConversion: 6438 case ImplicitConversionSequence::AmbiguousConversion: 6439 case ImplicitConversionSequence::EllipsisConversion: 6440 case ImplicitConversionSequence::StaticObjectArgumentConversion: 6441 break; 6442 6443 case ImplicitConversionSequence::UserDefinedConversion: 6444 dropPointerConversion(ICS.UserDefined.After); 6445 break; 6446 6447 case ImplicitConversionSequence::StandardConversion: 6448 dropPointerConversion(ICS.Standard); 6449 break; 6450 } 6451 6452 return ICS; 6453 } 6454 6455 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 6456 if (checkPlaceholderForOverload(*this, From)) 6457 return ExprError(); 6458 6459 QualType Ty = Context.getObjCIdType(); 6460 ImplicitConversionSequence ICS = 6461 TryContextuallyConvertToObjCPointer(*this, From); 6462 if (!ICS.isBad()) 6463 return PerformImplicitConversion(From, Ty, ICS, 6464 AssignmentAction::Converting); 6465 return ExprResult(); 6466 } 6467 6468 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) { 6469 const Expr *Base = nullptr; 6470 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) && 6471 "expected a member expression"); 6472 6473 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE); 6474 M && !M->isImplicitAccess()) 6475 Base = M->getBase(); 6476 else if (const auto M = dyn_cast<MemberExpr>(MemExprE); 6477 M && !M->isImplicitAccess()) 6478 Base = M->getBase(); 6479 6480 QualType T = Base ? Base->getType() : S.getCurrentThisType(); 6481 6482 if (T->isPointerType()) 6483 T = T->getPointeeType(); 6484 6485 return T; 6486 } 6487 6488 static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj, 6489 const FunctionDecl *Fun) { 6490 QualType ObjType = Obj->getType(); 6491 if (ObjType->isPointerType()) { 6492 ObjType = ObjType->getPointeeType(); 6493 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType, 6494 VK_LValue, OK_Ordinary, SourceLocation(), 6495 /*CanOverflow=*/false, FPOptionsOverride()); 6496 } 6497 return Obj; 6498 } 6499 6500 ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj, 6501 FunctionDecl *Fun) { 6502 Obj = GetExplicitObjectExpr(S, Obj, Fun); 6503 return S.PerformCopyInitialization( 6504 InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)), 6505 Obj->getExprLoc(), Obj); 6506 } 6507 6508 static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, 6509 Expr *Object, MultiExprArg &Args, 6510 SmallVectorImpl<Expr *> &NewArgs) { 6511 assert(Method->isExplicitObjectMemberFunction() && 6512 "Method is not an explicit member function"); 6513 assert(NewArgs.empty() && "NewArgs should be empty"); 6514 6515 NewArgs.reserve(Args.size() + 1); 6516 Expr *This = GetExplicitObjectExpr(S, Object, Method); 6517 NewArgs.push_back(This); 6518 NewArgs.append(Args.begin(), Args.end()); 6519 Args = NewArgs; 6520 return S.DiagnoseInvalidExplicitObjectParameterInLambda( 6521 Method, Object->getBeginLoc()); 6522 } 6523 6524 /// Determine whether the provided type is an integral type, or an enumeration 6525 /// type of a permitted flavor. 6526 bool Sema::ICEConvertDiagnoser::match(QualType T) { 6527 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 6528 : T->isIntegralOrUnscopedEnumerationType(); 6529 } 6530 6531 static ExprResult 6532 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 6533 Sema::ContextualImplicitConverter &Converter, 6534 QualType T, UnresolvedSetImpl &ViableConversions) { 6535 6536 if (Converter.Suppress) 6537 return ExprError(); 6538 6539 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 6540 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6541 CXXConversionDecl *Conv = 6542 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 6543 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 6544 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 6545 } 6546 return From; 6547 } 6548 6549 static bool 6550 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6551 Sema::ContextualImplicitConverter &Converter, 6552 QualType T, bool HadMultipleCandidates, 6553 UnresolvedSetImpl &ExplicitConversions) { 6554 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 6555 DeclAccessPair Found = ExplicitConversions[0]; 6556 CXXConversionDecl *Conversion = 6557 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6558 6559 // The user probably meant to invoke the given explicit 6560 // conversion; use it. 6561 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 6562 std::string TypeStr; 6563 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 6564 6565 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 6566 << FixItHint::CreateInsertion(From->getBeginLoc(), 6567 "static_cast<" + TypeStr + ">(") 6568 << FixItHint::CreateInsertion( 6569 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 6570 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 6571 6572 // If we aren't in a SFINAE context, build a call to the 6573 // explicit conversion function. 6574 if (SemaRef.isSFINAEContext()) 6575 return true; 6576 6577 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6578 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6579 HadMultipleCandidates); 6580 if (Result.isInvalid()) 6581 return true; 6582 6583 // Replace the conversion with a RecoveryExpr, so we don't try to 6584 // instantiate it later, but can further diagnose here. 6585 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), 6586 From, Result.get()->getType()); 6587 if (Result.isInvalid()) 6588 return true; 6589 From = Result.get(); 6590 } 6591 return false; 6592 } 6593 6594 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6595 Sema::ContextualImplicitConverter &Converter, 6596 QualType T, bool HadMultipleCandidates, 6597 DeclAccessPair &Found) { 6598 CXXConversionDecl *Conversion = 6599 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6600 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6601 6602 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 6603 if (!Converter.SuppressConversion) { 6604 if (SemaRef.isSFINAEContext()) 6605 return true; 6606 6607 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 6608 << From->getSourceRange(); 6609 } 6610 6611 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6612 HadMultipleCandidates); 6613 if (Result.isInvalid()) 6614 return true; 6615 // Record usage of conversion in an implicit cast. 6616 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6617 CK_UserDefinedConversion, Result.get(), 6618 nullptr, Result.get()->getValueKind(), 6619 SemaRef.CurFPFeatureOverrides()); 6620 return false; 6621 } 6622 6623 static ExprResult finishContextualImplicitConversion( 6624 Sema &SemaRef, SourceLocation Loc, Expr *From, 6625 Sema::ContextualImplicitConverter &Converter) { 6626 if (!Converter.match(From->getType()) && !Converter.Suppress) 6627 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 6628 << From->getSourceRange(); 6629 6630 return SemaRef.DefaultLvalueConversion(From); 6631 } 6632 6633 static void 6634 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 6635 UnresolvedSetImpl &ViableConversions, 6636 OverloadCandidateSet &CandidateSet) { 6637 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) { 6638 NamedDecl *D = FoundDecl.getDecl(); 6639 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6640 if (isa<UsingShadowDecl>(D)) 6641 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6642 6643 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 6644 SemaRef.AddTemplateConversionCandidate( 6645 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6646 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true); 6647 continue; 6648 } 6649 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6650 SemaRef.AddConversionCandidate( 6651 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 6652 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true); 6653 } 6654 } 6655 6656 /// Attempt to convert the given expression to a type which is accepted 6657 /// by the given converter. 6658 /// 6659 /// This routine will attempt to convert an expression of class type to a 6660 /// type accepted by the specified converter. In C++11 and before, the class 6661 /// must have a single non-explicit conversion function converting to a matching 6662 /// type. In C++1y, there can be multiple such conversion functions, but only 6663 /// one target type. 6664 /// 6665 /// \param Loc The source location of the construct that requires the 6666 /// conversion. 6667 /// 6668 /// \param From The expression we're converting from. 6669 /// 6670 /// \param Converter Used to control and diagnose the conversion process. 6671 /// 6672 /// \returns The expression, converted to an integral or enumeration type if 6673 /// successful. 6674 ExprResult Sema::PerformContextualImplicitConversion( 6675 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6676 // We can't perform any more checking for type-dependent expressions. 6677 if (From->isTypeDependent()) 6678 return From; 6679 6680 // Process placeholders immediately. 6681 if (From->hasPlaceholderType()) { 6682 ExprResult result = CheckPlaceholderExpr(From); 6683 if (result.isInvalid()) 6684 return result; 6685 From = result.get(); 6686 } 6687 6688 // Try converting the expression to an Lvalue first, to get rid of qualifiers. 6689 ExprResult Converted = DefaultLvalueConversion(From); 6690 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType(); 6691 // If the expression already has a matching type, we're golden. 6692 if (Converter.match(T)) 6693 return Converted; 6694 6695 // FIXME: Check for missing '()' if T is a function type? 6696 6697 // We can only perform contextual implicit conversions on objects of class 6698 // type. 6699 const RecordType *RecordTy = T->getAs<RecordType>(); 6700 if (!RecordTy || !getLangOpts().CPlusPlus) { 6701 if (!Converter.Suppress) 6702 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6703 return From; 6704 } 6705 6706 // We must have a complete class type. 6707 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6708 ContextualImplicitConverter &Converter; 6709 Expr *From; 6710 6711 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6712 : Converter(Converter), From(From) {} 6713 6714 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6715 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6716 } 6717 } IncompleteDiagnoser(Converter, From); 6718 6719 if (Converter.Suppress ? !isCompleteType(Loc, T) 6720 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6721 return From; 6722 6723 // Look for a conversion to an integral or enumeration type. 6724 UnresolvedSet<4> 6725 ViableConversions; // These are *potentially* viable in C++1y. 6726 UnresolvedSet<4> ExplicitConversions; 6727 const auto &Conversions = 6728 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6729 6730 bool HadMultipleCandidates = 6731 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6732 6733 // To check that there is only one target type, in C++1y: 6734 QualType ToType; 6735 bool HasUniqueTargetType = true; 6736 6737 // Collect explicit or viable (potentially in C++1y) conversions. 6738 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6739 NamedDecl *D = (*I)->getUnderlyingDecl(); 6740 CXXConversionDecl *Conversion; 6741 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6742 if (ConvTemplate) { 6743 if (getLangOpts().CPlusPlus14) 6744 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6745 else 6746 continue; // C++11 does not consider conversion operator templates(?). 6747 } else 6748 Conversion = cast<CXXConversionDecl>(D); 6749 6750 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6751 "Conversion operator templates are considered potentially " 6752 "viable in C++1y"); 6753 6754 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6755 if (Converter.match(CurToType) || ConvTemplate) { 6756 6757 if (Conversion->isExplicit()) { 6758 // FIXME: For C++1y, do we need this restriction? 6759 // cf. diagnoseNoViableConversion() 6760 if (!ConvTemplate) 6761 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6762 } else { 6763 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6764 if (ToType.isNull()) 6765 ToType = CurToType.getUnqualifiedType(); 6766 else if (HasUniqueTargetType && 6767 (CurToType.getUnqualifiedType() != ToType)) 6768 HasUniqueTargetType = false; 6769 } 6770 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6771 } 6772 } 6773 } 6774 6775 if (getLangOpts().CPlusPlus14) { 6776 // C++1y [conv]p6: 6777 // ... An expression e of class type E appearing in such a context 6778 // is said to be contextually implicitly converted to a specified 6779 // type T and is well-formed if and only if e can be implicitly 6780 // converted to a type T that is determined as follows: E is searched 6781 // for conversion functions whose return type is cv T or reference to 6782 // cv T such that T is allowed by the context. There shall be 6783 // exactly one such T. 6784 6785 // If no unique T is found: 6786 if (ToType.isNull()) { 6787 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6788 HadMultipleCandidates, 6789 ExplicitConversions)) 6790 return ExprError(); 6791 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6792 } 6793 6794 // If more than one unique Ts are found: 6795 if (!HasUniqueTargetType) 6796 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6797 ViableConversions); 6798 6799 // If one unique T is found: 6800 // First, build a candidate set from the previously recorded 6801 // potentially viable conversions. 6802 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6803 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6804 CandidateSet); 6805 6806 // Then, perform overload resolution over the candidate set. 6807 OverloadCandidateSet::iterator Best; 6808 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6809 case OR_Success: { 6810 // Apply this conversion. 6811 DeclAccessPair Found = 6812 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6813 if (recordConversion(*this, Loc, From, Converter, T, 6814 HadMultipleCandidates, Found)) 6815 return ExprError(); 6816 break; 6817 } 6818 case OR_Ambiguous: 6819 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6820 ViableConversions); 6821 case OR_No_Viable_Function: 6822 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6823 HadMultipleCandidates, 6824 ExplicitConversions)) 6825 return ExprError(); 6826 [[fallthrough]]; 6827 case OR_Deleted: 6828 // We'll complain below about a non-integral condition type. 6829 break; 6830 } 6831 } else { 6832 switch (ViableConversions.size()) { 6833 case 0: { 6834 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6835 HadMultipleCandidates, 6836 ExplicitConversions)) 6837 return ExprError(); 6838 6839 // We'll complain below about a non-integral condition type. 6840 break; 6841 } 6842 case 1: { 6843 // Apply this conversion. 6844 DeclAccessPair Found = ViableConversions[0]; 6845 if (recordConversion(*this, Loc, From, Converter, T, 6846 HadMultipleCandidates, Found)) 6847 return ExprError(); 6848 break; 6849 } 6850 default: 6851 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6852 ViableConversions); 6853 } 6854 } 6855 6856 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6857 } 6858 6859 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6860 /// an acceptable non-member overloaded operator for a call whose 6861 /// arguments have types T1 (and, if non-empty, T2). This routine 6862 /// implements the check in C++ [over.match.oper]p3b2 concerning 6863 /// enumeration types. 6864 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6865 FunctionDecl *Fn, 6866 ArrayRef<Expr *> Args) { 6867 QualType T1 = Args[0]->getType(); 6868 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6869 6870 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6871 return true; 6872 6873 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6874 return true; 6875 6876 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6877 if (Proto->getNumParams() < 1) 6878 return false; 6879 6880 if (T1->isEnumeralType()) { 6881 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6882 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6883 return true; 6884 } 6885 6886 if (Proto->getNumParams() < 2) 6887 return false; 6888 6889 if (!T2.isNull() && T2->isEnumeralType()) { 6890 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6891 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6892 return true; 6893 } 6894 6895 return false; 6896 } 6897 6898 static bool isNonViableMultiVersionOverload(FunctionDecl *FD) { 6899 if (FD->isTargetMultiVersionDefault()) 6900 return false; 6901 6902 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64()) 6903 return FD->isTargetMultiVersion(); 6904 6905 if (!FD->isMultiVersion()) 6906 return false; 6907 6908 // Among multiple target versions consider either the default, 6909 // or the first non-default in the absence of default version. 6910 unsigned SeenAt = 0; 6911 unsigned I = 0; 6912 bool HasDefault = false; 6913 FD->getASTContext().forEachMultiversionedFunctionVersion( 6914 FD, [&](const FunctionDecl *CurFD) { 6915 if (FD == CurFD) 6916 SeenAt = I; 6917 else if (CurFD->isTargetMultiVersionDefault()) 6918 HasDefault = true; 6919 ++I; 6920 }); 6921 return HasDefault || SeenAt != 0; 6922 } 6923 6924 void Sema::AddOverloadCandidate( 6925 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6926 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6927 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6928 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6929 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction, 6930 bool HasMatchedPackOnParmToNonPackOnArg) { 6931 const FunctionProtoType *Proto 6932 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6933 assert(Proto && "Functions without a prototype cannot be overloaded"); 6934 assert(!Function->getDescribedFunctionTemplate() && 6935 "Use AddTemplateOverloadCandidate for function templates"); 6936 6937 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6938 if (!isa<CXXConstructorDecl>(Method)) { 6939 // If we get here, it's because we're calling a member function 6940 // that is named without a member access expression (e.g., 6941 // "this->f") that was either written explicitly or created 6942 // implicitly. This can happen with a qualified call to a member 6943 // function, e.g., X::f(). We use an empty type for the implied 6944 // object argument (C++ [over.call.func]p3), and the acting context 6945 // is irrelevant. 6946 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6947 Expr::Classification::makeSimpleLValue(), Args, 6948 CandidateSet, SuppressUserConversions, 6949 PartialOverloading, EarlyConversions, PO, 6950 HasMatchedPackOnParmToNonPackOnArg); 6951 return; 6952 } 6953 // We treat a constructor like a non-member function, since its object 6954 // argument doesn't participate in overload resolution. 6955 } 6956 6957 if (!CandidateSet.isNewCandidate(Function, PO)) 6958 return; 6959 6960 // C++11 [class.copy]p11: [DR1402] 6961 // A defaulted move constructor that is defined as deleted is ignored by 6962 // overload resolution. 6963 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6964 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6965 Constructor->isMoveConstructor()) 6966 return; 6967 6968 // Overload resolution is always an unevaluated context. 6969 EnterExpressionEvaluationContext Unevaluated( 6970 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6971 6972 // C++ [over.match.oper]p3: 6973 // if no operand has a class type, only those non-member functions in the 6974 // lookup set that have a first parameter of type T1 or "reference to 6975 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6976 // is a right operand) a second parameter of type T2 or "reference to 6977 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6978 // candidate functions. 6979 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6980 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6981 return; 6982 6983 // Add this candidate 6984 OverloadCandidate &Candidate = 6985 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6986 Candidate.FoundDecl = FoundDecl; 6987 Candidate.Function = Function; 6988 Candidate.Viable = true; 6989 Candidate.RewriteKind = 6990 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6991 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate); 6992 Candidate.ExplicitCallArguments = Args.size(); 6993 Candidate.HasMatchedPackOnParmToNonPackOnArg = 6994 HasMatchedPackOnParmToNonPackOnArg; 6995 6996 // Explicit functions are not actually candidates at all if we're not 6997 // allowing them in this context, but keep them around so we can point 6998 // to them in diagnostics. 6999 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 7000 Candidate.Viable = false; 7001 Candidate.FailureKind = ovl_fail_explicit; 7002 return; 7003 } 7004 7005 // Functions with internal linkage are only viable in the same module unit. 7006 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) { 7007 /// FIXME: Currently, the semantics of linkage in clang is slightly 7008 /// different from the semantics in C++ spec. In C++ spec, only names 7009 /// have linkage. So that all entities of the same should share one 7010 /// linkage. But in clang, different entities of the same could have 7011 /// different linkage. 7012 const NamedDecl *ND = Function; 7013 bool IsImplicitlyInstantiated = false; 7014 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) { 7015 ND = SpecInfo->getTemplate(); 7016 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() == 7017 TSK_ImplicitInstantiation; 7018 } 7019 7020 /// Don't remove inline functions with internal linkage from the overload 7021 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17. 7022 /// However: 7023 /// - Inline functions with internal linkage are a common pattern in 7024 /// headers to avoid ODR issues. 7025 /// - The global module is meant to be a transition mechanism for C and C++ 7026 /// headers, and the current rules as written work against that goal. 7027 const bool IsInlineFunctionInGMF = 7028 Function->isFromGlobalModule() && 7029 (IsImplicitlyInstantiated || Function->isInlined()); 7030 7031 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) { 7032 Candidate.Viable = false; 7033 Candidate.FailureKind = ovl_fail_module_mismatched; 7034 return; 7035 } 7036 } 7037 7038 if (isNonViableMultiVersionOverload(Function)) { 7039 Candidate.Viable = false; 7040 Candidate.FailureKind = ovl_non_default_multiversion_function; 7041 return; 7042 } 7043 7044 if (Constructor) { 7045 // C++ [class.copy]p3: 7046 // A member function template is never instantiated to perform the copy 7047 // of a class object to an object of its class type. 7048 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 7049 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 7050 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 7051 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 7052 ClassType))) { 7053 Candidate.Viable = false; 7054 Candidate.FailureKind = ovl_fail_illegal_constructor; 7055 return; 7056 } 7057 7058 // C++ [over.match.funcs]p8: (proposed DR resolution) 7059 // A constructor inherited from class type C that has a first parameter 7060 // of type "reference to P" (including such a constructor instantiated 7061 // from a template) is excluded from the set of candidate functions when 7062 // constructing an object of type cv D if the argument list has exactly 7063 // one argument and D is reference-related to P and P is reference-related 7064 // to C. 7065 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 7066 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 7067 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 7068 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 7069 QualType C = Context.getRecordType(Constructor->getParent()); 7070 QualType D = Context.getRecordType(Shadow->getParent()); 7071 SourceLocation Loc = Args.front()->getExprLoc(); 7072 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 7073 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 7074 Candidate.Viable = false; 7075 Candidate.FailureKind = ovl_fail_inhctor_slice; 7076 return; 7077 } 7078 } 7079 7080 // Check that the constructor is capable of constructing an object in the 7081 // destination address space. 7082 if (!Qualifiers::isAddressSpaceSupersetOf( 7083 Constructor->getMethodQualifiers().getAddressSpace(), 7084 CandidateSet.getDestAS(), getASTContext())) { 7085 Candidate.Viable = false; 7086 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 7087 } 7088 } 7089 7090 unsigned NumParams = Proto->getNumParams(); 7091 7092 // (C++ 13.3.2p2): A candidate function having fewer than m 7093 // parameters is viable only if it has an ellipsis in its parameter 7094 // list (8.3.5). 7095 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 7096 !Proto->isVariadic() && 7097 shouldEnforceArgLimit(PartialOverloading, Function)) { 7098 Candidate.Viable = false; 7099 Candidate.FailureKind = ovl_fail_too_many_arguments; 7100 return; 7101 } 7102 7103 // (C++ 13.3.2p2): A candidate function having more than m parameters 7104 // is viable only if the (m+1)st parameter has a default argument 7105 // (8.3.6). For the purposes of overload resolution, the 7106 // parameter list is truncated on the right, so that there are 7107 // exactly m parameters. 7108 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 7109 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs && 7110 !PartialOverloading) { 7111 // Not enough arguments. 7112 Candidate.Viable = false; 7113 Candidate.FailureKind = ovl_fail_too_few_arguments; 7114 return; 7115 } 7116 7117 // (CUDA B.1): Check for invalid calls between targets. 7118 if (getLangOpts().CUDA) { 7119 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); 7120 // Skip the check for callers that are implicit members, because in this 7121 // case we may not yet know what the member's target is; the target is 7122 // inferred for the member automatically, based on the bases and fields of 7123 // the class. 7124 if (!(Caller && Caller->isImplicit()) && 7125 !CUDA().IsAllowedCall(Caller, Function)) { 7126 Candidate.Viable = false; 7127 Candidate.FailureKind = ovl_fail_bad_target; 7128 return; 7129 } 7130 } 7131 7132 if (Function->getTrailingRequiresClause()) { 7133 ConstraintSatisfaction Satisfaction; 7134 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {}, 7135 /*ForOverloadResolution*/ true) || 7136 !Satisfaction.IsSatisfied) { 7137 Candidate.Viable = false; 7138 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7139 return; 7140 } 7141 } 7142 7143 // Determine the implicit conversion sequences for each of the 7144 // arguments. 7145 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7146 unsigned ConvIdx = 7147 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 7148 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7149 // We already formed a conversion sequence for this parameter during 7150 // template argument deduction. 7151 } else if (ArgIdx < NumParams) { 7152 // (C++ 13.3.2p3): for F to be a viable function, there shall 7153 // exist for each argument an implicit conversion sequence 7154 // (13.3.3.1) that converts that argument to the corresponding 7155 // parameter of F. 7156 QualType ParamType = Proto->getParamType(ArgIdx); 7157 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI(); 7158 if (ParamABI == ParameterABI::HLSLOut || 7159 ParamABI == ParameterABI::HLSLInOut) 7160 ParamType = ParamType.getNonReferenceType(); 7161 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 7162 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 7163 /*InOverloadResolution=*/true, 7164 /*AllowObjCWritebackConversion=*/ 7165 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 7166 if (Candidate.Conversions[ConvIdx].isBad()) { 7167 Candidate.Viable = false; 7168 Candidate.FailureKind = ovl_fail_bad_conversion; 7169 return; 7170 } 7171 } else { 7172 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7173 // argument for which there is no corresponding parameter is 7174 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7175 Candidate.Conversions[ConvIdx].setEllipsis(); 7176 } 7177 } 7178 7179 if (EnableIfAttr *FailedAttr = 7180 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 7181 Candidate.Viable = false; 7182 Candidate.FailureKind = ovl_fail_enable_if; 7183 Candidate.DeductionFailure.Data = FailedAttr; 7184 return; 7185 } 7186 } 7187 7188 ObjCMethodDecl * 7189 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 7190 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 7191 if (Methods.size() <= 1) 7192 return nullptr; 7193 7194 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 7195 bool Match = true; 7196 ObjCMethodDecl *Method = Methods[b]; 7197 unsigned NumNamedArgs = Sel.getNumArgs(); 7198 // Method might have more arguments than selector indicates. This is due 7199 // to addition of c-style arguments in method. 7200 if (Method->param_size() > NumNamedArgs) 7201 NumNamedArgs = Method->param_size(); 7202 if (Args.size() < NumNamedArgs) 7203 continue; 7204 7205 for (unsigned i = 0; i < NumNamedArgs; i++) { 7206 // We can't do any type-checking on a type-dependent argument. 7207 if (Args[i]->isTypeDependent()) { 7208 Match = false; 7209 break; 7210 } 7211 7212 ParmVarDecl *param = Method->parameters()[i]; 7213 Expr *argExpr = Args[i]; 7214 assert(argExpr && "SelectBestMethod(): missing expression"); 7215 7216 // Strip the unbridged-cast placeholder expression off unless it's 7217 // a consumed argument. 7218 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 7219 !param->hasAttr<CFConsumedAttr>()) 7220 argExpr = ObjC().stripARCUnbridgedCast(argExpr); 7221 7222 // If the parameter is __unknown_anytype, move on to the next method. 7223 if (param->getType() == Context.UnknownAnyTy) { 7224 Match = false; 7225 break; 7226 } 7227 7228 ImplicitConversionSequence ConversionState 7229 = TryCopyInitialization(*this, argExpr, param->getType(), 7230 /*SuppressUserConversions*/false, 7231 /*InOverloadResolution=*/true, 7232 /*AllowObjCWritebackConversion=*/ 7233 getLangOpts().ObjCAutoRefCount, 7234 /*AllowExplicit*/false); 7235 // This function looks for a reasonably-exact match, so we consider 7236 // incompatible pointer conversions to be a failure here. 7237 if (ConversionState.isBad() || 7238 (ConversionState.isStandard() && 7239 ConversionState.Standard.Second == 7240 ICK_Incompatible_Pointer_Conversion)) { 7241 Match = false; 7242 break; 7243 } 7244 } 7245 // Promote additional arguments to variadic methods. 7246 if (Match && Method->isVariadic()) { 7247 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 7248 if (Args[i]->isTypeDependent()) { 7249 Match = false; 7250 break; 7251 } 7252 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 7253 nullptr); 7254 if (Arg.isInvalid()) { 7255 Match = false; 7256 break; 7257 } 7258 } 7259 } else { 7260 // Check for extra arguments to non-variadic methods. 7261 if (Args.size() != NumNamedArgs) 7262 Match = false; 7263 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 7264 // Special case when selectors have no argument. In this case, select 7265 // one with the most general result type of 'id'. 7266 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 7267 QualType ReturnT = Methods[b]->getReturnType(); 7268 if (ReturnT->isObjCIdType()) 7269 return Methods[b]; 7270 } 7271 } 7272 } 7273 7274 if (Match) 7275 return Method; 7276 } 7277 return nullptr; 7278 } 7279 7280 static bool convertArgsForAvailabilityChecks( 7281 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 7282 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 7283 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 7284 if (ThisArg) { 7285 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 7286 assert(!isa<CXXConstructorDecl>(Method) && 7287 "Shouldn't have `this` for ctors!"); 7288 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 7289 ExprResult R = S.PerformImplicitObjectArgumentInitialization( 7290 ThisArg, /*Qualifier=*/nullptr, Method, Method); 7291 if (R.isInvalid()) 7292 return false; 7293 ConvertedThis = R.get(); 7294 } else { 7295 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 7296 (void)MD; 7297 assert((MissingImplicitThis || MD->isStatic() || 7298 isa<CXXConstructorDecl>(MD)) && 7299 "Expected `this` for non-ctor instance methods"); 7300 } 7301 ConvertedThis = nullptr; 7302 } 7303 7304 // Ignore any variadic arguments. Converting them is pointless, since the 7305 // user can't refer to them in the function condition. 7306 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 7307 7308 // Convert the arguments. 7309 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 7310 ExprResult R; 7311 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 7312 S.Context, Function->getParamDecl(I)), 7313 SourceLocation(), Args[I]); 7314 7315 if (R.isInvalid()) 7316 return false; 7317 7318 ConvertedArgs.push_back(R.get()); 7319 } 7320 7321 if (Trap.hasErrorOccurred()) 7322 return false; 7323 7324 // Push default arguments if needed. 7325 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 7326 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 7327 ParmVarDecl *P = Function->getParamDecl(i); 7328 if (!P->hasDefaultArg()) 7329 return false; 7330 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 7331 if (R.isInvalid()) 7332 return false; 7333 ConvertedArgs.push_back(R.get()); 7334 } 7335 7336 if (Trap.hasErrorOccurred()) 7337 return false; 7338 } 7339 return true; 7340 } 7341 7342 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 7343 SourceLocation CallLoc, 7344 ArrayRef<Expr *> Args, 7345 bool MissingImplicitThis) { 7346 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 7347 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 7348 return nullptr; 7349 7350 SFINAETrap Trap(*this); 7351 SmallVector<Expr *, 16> ConvertedArgs; 7352 // FIXME: We should look into making enable_if late-parsed. 7353 Expr *DiscardedThis; 7354 if (!convertArgsForAvailabilityChecks( 7355 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 7356 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 7357 return *EnableIfAttrs.begin(); 7358 7359 for (auto *EIA : EnableIfAttrs) { 7360 APValue Result; 7361 // FIXME: This doesn't consider value-dependent cases, because doing so is 7362 // very difficult. Ideally, we should handle them more gracefully. 7363 if (EIA->getCond()->isValueDependent() || 7364 !EIA->getCond()->EvaluateWithSubstitution( 7365 Result, Context, Function, llvm::ArrayRef(ConvertedArgs))) 7366 return EIA; 7367 7368 if (!Result.isInt() || !Result.getInt().getBoolValue()) 7369 return EIA; 7370 } 7371 return nullptr; 7372 } 7373 7374 template <typename CheckFn> 7375 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 7376 bool ArgDependent, SourceLocation Loc, 7377 CheckFn &&IsSuccessful) { 7378 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 7379 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 7380 if (ArgDependent == DIA->getArgDependent()) 7381 Attrs.push_back(DIA); 7382 } 7383 7384 // Common case: No diagnose_if attributes, so we can quit early. 7385 if (Attrs.empty()) 7386 return false; 7387 7388 auto WarningBegin = std::stable_partition( 7389 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) { 7390 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error && 7391 DIA->getWarningGroup().empty(); 7392 }); 7393 7394 // Note that diagnose_if attributes are late-parsed, so they appear in the 7395 // correct order (unlike enable_if attributes). 7396 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 7397 IsSuccessful); 7398 if (ErrAttr != WarningBegin) { 7399 const DiagnoseIfAttr *DIA = *ErrAttr; 7400 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 7401 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 7402 << DIA->getParent() << DIA->getCond()->getSourceRange(); 7403 return true; 7404 } 7405 7406 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) { 7407 switch (Sev) { 7408 case DiagnoseIfAttr::DS_warning: 7409 return diag::Severity::Warning; 7410 case DiagnoseIfAttr::DS_error: 7411 return diag::Severity::Error; 7412 } 7413 llvm_unreachable("Fully covered switch above!"); 7414 }; 7415 7416 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 7417 if (IsSuccessful(DIA)) { 7418 if (DIA->getWarningGroup().empty() && 7419 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) { 7420 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 7421 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 7422 << DIA->getParent() << DIA->getCond()->getSourceRange(); 7423 } else { 7424 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption( 7425 DIA->getWarningGroup()); 7426 assert(DiagGroup); 7427 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID( 7428 {ToSeverity(DIA->getDefaultSeverity()), "%0", 7429 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup}); 7430 S.Diag(Loc, DiagID) << DIA->getMessage(); 7431 } 7432 } 7433 7434 return false; 7435 } 7436 7437 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 7438 const Expr *ThisArg, 7439 ArrayRef<const Expr *> Args, 7440 SourceLocation Loc) { 7441 return diagnoseDiagnoseIfAttrsWith( 7442 *this, Function, /*ArgDependent=*/true, Loc, 7443 [&](const DiagnoseIfAttr *DIA) { 7444 APValue Result; 7445 // It's sane to use the same Args for any redecl of this function, since 7446 // EvaluateWithSubstitution only cares about the position of each 7447 // argument in the arg list, not the ParmVarDecl* it maps to. 7448 if (!DIA->getCond()->EvaluateWithSubstitution( 7449 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 7450 return false; 7451 return Result.isInt() && Result.getInt().getBoolValue(); 7452 }); 7453 } 7454 7455 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 7456 SourceLocation Loc) { 7457 return diagnoseDiagnoseIfAttrsWith( 7458 *this, ND, /*ArgDependent=*/false, Loc, 7459 [&](const DiagnoseIfAttr *DIA) { 7460 bool Result; 7461 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 7462 Result; 7463 }); 7464 } 7465 7466 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 7467 ArrayRef<Expr *> Args, 7468 OverloadCandidateSet &CandidateSet, 7469 TemplateArgumentListInfo *ExplicitTemplateArgs, 7470 bool SuppressUserConversions, 7471 bool PartialOverloading, 7472 bool FirstArgumentIsBase) { 7473 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7474 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7475 ArrayRef<Expr *> FunctionArgs = Args; 7476 7477 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7478 FunctionDecl *FD = 7479 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7480 7481 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 7482 QualType ObjectType; 7483 Expr::Classification ObjectClassification; 7484 if (Args.size() > 0) { 7485 if (Expr *E = Args[0]) { 7486 // Use the explicit base to restrict the lookup: 7487 ObjectType = E->getType(); 7488 // Pointers in the object arguments are implicitly dereferenced, so we 7489 // always classify them as l-values. 7490 if (!ObjectType.isNull() && ObjectType->isPointerType()) 7491 ObjectClassification = Expr::Classification::makeSimpleLValue(); 7492 else 7493 ObjectClassification = E->Classify(Context); 7494 } // .. else there is an implicit base. 7495 FunctionArgs = Args.slice(1); 7496 } 7497 if (FunTmpl) { 7498 AddMethodTemplateCandidate( 7499 FunTmpl, F.getPair(), 7500 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 7501 ExplicitTemplateArgs, ObjectType, ObjectClassification, 7502 FunctionArgs, CandidateSet, SuppressUserConversions, 7503 PartialOverloading); 7504 } else { 7505 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 7506 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 7507 ObjectClassification, FunctionArgs, CandidateSet, 7508 SuppressUserConversions, PartialOverloading); 7509 } 7510 } else { 7511 // This branch handles both standalone functions and static methods. 7512 7513 // Slice the first argument (which is the base) when we access 7514 // static method as non-static. 7515 if (Args.size() > 0 && 7516 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 7517 !isa<CXXConstructorDecl>(FD)))) { 7518 assert(cast<CXXMethodDecl>(FD)->isStatic()); 7519 FunctionArgs = Args.slice(1); 7520 } 7521 if (FunTmpl) { 7522 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 7523 ExplicitTemplateArgs, FunctionArgs, 7524 CandidateSet, SuppressUserConversions, 7525 PartialOverloading); 7526 } else { 7527 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 7528 SuppressUserConversions, PartialOverloading); 7529 } 7530 } 7531 } 7532 } 7533 7534 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 7535 Expr::Classification ObjectClassification, 7536 ArrayRef<Expr *> Args, 7537 OverloadCandidateSet &CandidateSet, 7538 bool SuppressUserConversions, 7539 OverloadCandidateParamOrder PO) { 7540 NamedDecl *Decl = FoundDecl.getDecl(); 7541 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 7542 7543 if (isa<UsingShadowDecl>(Decl)) 7544 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 7545 7546 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 7547 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 7548 "Expected a member function template"); 7549 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 7550 /*ExplicitArgs*/ nullptr, ObjectType, 7551 ObjectClassification, Args, CandidateSet, 7552 SuppressUserConversions, false, PO); 7553 } else { 7554 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 7555 ObjectType, ObjectClassification, Args, CandidateSet, 7556 SuppressUserConversions, false, {}, PO); 7557 } 7558 } 7559 7560 void Sema::AddMethodCandidate( 7561 CXXMethodDecl *Method, DeclAccessPair FoundDecl, 7562 CXXRecordDecl *ActingContext, QualType ObjectType, 7563 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7564 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7565 bool PartialOverloading, ConversionSequenceList EarlyConversions, 7566 OverloadCandidateParamOrder PO, bool HasMatchedPackOnParmToNonPackOnArg) { 7567 const FunctionProtoType *Proto 7568 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 7569 assert(Proto && "Methods without a prototype cannot be overloaded"); 7570 assert(!isa<CXXConstructorDecl>(Method) && 7571 "Use AddOverloadCandidate for constructors"); 7572 7573 if (!CandidateSet.isNewCandidate(Method, PO)) 7574 return; 7575 7576 // C++11 [class.copy]p23: [DR1402] 7577 // A defaulted move assignment operator that is defined as deleted is 7578 // ignored by overload resolution. 7579 if (Method->isDefaulted() && Method->isDeleted() && 7580 Method->isMoveAssignmentOperator()) 7581 return; 7582 7583 // Overload resolution is always an unevaluated context. 7584 EnterExpressionEvaluationContext Unevaluated( 7585 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7586 7587 // Add this candidate 7588 OverloadCandidate &Candidate = 7589 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 7590 Candidate.FoundDecl = FoundDecl; 7591 Candidate.Function = Method; 7592 Candidate.RewriteKind = 7593 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 7594 Candidate.TookAddressOfOverload = 7595 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet; 7596 Candidate.ExplicitCallArguments = Args.size(); 7597 Candidate.HasMatchedPackOnParmToNonPackOnArg = 7598 HasMatchedPackOnParmToNonPackOnArg; 7599 7600 bool IgnoreExplicitObject = 7601 (Method->isExplicitObjectMemberFunction() && 7602 CandidateSet.getKind() == 7603 OverloadCandidateSet::CSK_AddressOfOverloadSet); 7604 bool ImplicitObjectMethodTreatedAsStatic = 7605 CandidateSet.getKind() == 7606 OverloadCandidateSet::CSK_AddressOfOverloadSet && 7607 Method->isImplicitObjectMemberFunction(); 7608 7609 unsigned ExplicitOffset = 7610 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0; 7611 7612 unsigned NumParams = Method->getNumParams() - ExplicitOffset + 7613 int(ImplicitObjectMethodTreatedAsStatic); 7614 7615 // (C++ 13.3.2p2): A candidate function having fewer than m 7616 // parameters is viable only if it has an ellipsis in its parameter 7617 // list (8.3.5). 7618 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 7619 !Proto->isVariadic() && 7620 shouldEnforceArgLimit(PartialOverloading, Method)) { 7621 Candidate.Viable = false; 7622 Candidate.FailureKind = ovl_fail_too_many_arguments; 7623 return; 7624 } 7625 7626 // (C++ 13.3.2p2): A candidate function having more than m parameters 7627 // is viable only if the (m+1)st parameter has a default argument 7628 // (8.3.6). For the purposes of overload resolution, the 7629 // parameter list is truncated on the right, so that there are 7630 // exactly m parameters. 7631 unsigned MinRequiredArgs = Method->getMinRequiredArguments() - 7632 ExplicitOffset + 7633 int(ImplicitObjectMethodTreatedAsStatic); 7634 7635 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 7636 // Not enough arguments. 7637 Candidate.Viable = false; 7638 Candidate.FailureKind = ovl_fail_too_few_arguments; 7639 return; 7640 } 7641 7642 Candidate.Viable = true; 7643 7644 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7645 if (ObjectType.isNull()) 7646 Candidate.IgnoreObjectArgument = true; 7647 else if (Method->isStatic()) { 7648 // [over.best.ics.general]p8 7649 // When the parameter is the implicit object parameter of a static member 7650 // function, the implicit conversion sequence is a standard conversion 7651 // sequence that is neither better nor worse than any other standard 7652 // conversion sequence. 7653 // 7654 // This is a rule that was introduced in C++23 to support static lambdas. We 7655 // apply it retroactively because we want to support static lambdas as an 7656 // extension and it doesn't hurt previous code. 7657 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument(); 7658 } else { 7659 // Determine the implicit conversion sequence for the object 7660 // parameter. 7661 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization( 7662 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7663 Method, ActingContext, /*InOverloadResolution=*/true); 7664 if (Candidate.Conversions[FirstConvIdx].isBad()) { 7665 Candidate.Viable = false; 7666 Candidate.FailureKind = ovl_fail_bad_conversion; 7667 return; 7668 } 7669 } 7670 7671 // (CUDA B.1): Check for invalid calls between targets. 7672 if (getLangOpts().CUDA) 7673 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true), 7674 Method)) { 7675 Candidate.Viable = false; 7676 Candidate.FailureKind = ovl_fail_bad_target; 7677 return; 7678 } 7679 7680 if (Method->getTrailingRequiresClause()) { 7681 ConstraintSatisfaction Satisfaction; 7682 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {}, 7683 /*ForOverloadResolution*/ true) || 7684 !Satisfaction.IsSatisfied) { 7685 Candidate.Viable = false; 7686 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7687 return; 7688 } 7689 } 7690 7691 // Determine the implicit conversion sequences for each of the 7692 // arguments. 7693 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7694 unsigned ConvIdx = 7695 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 7696 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7697 // We already formed a conversion sequence for this parameter during 7698 // template argument deduction. 7699 } else if (ArgIdx < NumParams) { 7700 // (C++ 13.3.2p3): for F to be a viable function, there shall 7701 // exist for each argument an implicit conversion sequence 7702 // (13.3.3.1) that converts that argument to the corresponding 7703 // parameter of F. 7704 QualType ParamType; 7705 if (ImplicitObjectMethodTreatedAsStatic) { 7706 ParamType = ArgIdx == 0 7707 ? Method->getFunctionObjectParameterReferenceType() 7708 : Proto->getParamType(ArgIdx - 1); 7709 } else { 7710 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset); 7711 } 7712 Candidate.Conversions[ConvIdx] 7713 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7714 SuppressUserConversions, 7715 /*InOverloadResolution=*/true, 7716 /*AllowObjCWritebackConversion=*/ 7717 getLangOpts().ObjCAutoRefCount); 7718 if (Candidate.Conversions[ConvIdx].isBad()) { 7719 Candidate.Viable = false; 7720 Candidate.FailureKind = ovl_fail_bad_conversion; 7721 return; 7722 } 7723 } else { 7724 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7725 // argument for which there is no corresponding parameter is 7726 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 7727 Candidate.Conversions[ConvIdx].setEllipsis(); 7728 } 7729 } 7730 7731 if (EnableIfAttr *FailedAttr = 7732 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 7733 Candidate.Viable = false; 7734 Candidate.FailureKind = ovl_fail_enable_if; 7735 Candidate.DeductionFailure.Data = FailedAttr; 7736 return; 7737 } 7738 7739 if (isNonViableMultiVersionOverload(Method)) { 7740 Candidate.Viable = false; 7741 Candidate.FailureKind = ovl_non_default_multiversion_function; 7742 } 7743 } 7744 7745 void Sema::AddMethodTemplateCandidate( 7746 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7747 CXXRecordDecl *ActingContext, 7748 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7749 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7750 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7751 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7752 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7753 return; 7754 7755 // C++ [over.match.funcs]p7: 7756 // In each case where a candidate is a function template, candidate 7757 // function template specializations are generated using template argument 7758 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7759 // candidate functions in the usual way.113) A given name can refer to one 7760 // or more function templates and also to a set of overloaded non-template 7761 // functions. In such a case, the candidate functions generated from each 7762 // function template are combined with the set of non-template candidate 7763 // functions. 7764 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7765 FunctionDecl *Specialization = nullptr; 7766 ConversionSequenceList Conversions; 7767 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7768 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7769 PartialOverloading, /*AggregateDeductionCandidate=*/false, 7770 /*PartialOrdering=*/false, ObjectType, ObjectClassification, 7771 [&](ArrayRef<QualType> ParamTypes) { 7772 return CheckNonDependentConversions( 7773 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7774 SuppressUserConversions, ActingContext, ObjectType, 7775 ObjectClassification, PO); 7776 }); 7777 Result != TemplateDeductionResult::Success) { 7778 OverloadCandidate &Candidate = 7779 CandidateSet.addCandidate(Conversions.size(), Conversions); 7780 Candidate.FoundDecl = FoundDecl; 7781 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7782 Candidate.Viable = false; 7783 Candidate.RewriteKind = 7784 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7785 Candidate.IsSurrogate = false; 7786 Candidate.IgnoreObjectArgument = 7787 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7788 ObjectType.isNull(); 7789 Candidate.ExplicitCallArguments = Args.size(); 7790 if (Result == TemplateDeductionResult::NonDependentConversionFailure) 7791 Candidate.FailureKind = ovl_fail_bad_conversion; 7792 else { 7793 Candidate.FailureKind = ovl_fail_bad_deduction; 7794 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7795 Info); 7796 } 7797 return; 7798 } 7799 7800 // Add the function template specialization produced by template argument 7801 // deduction as a candidate. 7802 assert(Specialization && "Missing member function template specialization?"); 7803 assert(isa<CXXMethodDecl>(Specialization) && 7804 "Specialization is not a member function?"); 7805 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7806 ActingContext, ObjectType, ObjectClassification, Args, 7807 CandidateSet, SuppressUserConversions, PartialOverloading, 7808 Conversions, PO, 7809 Info.hasMatchedPackOnParmToNonPackOnArg()); 7810 } 7811 7812 /// Determine whether a given function template has a simple explicit specifier 7813 /// or a non-value-dependent explicit-specification that evaluates to true. 7814 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7815 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7816 } 7817 7818 void Sema::AddTemplateOverloadCandidate( 7819 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7820 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7821 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7822 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7823 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { 7824 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7825 return; 7826 7827 // If the function template has a non-dependent explicit specification, 7828 // exclude it now if appropriate; we are not permitted to perform deduction 7829 // and substitution in this case. 7830 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7831 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7832 Candidate.FoundDecl = FoundDecl; 7833 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7834 Candidate.Viable = false; 7835 Candidate.FailureKind = ovl_fail_explicit; 7836 return; 7837 } 7838 7839 // C++ [over.match.funcs]p7: 7840 // In each case where a candidate is a function template, candidate 7841 // function template specializations are generated using template argument 7842 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7843 // candidate functions in the usual way.113) A given name can refer to one 7844 // or more function templates and also to a set of overloaded non-template 7845 // functions. In such a case, the candidate functions generated from each 7846 // function template are combined with the set of non-template candidate 7847 // functions. 7848 TemplateDeductionInfo Info(CandidateSet.getLocation(), 7849 FunctionTemplate->getTemplateDepth()); 7850 FunctionDecl *Specialization = nullptr; 7851 ConversionSequenceList Conversions; 7852 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7853 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7854 PartialOverloading, AggregateCandidateDeduction, 7855 /*PartialOrdering=*/false, 7856 /*ObjectType=*/QualType(), 7857 /*ObjectClassification=*/Expr::Classification(), 7858 [&](ArrayRef<QualType> ParamTypes) { 7859 return CheckNonDependentConversions( 7860 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7861 SuppressUserConversions, nullptr, QualType(), {}, PO); 7862 }); 7863 Result != TemplateDeductionResult::Success) { 7864 OverloadCandidate &Candidate = 7865 CandidateSet.addCandidate(Conversions.size(), Conversions); 7866 Candidate.FoundDecl = FoundDecl; 7867 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7868 Candidate.Viable = false; 7869 Candidate.RewriteKind = 7870 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7871 Candidate.IsSurrogate = false; 7872 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate); 7873 // Ignore the object argument if there is one, since we don't have an object 7874 // type. 7875 Candidate.IgnoreObjectArgument = 7876 isa<CXXMethodDecl>(Candidate.Function) && 7877 !isa<CXXConstructorDecl>(Candidate.Function); 7878 Candidate.ExplicitCallArguments = Args.size(); 7879 if (Result == TemplateDeductionResult::NonDependentConversionFailure) 7880 Candidate.FailureKind = ovl_fail_bad_conversion; 7881 else { 7882 Candidate.FailureKind = ovl_fail_bad_deduction; 7883 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7884 Info); 7885 } 7886 return; 7887 } 7888 7889 // Add the function template specialization produced by template argument 7890 // deduction as a candidate. 7891 assert(Specialization && "Missing function template specialization?"); 7892 AddOverloadCandidate( 7893 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7894 PartialOverloading, AllowExplicit, 7895 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO, 7896 Info.AggregateDeductionCandidateHasMismatchedArity, 7897 Info.hasMatchedPackOnParmToNonPackOnArg()); 7898 } 7899 7900 bool Sema::CheckNonDependentConversions( 7901 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7902 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7903 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7904 CXXRecordDecl *ActingContext, QualType ObjectType, 7905 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7906 // FIXME: The cases in which we allow explicit conversions for constructor 7907 // arguments never consider calling a constructor template. It's not clear 7908 // that is correct. 7909 const bool AllowExplicit = false; 7910 7911 auto *FD = FunctionTemplate->getTemplatedDecl(); 7912 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7913 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7914 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7915 7916 Conversions = 7917 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7918 7919 // Overload resolution is always an unevaluated context. 7920 EnterExpressionEvaluationContext Unevaluated( 7921 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7922 7923 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7924 // require that, but this check should never result in a hard error, and 7925 // overload resolution is permitted to sidestep instantiations. 7926 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7927 !ObjectType.isNull()) { 7928 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7929 if (!FD->hasCXXExplicitFunctionObjectParameter() || 7930 !ParamTypes[0]->isDependentType()) { 7931 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7932 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7933 Method, ActingContext, /*InOverloadResolution=*/true, 7934 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0] 7935 : QualType()); 7936 if (Conversions[ConvIdx].isBad()) 7937 return true; 7938 } 7939 } 7940 7941 unsigned Offset = 7942 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0; 7943 7944 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size()); 7945 I != N; ++I) { 7946 QualType ParamType = ParamTypes[I + Offset]; 7947 if (!ParamType->isDependentType()) { 7948 unsigned ConvIdx; 7949 if (PO == OverloadCandidateParamOrder::Reversed) { 7950 ConvIdx = Args.size() - 1 - I; 7951 assert(Args.size() + ThisConversions == 2 && 7952 "number of args (including 'this') must be exactly 2 for " 7953 "reversed order"); 7954 // For members, there would be only one arg 'Args[0]' whose ConvIdx 7955 // would also be 0. 'this' got ConvIdx = 1 previously. 7956 assert(!HasThisConversion || (ConvIdx == 0 && I == 0)); 7957 } else { 7958 // For members, 'this' got ConvIdx = 0 previously. 7959 ConvIdx = ThisConversions + I; 7960 } 7961 Conversions[ConvIdx] 7962 = TryCopyInitialization(*this, Args[I], ParamType, 7963 SuppressUserConversions, 7964 /*InOverloadResolution=*/true, 7965 /*AllowObjCWritebackConversion=*/ 7966 getLangOpts().ObjCAutoRefCount, 7967 AllowExplicit); 7968 if (Conversions[ConvIdx].isBad()) 7969 return true; 7970 } 7971 } 7972 7973 return false; 7974 } 7975 7976 /// Determine whether this is an allowable conversion from the result 7977 /// of an explicit conversion operator to the expected type, per C++ 7978 /// [over.match.conv]p1 and [over.match.ref]p1. 7979 /// 7980 /// \param ConvType The return type of the conversion function. 7981 /// 7982 /// \param ToType The type we are converting to. 7983 /// 7984 /// \param AllowObjCPointerConversion Allow a conversion from one 7985 /// Objective-C pointer to another. 7986 /// 7987 /// \returns true if the conversion is allowable, false otherwise. 7988 static bool isAllowableExplicitConversion(Sema &S, 7989 QualType ConvType, QualType ToType, 7990 bool AllowObjCPointerConversion) { 7991 QualType ToNonRefType = ToType.getNonReferenceType(); 7992 7993 // Easy case: the types are the same. 7994 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7995 return true; 7996 7997 // Allow qualification conversions. 7998 bool ObjCLifetimeConversion; 7999 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 8000 ObjCLifetimeConversion)) 8001 return true; 8002 8003 // If we're not allowed to consider Objective-C pointer conversions, 8004 // we're done. 8005 if (!AllowObjCPointerConversion) 8006 return false; 8007 8008 // Is this an Objective-C pointer conversion? 8009 bool IncompatibleObjC = false; 8010 QualType ConvertedType; 8011 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 8012 IncompatibleObjC); 8013 } 8014 8015 void Sema::AddConversionCandidate( 8016 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 8017 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 8018 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 8019 bool AllowExplicit, bool AllowResultConversion, 8020 bool HasMatchedPackOnParmToNonPackOnArg) { 8021 assert(!Conversion->getDescribedFunctionTemplate() && 8022 "Conversion function templates use AddTemplateConversionCandidate"); 8023 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 8024 if (!CandidateSet.isNewCandidate(Conversion)) 8025 return; 8026 8027 // If the conversion function has an undeduced return type, trigger its 8028 // deduction now. 8029 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 8030 if (DeduceReturnType(Conversion, From->getExprLoc())) 8031 return; 8032 ConvType = Conversion->getConversionType().getNonReferenceType(); 8033 } 8034 8035 // If we don't allow any conversion of the result type, ignore conversion 8036 // functions that don't convert to exactly (possibly cv-qualified) T. 8037 if (!AllowResultConversion && 8038 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 8039 return; 8040 8041 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 8042 // operator is only a candidate if its return type is the target type or 8043 // can be converted to the target type with a qualification conversion. 8044 // 8045 // FIXME: Include such functions in the candidate list and explain why we 8046 // can't select them. 8047 if (Conversion->isExplicit() && 8048 !isAllowableExplicitConversion(*this, ConvType, ToType, 8049 AllowObjCConversionOnExplicit)) 8050 return; 8051 8052 // Overload resolution is always an unevaluated context. 8053 EnterExpressionEvaluationContext Unevaluated( 8054 *this, Sema::ExpressionEvaluationContext::Unevaluated); 8055 8056 // Add this candidate 8057 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 8058 Candidate.FoundDecl = FoundDecl; 8059 Candidate.Function = Conversion; 8060 Candidate.FinalConversion.setAsIdentityConversion(); 8061 Candidate.FinalConversion.setFromType(ConvType); 8062 Candidate.FinalConversion.setAllToTypes(ToType); 8063 Candidate.Viable = true; 8064 Candidate.ExplicitCallArguments = 1; 8065 Candidate.HasMatchedPackOnParmToNonPackOnArg = 8066 HasMatchedPackOnParmToNonPackOnArg; 8067 8068 // Explicit functions are not actually candidates at all if we're not 8069 // allowing them in this context, but keep them around so we can point 8070 // to them in diagnostics. 8071 if (!AllowExplicit && Conversion->isExplicit()) { 8072 Candidate.Viable = false; 8073 Candidate.FailureKind = ovl_fail_explicit; 8074 return; 8075 } 8076 8077 // C++ [over.match.funcs]p4: 8078 // For conversion functions, the function is considered to be a member of 8079 // the class of the implicit implied object argument for the purpose of 8080 // defining the type of the implicit object parameter. 8081 // 8082 // Determine the implicit conversion sequence for the implicit 8083 // object parameter. 8084 QualType ObjectType = From->getType(); 8085 if (const auto *FromPtrType = ObjectType->getAs<PointerType>()) 8086 ObjectType = FromPtrType->getPointeeType(); 8087 const auto *ConversionContext = 8088 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl()); 8089 8090 // C++23 [over.best.ics.general] 8091 // However, if the target is [...] 8092 // - the object parameter of a user-defined conversion function 8093 // [...] user-defined conversion sequences are not considered. 8094 Candidate.Conversions[0] = TryObjectArgumentInitialization( 8095 *this, CandidateSet.getLocation(), From->getType(), 8096 From->Classify(Context), Conversion, ConversionContext, 8097 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(), 8098 /*SuppressUserConversion*/ true); 8099 8100 if (Candidate.Conversions[0].isBad()) { 8101 Candidate.Viable = false; 8102 Candidate.FailureKind = ovl_fail_bad_conversion; 8103 return; 8104 } 8105 8106 if (Conversion->getTrailingRequiresClause()) { 8107 ConstraintSatisfaction Satisfaction; 8108 if (CheckFunctionConstraints(Conversion, Satisfaction) || 8109 !Satisfaction.IsSatisfied) { 8110 Candidate.Viable = false; 8111 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 8112 return; 8113 } 8114 } 8115 8116 // We won't go through a user-defined type conversion function to convert a 8117 // derived to base as such conversions are given Conversion Rank. They only 8118 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 8119 QualType FromCanon 8120 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 8121 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 8122 if (FromCanon == ToCanon || 8123 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 8124 Candidate.Viable = false; 8125 Candidate.FailureKind = ovl_fail_trivial_conversion; 8126 return; 8127 } 8128 8129 // To determine what the conversion from the result of calling the 8130 // conversion function to the type we're eventually trying to 8131 // convert to (ToType), we need to synthesize a call to the 8132 // conversion function and attempt copy initialization from it. This 8133 // makes sure that we get the right semantics with respect to 8134 // lvalues/rvalues and the type. Fortunately, we can allocate this 8135 // call on the stack and we don't need its arguments to be 8136 // well-formed. 8137 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 8138 VK_LValue, From->getBeginLoc()); 8139 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 8140 Context.getPointerType(Conversion->getType()), 8141 CK_FunctionToPointerDecay, &ConversionRef, 8142 VK_PRValue, FPOptionsOverride()); 8143 8144 QualType ConversionType = Conversion->getConversionType(); 8145 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 8146 Candidate.Viable = false; 8147 Candidate.FailureKind = ovl_fail_bad_final_conversion; 8148 return; 8149 } 8150 8151 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 8152 8153 // Note that it is safe to allocate CallExpr on the stack here because 8154 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 8155 // allocator). 8156 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 8157 8158 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 8159 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 8160 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 8161 8162 ImplicitConversionSequence ICS = 8163 TryCopyInitialization(*this, TheTemporaryCall, ToType, 8164 /*SuppressUserConversions=*/true, 8165 /*InOverloadResolution=*/false, 8166 /*AllowObjCWritebackConversion=*/false); 8167 8168 switch (ICS.getKind()) { 8169 case ImplicitConversionSequence::StandardConversion: 8170 Candidate.FinalConversion = ICS.Standard; 8171 8172 // C++ [over.ics.user]p3: 8173 // If the user-defined conversion is specified by a specialization of a 8174 // conversion function template, the second standard conversion sequence 8175 // shall have exact match rank. 8176 if (Conversion->getPrimaryTemplate() && 8177 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 8178 Candidate.Viable = false; 8179 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 8180 return; 8181 } 8182 8183 // C++0x [dcl.init.ref]p5: 8184 // In the second case, if the reference is an rvalue reference and 8185 // the second standard conversion sequence of the user-defined 8186 // conversion sequence includes an lvalue-to-rvalue conversion, the 8187 // program is ill-formed. 8188 if (ToType->isRValueReferenceType() && 8189 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 8190 Candidate.Viable = false; 8191 Candidate.FailureKind = ovl_fail_bad_final_conversion; 8192 return; 8193 } 8194 break; 8195 8196 case ImplicitConversionSequence::BadConversion: 8197 Candidate.Viable = false; 8198 Candidate.FailureKind = ovl_fail_bad_final_conversion; 8199 return; 8200 8201 default: 8202 llvm_unreachable( 8203 "Can only end up with a standard conversion sequence or failure"); 8204 } 8205 8206 if (EnableIfAttr *FailedAttr = 8207 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) { 8208 Candidate.Viable = false; 8209 Candidate.FailureKind = ovl_fail_enable_if; 8210 Candidate.DeductionFailure.Data = FailedAttr; 8211 return; 8212 } 8213 8214 if (isNonViableMultiVersionOverload(Conversion)) { 8215 Candidate.Viable = false; 8216 Candidate.FailureKind = ovl_non_default_multiversion_function; 8217 } 8218 } 8219 8220 void Sema::AddTemplateConversionCandidate( 8221 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 8222 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 8223 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 8224 bool AllowExplicit, bool AllowResultConversion) { 8225 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 8226 "Only conversion function templates permitted here"); 8227 8228 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 8229 return; 8230 8231 // If the function template has a non-dependent explicit specification, 8232 // exclude it now if appropriate; we are not permitted to perform deduction 8233 // and substitution in this case. 8234 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 8235 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 8236 Candidate.FoundDecl = FoundDecl; 8237 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 8238 Candidate.Viable = false; 8239 Candidate.FailureKind = ovl_fail_explicit; 8240 return; 8241 } 8242 8243 QualType ObjectType = From->getType(); 8244 Expr::Classification ObjectClassification = From->Classify(getASTContext()); 8245 8246 TemplateDeductionInfo Info(CandidateSet.getLocation()); 8247 CXXConversionDecl *Specialization = nullptr; 8248 if (TemplateDeductionResult Result = DeduceTemplateArguments( 8249 FunctionTemplate, ObjectType, ObjectClassification, ToType, 8250 Specialization, Info); 8251 Result != TemplateDeductionResult::Success) { 8252 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 8253 Candidate.FoundDecl = FoundDecl; 8254 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 8255 Candidate.Viable = false; 8256 Candidate.FailureKind = ovl_fail_bad_deduction; 8257 Candidate.ExplicitCallArguments = 1; 8258 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 8259 Info); 8260 return; 8261 } 8262 8263 // Add the conversion function template specialization produced by 8264 // template argument deduction as a candidate. 8265 assert(Specialization && "Missing function template specialization?"); 8266 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 8267 CandidateSet, AllowObjCConversionOnExplicit, 8268 AllowExplicit, AllowResultConversion, 8269 Info.hasMatchedPackOnParmToNonPackOnArg()); 8270 } 8271 8272 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 8273 DeclAccessPair FoundDecl, 8274 CXXRecordDecl *ActingContext, 8275 const FunctionProtoType *Proto, 8276 Expr *Object, 8277 ArrayRef<Expr *> Args, 8278 OverloadCandidateSet& CandidateSet) { 8279 if (!CandidateSet.isNewCandidate(Conversion)) 8280 return; 8281 8282 // Overload resolution is always an unevaluated context. 8283 EnterExpressionEvaluationContext Unevaluated( 8284 *this, Sema::ExpressionEvaluationContext::Unevaluated); 8285 8286 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 8287 Candidate.FoundDecl = FoundDecl; 8288 Candidate.Function = nullptr; 8289 Candidate.Surrogate = Conversion; 8290 Candidate.IsSurrogate = true; 8291 Candidate.Viable = true; 8292 Candidate.ExplicitCallArguments = Args.size(); 8293 8294 // Determine the implicit conversion sequence for the implicit 8295 // object parameter. 8296 ImplicitConversionSequence ObjectInit; 8297 if (Conversion->hasCXXExplicitFunctionObjectParameter()) { 8298 ObjectInit = TryCopyInitialization(*this, Object, 8299 Conversion->getParamDecl(0)->getType(), 8300 /*SuppressUserConversions=*/false, 8301 /*InOverloadResolution=*/true, false); 8302 } else { 8303 ObjectInit = TryObjectArgumentInitialization( 8304 *this, CandidateSet.getLocation(), Object->getType(), 8305 Object->Classify(Context), Conversion, ActingContext); 8306 } 8307 8308 if (ObjectInit.isBad()) { 8309 Candidate.Viable = false; 8310 Candidate.FailureKind = ovl_fail_bad_conversion; 8311 Candidate.Conversions[0] = ObjectInit; 8312 return; 8313 } 8314 8315 // The first conversion is actually a user-defined conversion whose 8316 // first conversion is ObjectInit's standard conversion (which is 8317 // effectively a reference binding). Record it as such. 8318 Candidate.Conversions[0].setUserDefined(); 8319 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 8320 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 8321 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 8322 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 8323 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 8324 Candidate.Conversions[0].UserDefined.After 8325 = Candidate.Conversions[0].UserDefined.Before; 8326 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 8327 8328 // Find the 8329 unsigned NumParams = Proto->getNumParams(); 8330 8331 // (C++ 13.3.2p2): A candidate function having fewer than m 8332 // parameters is viable only if it has an ellipsis in its parameter 8333 // list (8.3.5). 8334 if (Args.size() > NumParams && !Proto->isVariadic()) { 8335 Candidate.Viable = false; 8336 Candidate.FailureKind = ovl_fail_too_many_arguments; 8337 return; 8338 } 8339 8340 // Function types don't have any default arguments, so just check if 8341 // we have enough arguments. 8342 if (Args.size() < NumParams) { 8343 // Not enough arguments. 8344 Candidate.Viable = false; 8345 Candidate.FailureKind = ovl_fail_too_few_arguments; 8346 return; 8347 } 8348 8349 // Determine the implicit conversion sequences for each of the 8350 // arguments. 8351 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8352 if (ArgIdx < NumParams) { 8353 // (C++ 13.3.2p3): for F to be a viable function, there shall 8354 // exist for each argument an implicit conversion sequence 8355 // (13.3.3.1) that converts that argument to the corresponding 8356 // parameter of F. 8357 QualType ParamType = Proto->getParamType(ArgIdx); 8358 Candidate.Conversions[ArgIdx + 1] 8359 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 8360 /*SuppressUserConversions=*/false, 8361 /*InOverloadResolution=*/false, 8362 /*AllowObjCWritebackConversion=*/ 8363 getLangOpts().ObjCAutoRefCount); 8364 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 8365 Candidate.Viable = false; 8366 Candidate.FailureKind = ovl_fail_bad_conversion; 8367 return; 8368 } 8369 } else { 8370 // (C++ 13.3.2p2): For the purposes of overload resolution, any 8371 // argument for which there is no corresponding parameter is 8372 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 8373 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 8374 } 8375 } 8376 8377 if (Conversion->getTrailingRequiresClause()) { 8378 ConstraintSatisfaction Satisfaction; 8379 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {}, 8380 /*ForOverloadResolution*/ true) || 8381 !Satisfaction.IsSatisfied) { 8382 Candidate.Viable = false; 8383 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 8384 return; 8385 } 8386 } 8387 8388 if (EnableIfAttr *FailedAttr = 8389 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) { 8390 Candidate.Viable = false; 8391 Candidate.FailureKind = ovl_fail_enable_if; 8392 Candidate.DeductionFailure.Data = FailedAttr; 8393 return; 8394 } 8395 } 8396 8397 void Sema::AddNonMemberOperatorCandidates( 8398 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 8399 OverloadCandidateSet &CandidateSet, 8400 TemplateArgumentListInfo *ExplicitTemplateArgs) { 8401 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 8402 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 8403 ArrayRef<Expr *> FunctionArgs = Args; 8404 8405 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 8406 FunctionDecl *FD = 8407 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 8408 8409 // Don't consider rewritten functions if we're not rewriting. 8410 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 8411 continue; 8412 8413 assert(!isa<CXXMethodDecl>(FD) && 8414 "unqualified operator lookup found a member function"); 8415 8416 if (FunTmpl) { 8417 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 8418 FunctionArgs, CandidateSet); 8419 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) 8420 AddTemplateOverloadCandidate( 8421 FunTmpl, F.getPair(), ExplicitTemplateArgs, 8422 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 8423 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 8424 } else { 8425 if (ExplicitTemplateArgs) 8426 continue; 8427 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 8428 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) 8429 AddOverloadCandidate(FD, F.getPair(), 8430 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 8431 false, false, true, false, ADLCallKind::NotADL, {}, 8432 OverloadCandidateParamOrder::Reversed); 8433 } 8434 } 8435 } 8436 8437 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 8438 SourceLocation OpLoc, 8439 ArrayRef<Expr *> Args, 8440 OverloadCandidateSet &CandidateSet, 8441 OverloadCandidateParamOrder PO) { 8442 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 8443 8444 // C++ [over.match.oper]p3: 8445 // For a unary operator @ with an operand of a type whose 8446 // cv-unqualified version is T1, and for a binary operator @ with 8447 // a left operand of a type whose cv-unqualified version is T1 and 8448 // a right operand of a type whose cv-unqualified version is T2, 8449 // three sets of candidate functions, designated member 8450 // candidates, non-member candidates and built-in candidates, are 8451 // constructed as follows: 8452 QualType T1 = Args[0]->getType(); 8453 8454 // -- If T1 is a complete class type or a class currently being 8455 // defined, the set of member candidates is the result of the 8456 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 8457 // the set of member candidates is empty. 8458 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 8459 // Complete the type if it can be completed. 8460 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 8461 return; 8462 // If the type is neither complete nor being defined, bail out now. 8463 if (!T1Rec->getDecl()->getDefinition()) 8464 return; 8465 8466 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 8467 LookupQualifiedName(Operators, T1Rec->getDecl()); 8468 Operators.suppressAccessDiagnostics(); 8469 8470 for (LookupResult::iterator Oper = Operators.begin(), 8471 OperEnd = Operators.end(); 8472 Oper != OperEnd; ++Oper) { 8473 if (Oper->getAsFunction() && 8474 PO == OverloadCandidateParamOrder::Reversed && 8475 !CandidateSet.getRewriteInfo().shouldAddReversed( 8476 *this, {Args[1], Args[0]}, Oper->getAsFunction())) 8477 continue; 8478 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 8479 Args[0]->Classify(Context), Args.slice(1), 8480 CandidateSet, /*SuppressUserConversion=*/false, PO); 8481 } 8482 } 8483 } 8484 8485 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 8486 OverloadCandidateSet& CandidateSet, 8487 bool IsAssignmentOperator, 8488 unsigned NumContextualBoolArguments) { 8489 // Overload resolution is always an unevaluated context. 8490 EnterExpressionEvaluationContext Unevaluated( 8491 *this, Sema::ExpressionEvaluationContext::Unevaluated); 8492 8493 // Add this candidate 8494 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 8495 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 8496 Candidate.Function = nullptr; 8497 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 8498 8499 // Determine the implicit conversion sequences for each of the 8500 // arguments. 8501 Candidate.Viable = true; 8502 Candidate.ExplicitCallArguments = Args.size(); 8503 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8504 // C++ [over.match.oper]p4: 8505 // For the built-in assignment operators, conversions of the 8506 // left operand are restricted as follows: 8507 // -- no temporaries are introduced to hold the left operand, and 8508 // -- no user-defined conversions are applied to the left 8509 // operand to achieve a type match with the left-most 8510 // parameter of a built-in candidate. 8511 // 8512 // We block these conversions by turning off user-defined 8513 // conversions, since that is the only way that initialization of 8514 // a reference to a non-class type can occur from something that 8515 // is not of the same type. 8516 if (ArgIdx < NumContextualBoolArguments) { 8517 assert(ParamTys[ArgIdx] == Context.BoolTy && 8518 "Contextual conversion to bool requires bool type"); 8519 Candidate.Conversions[ArgIdx] 8520 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 8521 } else { 8522 Candidate.Conversions[ArgIdx] 8523 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 8524 ArgIdx == 0 && IsAssignmentOperator, 8525 /*InOverloadResolution=*/false, 8526 /*AllowObjCWritebackConversion=*/ 8527 getLangOpts().ObjCAutoRefCount); 8528 } 8529 if (Candidate.Conversions[ArgIdx].isBad()) { 8530 Candidate.Viable = false; 8531 Candidate.FailureKind = ovl_fail_bad_conversion; 8532 break; 8533 } 8534 } 8535 } 8536 8537 namespace { 8538 8539 /// BuiltinCandidateTypeSet - A set of types that will be used for the 8540 /// candidate operator functions for built-in operators (C++ 8541 /// [over.built]). The types are separated into pointer types and 8542 /// enumeration types. 8543 class BuiltinCandidateTypeSet { 8544 /// TypeSet - A set of types. 8545 typedef llvm::SmallSetVector<QualType, 8> TypeSet; 8546 8547 /// PointerTypes - The set of pointer types that will be used in the 8548 /// built-in candidates. 8549 TypeSet PointerTypes; 8550 8551 /// MemberPointerTypes - The set of member pointer types that will be 8552 /// used in the built-in candidates. 8553 TypeSet MemberPointerTypes; 8554 8555 /// EnumerationTypes - The set of enumeration types that will be 8556 /// used in the built-in candidates. 8557 TypeSet EnumerationTypes; 8558 8559 /// The set of vector types that will be used in the built-in 8560 /// candidates. 8561 TypeSet VectorTypes; 8562 8563 /// The set of matrix types that will be used in the built-in 8564 /// candidates. 8565 TypeSet MatrixTypes; 8566 8567 /// The set of _BitInt types that will be used in the built-in candidates. 8568 TypeSet BitIntTypes; 8569 8570 /// A flag indicating non-record types are viable candidates 8571 bool HasNonRecordTypes; 8572 8573 /// A flag indicating whether either arithmetic or enumeration types 8574 /// were present in the candidate set. 8575 bool HasArithmeticOrEnumeralTypes; 8576 8577 /// A flag indicating whether the nullptr type was present in the 8578 /// candidate set. 8579 bool HasNullPtrType; 8580 8581 /// Sema - The semantic analysis instance where we are building the 8582 /// candidate type set. 8583 Sema &SemaRef; 8584 8585 /// Context - The AST context in which we will build the type sets. 8586 ASTContext &Context; 8587 8588 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 8589 const Qualifiers &VisibleQuals); 8590 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 8591 8592 public: 8593 /// iterator - Iterates through the types that are part of the set. 8594 typedef TypeSet::iterator iterator; 8595 8596 BuiltinCandidateTypeSet(Sema &SemaRef) 8597 : HasNonRecordTypes(false), 8598 HasArithmeticOrEnumeralTypes(false), 8599 HasNullPtrType(false), 8600 SemaRef(SemaRef), 8601 Context(SemaRef.Context) { } 8602 8603 void AddTypesConvertedFrom(QualType Ty, 8604 SourceLocation Loc, 8605 bool AllowUserConversions, 8606 bool AllowExplicitConversions, 8607 const Qualifiers &VisibleTypeConversionsQuals); 8608 8609 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 8610 llvm::iterator_range<iterator> member_pointer_types() { 8611 return MemberPointerTypes; 8612 } 8613 llvm::iterator_range<iterator> enumeration_types() { 8614 return EnumerationTypes; 8615 } 8616 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 8617 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 8618 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; } 8619 8620 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 8621 bool hasNonRecordTypes() { return HasNonRecordTypes; } 8622 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 8623 bool hasNullPtrType() const { return HasNullPtrType; } 8624 }; 8625 8626 } // end anonymous namespace 8627 8628 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 8629 /// the set of pointer types along with any more-qualified variants of 8630 /// that type. For example, if @p Ty is "int const *", this routine 8631 /// will add "int const *", "int const volatile *", "int const 8632 /// restrict *", and "int const volatile restrict *" to the set of 8633 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8634 /// false otherwise. 8635 /// 8636 /// FIXME: what to do about extended qualifiers? 8637 bool 8638 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 8639 const Qualifiers &VisibleQuals) { 8640 8641 // Insert this type. 8642 if (!PointerTypes.insert(Ty)) 8643 return false; 8644 8645 QualType PointeeTy; 8646 const PointerType *PointerTy = Ty->getAs<PointerType>(); 8647 bool buildObjCPtr = false; 8648 if (!PointerTy) { 8649 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 8650 PointeeTy = PTy->getPointeeType(); 8651 buildObjCPtr = true; 8652 } else { 8653 PointeeTy = PointerTy->getPointeeType(); 8654 } 8655 8656 // Don't add qualified variants of arrays. For one, they're not allowed 8657 // (the qualifier would sink to the element type), and for another, the 8658 // only overload situation where it matters is subscript or pointer +- int, 8659 // and those shouldn't have qualifier variants anyway. 8660 if (PointeeTy->isArrayType()) 8661 return true; 8662 8663 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8664 bool hasVolatile = VisibleQuals.hasVolatile(); 8665 bool hasRestrict = VisibleQuals.hasRestrict(); 8666 8667 // Iterate through all strict supersets of BaseCVR. 8668 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8669 if ((CVR | BaseCVR) != CVR) continue; 8670 // Skip over volatile if no volatile found anywhere in the types. 8671 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 8672 8673 // Skip over restrict if no restrict found anywhere in the types, or if 8674 // the type cannot be restrict-qualified. 8675 if ((CVR & Qualifiers::Restrict) && 8676 (!hasRestrict || 8677 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 8678 continue; 8679 8680 // Build qualified pointee type. 8681 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8682 8683 // Build qualified pointer type. 8684 QualType QPointerTy; 8685 if (!buildObjCPtr) 8686 QPointerTy = Context.getPointerType(QPointeeTy); 8687 else 8688 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 8689 8690 // Insert qualified pointer type. 8691 PointerTypes.insert(QPointerTy); 8692 } 8693 8694 return true; 8695 } 8696 8697 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 8698 /// to the set of pointer types along with any more-qualified variants of 8699 /// that type. For example, if @p Ty is "int const *", this routine 8700 /// will add "int const *", "int const volatile *", "int const 8701 /// restrict *", and "int const volatile restrict *" to the set of 8702 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8703 /// false otherwise. 8704 /// 8705 /// FIXME: what to do about extended qualifiers? 8706 bool 8707 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 8708 QualType Ty) { 8709 // Insert this type. 8710 if (!MemberPointerTypes.insert(Ty)) 8711 return false; 8712 8713 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 8714 assert(PointerTy && "type was not a member pointer type!"); 8715 8716 QualType PointeeTy = PointerTy->getPointeeType(); 8717 // Don't add qualified variants of arrays. For one, they're not allowed 8718 // (the qualifier would sink to the element type), and for another, the 8719 // only overload situation where it matters is subscript or pointer +- int, 8720 // and those shouldn't have qualifier variants anyway. 8721 if (PointeeTy->isArrayType()) 8722 return true; 8723 const Type *ClassTy = PointerTy->getClass(); 8724 8725 // Iterate through all strict supersets of the pointee type's CVR 8726 // qualifiers. 8727 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8728 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8729 if ((CVR | BaseCVR) != CVR) continue; 8730 8731 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8732 MemberPointerTypes.insert( 8733 Context.getMemberPointerType(QPointeeTy, ClassTy)); 8734 } 8735 8736 return true; 8737 } 8738 8739 /// AddTypesConvertedFrom - Add each of the types to which the type @p 8740 /// Ty can be implicit converted to the given set of @p Types. We're 8741 /// primarily interested in pointer types and enumeration types. We also 8742 /// take member pointer types, for the conditional operator. 8743 /// AllowUserConversions is true if we should look at the conversion 8744 /// functions of a class type, and AllowExplicitConversions if we 8745 /// should also include the explicit conversion functions of a class 8746 /// type. 8747 void 8748 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 8749 SourceLocation Loc, 8750 bool AllowUserConversions, 8751 bool AllowExplicitConversions, 8752 const Qualifiers &VisibleQuals) { 8753 // Only deal with canonical types. 8754 Ty = Context.getCanonicalType(Ty); 8755 8756 // Look through reference types; they aren't part of the type of an 8757 // expression for the purposes of conversions. 8758 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8759 Ty = RefTy->getPointeeType(); 8760 8761 // If we're dealing with an array type, decay to the pointer. 8762 if (Ty->isArrayType()) 8763 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8764 8765 // Otherwise, we don't care about qualifiers on the type. 8766 Ty = Ty.getLocalUnqualifiedType(); 8767 8768 // Flag if we ever add a non-record type. 8769 const RecordType *TyRec = Ty->getAs<RecordType>(); 8770 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8771 8772 // Flag if we encounter an arithmetic type. 8773 HasArithmeticOrEnumeralTypes = 8774 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8775 8776 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8777 PointerTypes.insert(Ty); 8778 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8779 // Insert our type, and its more-qualified variants, into the set 8780 // of types. 8781 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8782 return; 8783 } else if (Ty->isMemberPointerType()) { 8784 // Member pointers are far easier, since the pointee can't be converted. 8785 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8786 return; 8787 } else if (Ty->isEnumeralType()) { 8788 HasArithmeticOrEnumeralTypes = true; 8789 EnumerationTypes.insert(Ty); 8790 } else if (Ty->isBitIntType()) { 8791 HasArithmeticOrEnumeralTypes = true; 8792 BitIntTypes.insert(Ty); 8793 } else if (Ty->isVectorType()) { 8794 // We treat vector types as arithmetic types in many contexts as an 8795 // extension. 8796 HasArithmeticOrEnumeralTypes = true; 8797 VectorTypes.insert(Ty); 8798 } else if (Ty->isMatrixType()) { 8799 // Similar to vector types, we treat vector types as arithmetic types in 8800 // many contexts as an extension. 8801 HasArithmeticOrEnumeralTypes = true; 8802 MatrixTypes.insert(Ty); 8803 } else if (Ty->isNullPtrType()) { 8804 HasNullPtrType = true; 8805 } else if (AllowUserConversions && TyRec) { 8806 // No conversion functions in incomplete types. 8807 if (!SemaRef.isCompleteType(Loc, Ty)) 8808 return; 8809 8810 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8811 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8812 if (isa<UsingShadowDecl>(D)) 8813 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8814 8815 // Skip conversion function templates; they don't tell us anything 8816 // about which builtin types we can convert to. 8817 if (isa<FunctionTemplateDecl>(D)) 8818 continue; 8819 8820 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8821 if (AllowExplicitConversions || !Conv->isExplicit()) { 8822 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8823 VisibleQuals); 8824 } 8825 } 8826 } 8827 } 8828 /// Helper function for adjusting address spaces for the pointer or reference 8829 /// operands of builtin operators depending on the argument. 8830 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8831 Expr *Arg) { 8832 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8833 } 8834 8835 /// Helper function for AddBuiltinOperatorCandidates() that adds 8836 /// the volatile- and non-volatile-qualified assignment operators for the 8837 /// given type to the candidate set. 8838 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8839 QualType T, 8840 ArrayRef<Expr *> Args, 8841 OverloadCandidateSet &CandidateSet) { 8842 QualType ParamTypes[2]; 8843 8844 // T& operator=(T&, T) 8845 ParamTypes[0] = S.Context.getLValueReferenceType( 8846 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8847 ParamTypes[1] = T; 8848 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8849 /*IsAssignmentOperator=*/true); 8850 8851 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8852 // volatile T& operator=(volatile T&, T) 8853 ParamTypes[0] = S.Context.getLValueReferenceType( 8854 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8855 Args[0])); 8856 ParamTypes[1] = T; 8857 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8858 /*IsAssignmentOperator=*/true); 8859 } 8860 } 8861 8862 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8863 /// if any, found in visible type conversion functions found in ArgExpr's type. 8864 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8865 Qualifiers VRQuals; 8866 const RecordType *TyRec; 8867 if (const MemberPointerType *RHSMPType = 8868 ArgExpr->getType()->getAs<MemberPointerType>()) 8869 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8870 else 8871 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8872 if (!TyRec) { 8873 // Just to be safe, assume the worst case. 8874 VRQuals.addVolatile(); 8875 VRQuals.addRestrict(); 8876 return VRQuals; 8877 } 8878 8879 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8880 if (!ClassDecl->hasDefinition()) 8881 return VRQuals; 8882 8883 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8884 if (isa<UsingShadowDecl>(D)) 8885 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8886 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8887 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8888 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8889 CanTy = ResTypeRef->getPointeeType(); 8890 // Need to go down the pointer/mempointer chain and add qualifiers 8891 // as see them. 8892 bool done = false; 8893 while (!done) { 8894 if (CanTy.isRestrictQualified()) 8895 VRQuals.addRestrict(); 8896 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8897 CanTy = ResTypePtr->getPointeeType(); 8898 else if (const MemberPointerType *ResTypeMPtr = 8899 CanTy->getAs<MemberPointerType>()) 8900 CanTy = ResTypeMPtr->getPointeeType(); 8901 else 8902 done = true; 8903 if (CanTy.isVolatileQualified()) 8904 VRQuals.addVolatile(); 8905 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8906 return VRQuals; 8907 } 8908 } 8909 } 8910 return VRQuals; 8911 } 8912 8913 // Note: We're currently only handling qualifiers that are meaningful for the 8914 // LHS of compound assignment overloading. 8915 static void forAllQualifierCombinationsImpl( 8916 QualifiersAndAtomic Available, QualifiersAndAtomic Applied, 8917 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8918 // _Atomic 8919 if (Available.hasAtomic()) { 8920 Available.removeAtomic(); 8921 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback); 8922 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8923 return; 8924 } 8925 8926 // volatile 8927 if (Available.hasVolatile()) { 8928 Available.removeVolatile(); 8929 assert(!Applied.hasVolatile()); 8930 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(), 8931 Callback); 8932 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8933 return; 8934 } 8935 8936 Callback(Applied); 8937 } 8938 8939 static void forAllQualifierCombinations( 8940 QualifiersAndAtomic Quals, 8941 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8942 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(), 8943 Callback); 8944 } 8945 8946 static QualType makeQualifiedLValueReferenceType(QualType Base, 8947 QualifiersAndAtomic Quals, 8948 Sema &S) { 8949 if (Quals.hasAtomic()) 8950 Base = S.Context.getAtomicType(Base); 8951 if (Quals.hasVolatile()) 8952 Base = S.Context.getVolatileType(Base); 8953 return S.Context.getLValueReferenceType(Base); 8954 } 8955 8956 namespace { 8957 8958 /// Helper class to manage the addition of builtin operator overload 8959 /// candidates. It provides shared state and utility methods used throughout 8960 /// the process, as well as a helper method to add each group of builtin 8961 /// operator overloads from the standard to a candidate set. 8962 class BuiltinOperatorOverloadBuilder { 8963 // Common instance state available to all overload candidate addition methods. 8964 Sema &S; 8965 ArrayRef<Expr *> Args; 8966 QualifiersAndAtomic VisibleTypeConversionsQuals; 8967 bool HasArithmeticOrEnumeralCandidateType; 8968 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8969 OverloadCandidateSet &CandidateSet; 8970 8971 static constexpr int ArithmeticTypesCap = 26; 8972 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8973 8974 // Define some indices used to iterate over the arithmetic types in 8975 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8976 // types are that preserved by promotion (C++ [over.built]p2). 8977 unsigned FirstIntegralType, 8978 LastIntegralType; 8979 unsigned FirstPromotedIntegralType, 8980 LastPromotedIntegralType; 8981 unsigned FirstPromotedArithmeticType, 8982 LastPromotedArithmeticType; 8983 unsigned NumArithmeticTypes; 8984 8985 void InitArithmeticTypes() { 8986 // Start of promoted types. 8987 FirstPromotedArithmeticType = 0; 8988 ArithmeticTypes.push_back(S.Context.FloatTy); 8989 ArithmeticTypes.push_back(S.Context.DoubleTy); 8990 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8991 if (S.Context.getTargetInfo().hasFloat128Type()) 8992 ArithmeticTypes.push_back(S.Context.Float128Ty); 8993 if (S.Context.getTargetInfo().hasIbm128Type()) 8994 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8995 8996 // Start of integral types. 8997 FirstIntegralType = ArithmeticTypes.size(); 8998 FirstPromotedIntegralType = ArithmeticTypes.size(); 8999 ArithmeticTypes.push_back(S.Context.IntTy); 9000 ArithmeticTypes.push_back(S.Context.LongTy); 9001 ArithmeticTypes.push_back(S.Context.LongLongTy); 9002 if (S.Context.getTargetInfo().hasInt128Type() || 9003 (S.Context.getAuxTargetInfo() && 9004 S.Context.getAuxTargetInfo()->hasInt128Type())) 9005 ArithmeticTypes.push_back(S.Context.Int128Ty); 9006 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 9007 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 9008 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 9009 if (S.Context.getTargetInfo().hasInt128Type() || 9010 (S.Context.getAuxTargetInfo() && 9011 S.Context.getAuxTargetInfo()->hasInt128Type())) 9012 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 9013 9014 /// We add candidates for the unique, unqualified _BitInt types present in 9015 /// the candidate type set. The candidate set already handled ensuring the 9016 /// type is unqualified and canonical, but because we're adding from N 9017 /// different sets, we need to do some extra work to unique things. Insert 9018 /// the candidates into a unique set, then move from that set into the list 9019 /// of arithmetic types. 9020 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates; 9021 llvm::for_each(CandidateTypes, [&BitIntCandidates]( 9022 BuiltinCandidateTypeSet &Candidate) { 9023 for (QualType BitTy : Candidate.bitint_types()) 9024 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy)); 9025 }); 9026 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes)); 9027 LastPromotedIntegralType = ArithmeticTypes.size(); 9028 LastPromotedArithmeticType = ArithmeticTypes.size(); 9029 // End of promoted types. 9030 9031 ArithmeticTypes.push_back(S.Context.BoolTy); 9032 ArithmeticTypes.push_back(S.Context.CharTy); 9033 ArithmeticTypes.push_back(S.Context.WCharTy); 9034 if (S.Context.getLangOpts().Char8) 9035 ArithmeticTypes.push_back(S.Context.Char8Ty); 9036 ArithmeticTypes.push_back(S.Context.Char16Ty); 9037 ArithmeticTypes.push_back(S.Context.Char32Ty); 9038 ArithmeticTypes.push_back(S.Context.SignedCharTy); 9039 ArithmeticTypes.push_back(S.Context.ShortTy); 9040 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 9041 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 9042 LastIntegralType = ArithmeticTypes.size(); 9043 NumArithmeticTypes = ArithmeticTypes.size(); 9044 // End of integral types. 9045 // FIXME: What about complex? What about half? 9046 9047 // We don't know for sure how many bit-precise candidates were involved, so 9048 // we subtract those from the total when testing whether we're under the 9049 // cap or not. 9050 assert(ArithmeticTypes.size() - BitIntCandidates.size() <= 9051 ArithmeticTypesCap && 9052 "Enough inline storage for all arithmetic types."); 9053 } 9054 9055 /// Helper method to factor out the common pattern of adding overloads 9056 /// for '++' and '--' builtin operators. 9057 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 9058 bool HasVolatile, 9059 bool HasRestrict) { 9060 QualType ParamTypes[2] = { 9061 S.Context.getLValueReferenceType(CandidateTy), 9062 S.Context.IntTy 9063 }; 9064 9065 // Non-volatile version. 9066 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9067 9068 // Use a heuristic to reduce number of builtin candidates in the set: 9069 // add volatile version only if there are conversions to a volatile type. 9070 if (HasVolatile) { 9071 ParamTypes[0] = 9072 S.Context.getLValueReferenceType( 9073 S.Context.getVolatileType(CandidateTy)); 9074 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9075 } 9076 9077 // Add restrict version only if there are conversions to a restrict type 9078 // and our candidate type is a non-restrict-qualified pointer. 9079 if (HasRestrict && CandidateTy->isAnyPointerType() && 9080 !CandidateTy.isRestrictQualified()) { 9081 ParamTypes[0] 9082 = S.Context.getLValueReferenceType( 9083 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 9084 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9085 9086 if (HasVolatile) { 9087 ParamTypes[0] 9088 = S.Context.getLValueReferenceType( 9089 S.Context.getCVRQualifiedType(CandidateTy, 9090 (Qualifiers::Volatile | 9091 Qualifiers::Restrict))); 9092 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9093 } 9094 } 9095 9096 } 9097 9098 /// Helper to add an overload candidate for a binary builtin with types \p L 9099 /// and \p R. 9100 void AddCandidate(QualType L, QualType R) { 9101 QualType LandR[2] = {L, R}; 9102 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9103 } 9104 9105 public: 9106 BuiltinOperatorOverloadBuilder( 9107 Sema &S, ArrayRef<Expr *> Args, 9108 QualifiersAndAtomic VisibleTypeConversionsQuals, 9109 bool HasArithmeticOrEnumeralCandidateType, 9110 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 9111 OverloadCandidateSet &CandidateSet) 9112 : S(S), Args(Args), 9113 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 9114 HasArithmeticOrEnumeralCandidateType( 9115 HasArithmeticOrEnumeralCandidateType), 9116 CandidateTypes(CandidateTypes), 9117 CandidateSet(CandidateSet) { 9118 9119 InitArithmeticTypes(); 9120 } 9121 9122 // Increment is deprecated for bool since C++17. 9123 // 9124 // C++ [over.built]p3: 9125 // 9126 // For every pair (T, VQ), where T is an arithmetic type other 9127 // than bool, and VQ is either volatile or empty, there exist 9128 // candidate operator functions of the form 9129 // 9130 // VQ T& operator++(VQ T&); 9131 // T operator++(VQ T&, int); 9132 // 9133 // C++ [over.built]p4: 9134 // 9135 // For every pair (T, VQ), where T is an arithmetic type other 9136 // than bool, and VQ is either volatile or empty, there exist 9137 // candidate operator functions of the form 9138 // 9139 // VQ T& operator--(VQ T&); 9140 // T operator--(VQ T&, int); 9141 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 9142 if (!HasArithmeticOrEnumeralCandidateType) 9143 return; 9144 9145 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 9146 const auto TypeOfT = ArithmeticTypes[Arith]; 9147 if (TypeOfT == S.Context.BoolTy) { 9148 if (Op == OO_MinusMinus) 9149 continue; 9150 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 9151 continue; 9152 } 9153 addPlusPlusMinusMinusStyleOverloads( 9154 TypeOfT, 9155 VisibleTypeConversionsQuals.hasVolatile(), 9156 VisibleTypeConversionsQuals.hasRestrict()); 9157 } 9158 } 9159 9160 // C++ [over.built]p5: 9161 // 9162 // For every pair (T, VQ), where T is a cv-qualified or 9163 // cv-unqualified object type, and VQ is either volatile or 9164 // empty, there exist candidate operator functions of the form 9165 // 9166 // T*VQ& operator++(T*VQ&); 9167 // T*VQ& operator--(T*VQ&); 9168 // T* operator++(T*VQ&, int); 9169 // T* operator--(T*VQ&, int); 9170 void addPlusPlusMinusMinusPointerOverloads() { 9171 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9172 // Skip pointer types that aren't pointers to object types. 9173 if (!PtrTy->getPointeeType()->isObjectType()) 9174 continue; 9175 9176 addPlusPlusMinusMinusStyleOverloads( 9177 PtrTy, 9178 (!PtrTy.isVolatileQualified() && 9179 VisibleTypeConversionsQuals.hasVolatile()), 9180 (!PtrTy.isRestrictQualified() && 9181 VisibleTypeConversionsQuals.hasRestrict())); 9182 } 9183 } 9184 9185 // C++ [over.built]p6: 9186 // For every cv-qualified or cv-unqualified object type T, there 9187 // exist candidate operator functions of the form 9188 // 9189 // T& operator*(T*); 9190 // 9191 // C++ [over.built]p7: 9192 // For every function type T that does not have cv-qualifiers or a 9193 // ref-qualifier, there exist candidate operator functions of the form 9194 // T& operator*(T*); 9195 void addUnaryStarPointerOverloads() { 9196 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 9197 QualType PointeeTy = ParamTy->getPointeeType(); 9198 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 9199 continue; 9200 9201 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 9202 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 9203 continue; 9204 9205 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 9206 } 9207 } 9208 9209 // C++ [over.built]p9: 9210 // For every promoted arithmetic type T, there exist candidate 9211 // operator functions of the form 9212 // 9213 // T operator+(T); 9214 // T operator-(T); 9215 void addUnaryPlusOrMinusArithmeticOverloads() { 9216 if (!HasArithmeticOrEnumeralCandidateType) 9217 return; 9218 9219 for (unsigned Arith = FirstPromotedArithmeticType; 9220 Arith < LastPromotedArithmeticType; ++Arith) { 9221 QualType ArithTy = ArithmeticTypes[Arith]; 9222 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 9223 } 9224 9225 // Extension: We also add these operators for vector types. 9226 for (QualType VecTy : CandidateTypes[0].vector_types()) 9227 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 9228 } 9229 9230 // C++ [over.built]p8: 9231 // For every type T, there exist candidate operator functions of 9232 // the form 9233 // 9234 // T* operator+(T*); 9235 void addUnaryPlusPointerOverloads() { 9236 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 9237 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 9238 } 9239 9240 // C++ [over.built]p10: 9241 // For every promoted integral type T, there exist candidate 9242 // operator functions of the form 9243 // 9244 // T operator~(T); 9245 void addUnaryTildePromotedIntegralOverloads() { 9246 if (!HasArithmeticOrEnumeralCandidateType) 9247 return; 9248 9249 for (unsigned Int = FirstPromotedIntegralType; 9250 Int < LastPromotedIntegralType; ++Int) { 9251 QualType IntTy = ArithmeticTypes[Int]; 9252 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 9253 } 9254 9255 // Extension: We also add this operator for vector types. 9256 for (QualType VecTy : CandidateTypes[0].vector_types()) 9257 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 9258 } 9259 9260 // C++ [over.match.oper]p16: 9261 // For every pointer to member type T or type std::nullptr_t, there 9262 // exist candidate operator functions of the form 9263 // 9264 // bool operator==(T,T); 9265 // bool operator!=(T,T); 9266 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 9267 /// Set of (canonical) types that we've already handled. 9268 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9269 9270 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9271 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9272 // Don't add the same builtin candidate twice. 9273 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9274 continue; 9275 9276 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9277 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9278 } 9279 9280 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 9281 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 9282 if (AddedTypes.insert(NullPtrTy).second) { 9283 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 9284 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9285 } 9286 } 9287 } 9288 } 9289 9290 // C++ [over.built]p15: 9291 // 9292 // For every T, where T is an enumeration type or a pointer type, 9293 // there exist candidate operator functions of the form 9294 // 9295 // bool operator<(T, T); 9296 // bool operator>(T, T); 9297 // bool operator<=(T, T); 9298 // bool operator>=(T, T); 9299 // bool operator==(T, T); 9300 // bool operator!=(T, T); 9301 // R operator<=>(T, T) 9302 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 9303 // C++ [over.match.oper]p3: 9304 // [...]the built-in candidates include all of the candidate operator 9305 // functions defined in 13.6 that, compared to the given operator, [...] 9306 // do not have the same parameter-type-list as any non-template non-member 9307 // candidate. 9308 // 9309 // Note that in practice, this only affects enumeration types because there 9310 // aren't any built-in candidates of record type, and a user-defined operator 9311 // must have an operand of record or enumeration type. Also, the only other 9312 // overloaded operator with enumeration arguments, operator=, 9313 // cannot be overloaded for enumeration types, so this is the only place 9314 // where we must suppress candidates like this. 9315 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 9316 UserDefinedBinaryOperators; 9317 9318 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9319 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 9320 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 9321 CEnd = CandidateSet.end(); 9322 C != CEnd; ++C) { 9323 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 9324 continue; 9325 9326 if (C->Function->isFunctionTemplateSpecialization()) 9327 continue; 9328 9329 // We interpret "same parameter-type-list" as applying to the 9330 // "synthesized candidate, with the order of the two parameters 9331 // reversed", not to the original function. 9332 bool Reversed = C->isReversed(); 9333 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 9334 ->getType() 9335 .getUnqualifiedType(); 9336 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 9337 ->getType() 9338 .getUnqualifiedType(); 9339 9340 // Skip if either parameter isn't of enumeral type. 9341 if (!FirstParamType->isEnumeralType() || 9342 !SecondParamType->isEnumeralType()) 9343 continue; 9344 9345 // Add this operator to the set of known user-defined operators. 9346 UserDefinedBinaryOperators.insert( 9347 std::make_pair(S.Context.getCanonicalType(FirstParamType), 9348 S.Context.getCanonicalType(SecondParamType))); 9349 } 9350 } 9351 } 9352 9353 /// Set of (canonical) types that we've already handled. 9354 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9355 9356 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9357 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9358 // Don't add the same builtin candidate twice. 9359 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9360 continue; 9361 if (IsSpaceship && PtrTy->isFunctionPointerType()) 9362 continue; 9363 9364 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9365 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9366 } 9367 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9368 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 9369 9370 // Don't add the same builtin candidate twice, or if a user defined 9371 // candidate exists. 9372 if (!AddedTypes.insert(CanonType).second || 9373 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 9374 CanonType))) 9375 continue; 9376 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9377 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9378 } 9379 } 9380 } 9381 9382 // C++ [over.built]p13: 9383 // 9384 // For every cv-qualified or cv-unqualified object type T 9385 // there exist candidate operator functions of the form 9386 // 9387 // T* operator+(T*, ptrdiff_t); 9388 // T& operator[](T*, ptrdiff_t); [BELOW] 9389 // T* operator-(T*, ptrdiff_t); 9390 // T* operator+(ptrdiff_t, T*); 9391 // T& operator[](ptrdiff_t, T*); [BELOW] 9392 // 9393 // C++ [over.built]p14: 9394 // 9395 // For every T, where T is a pointer to object type, there 9396 // exist candidate operator functions of the form 9397 // 9398 // ptrdiff_t operator-(T, T); 9399 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 9400 /// Set of (canonical) types that we've already handled. 9401 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9402 9403 for (int Arg = 0; Arg < 2; ++Arg) { 9404 QualType AsymmetricParamTypes[2] = { 9405 S.Context.getPointerDiffType(), 9406 S.Context.getPointerDiffType(), 9407 }; 9408 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 9409 QualType PointeeTy = PtrTy->getPointeeType(); 9410 if (!PointeeTy->isObjectType()) 9411 continue; 9412 9413 AsymmetricParamTypes[Arg] = PtrTy; 9414 if (Arg == 0 || Op == OO_Plus) { 9415 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 9416 // T* operator+(ptrdiff_t, T*); 9417 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 9418 } 9419 if (Op == OO_Minus) { 9420 // ptrdiff_t operator-(T, T); 9421 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9422 continue; 9423 9424 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9425 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9426 } 9427 } 9428 } 9429 } 9430 9431 // C++ [over.built]p12: 9432 // 9433 // For every pair of promoted arithmetic types L and R, there 9434 // exist candidate operator functions of the form 9435 // 9436 // LR operator*(L, R); 9437 // LR operator/(L, R); 9438 // LR operator+(L, R); 9439 // LR operator-(L, R); 9440 // bool operator<(L, R); 9441 // bool operator>(L, R); 9442 // bool operator<=(L, R); 9443 // bool operator>=(L, R); 9444 // bool operator==(L, R); 9445 // bool operator!=(L, R); 9446 // 9447 // where LR is the result of the usual arithmetic conversions 9448 // between types L and R. 9449 // 9450 // C++ [over.built]p24: 9451 // 9452 // For every pair of promoted arithmetic types L and R, there exist 9453 // candidate operator functions of the form 9454 // 9455 // LR operator?(bool, L, R); 9456 // 9457 // where LR is the result of the usual arithmetic conversions 9458 // between types L and R. 9459 // Our candidates ignore the first parameter. 9460 void addGenericBinaryArithmeticOverloads() { 9461 if (!HasArithmeticOrEnumeralCandidateType) 9462 return; 9463 9464 for (unsigned Left = FirstPromotedArithmeticType; 9465 Left < LastPromotedArithmeticType; ++Left) { 9466 for (unsigned Right = FirstPromotedArithmeticType; 9467 Right < LastPromotedArithmeticType; ++Right) { 9468 QualType LandR[2] = { ArithmeticTypes[Left], 9469 ArithmeticTypes[Right] }; 9470 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9471 } 9472 } 9473 9474 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 9475 // conditional operator for vector types. 9476 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9477 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 9478 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 9479 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9480 } 9481 } 9482 9483 /// Add binary operator overloads for each candidate matrix type M1, M2: 9484 /// * (M1, M1) -> M1 9485 /// * (M1, M1.getElementType()) -> M1 9486 /// * (M2.getElementType(), M2) -> M2 9487 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 9488 void addMatrixBinaryArithmeticOverloads() { 9489 if (!HasArithmeticOrEnumeralCandidateType) 9490 return; 9491 9492 for (QualType M1 : CandidateTypes[0].matrix_types()) { 9493 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 9494 AddCandidate(M1, M1); 9495 } 9496 9497 for (QualType M2 : CandidateTypes[1].matrix_types()) { 9498 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 9499 if (!CandidateTypes[0].containsMatrixType(M2)) 9500 AddCandidate(M2, M2); 9501 } 9502 } 9503 9504 // C++2a [over.built]p14: 9505 // 9506 // For every integral type T there exists a candidate operator function 9507 // of the form 9508 // 9509 // std::strong_ordering operator<=>(T, T) 9510 // 9511 // C++2a [over.built]p15: 9512 // 9513 // For every pair of floating-point types L and R, there exists a candidate 9514 // operator function of the form 9515 // 9516 // std::partial_ordering operator<=>(L, R); 9517 // 9518 // FIXME: The current specification for integral types doesn't play nice with 9519 // the direction of p0946r0, which allows mixed integral and unscoped-enum 9520 // comparisons. Under the current spec this can lead to ambiguity during 9521 // overload resolution. For example: 9522 // 9523 // enum A : int {a}; 9524 // auto x = (a <=> (long)42); 9525 // 9526 // error: call is ambiguous for arguments 'A' and 'long'. 9527 // note: candidate operator<=>(int, int) 9528 // note: candidate operator<=>(long, long) 9529 // 9530 // To avoid this error, this function deviates from the specification and adds 9531 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 9532 // arithmetic types (the same as the generic relational overloads). 9533 // 9534 // For now this function acts as a placeholder. 9535 void addThreeWayArithmeticOverloads() { 9536 addGenericBinaryArithmeticOverloads(); 9537 } 9538 9539 // C++ [over.built]p17: 9540 // 9541 // For every pair of promoted integral types L and R, there 9542 // exist candidate operator functions of the form 9543 // 9544 // LR operator%(L, R); 9545 // LR operator&(L, R); 9546 // LR operator^(L, R); 9547 // LR operator|(L, R); 9548 // L operator<<(L, R); 9549 // L operator>>(L, R); 9550 // 9551 // where LR is the result of the usual arithmetic conversions 9552 // between types L and R. 9553 void addBinaryBitwiseArithmeticOverloads() { 9554 if (!HasArithmeticOrEnumeralCandidateType) 9555 return; 9556 9557 for (unsigned Left = FirstPromotedIntegralType; 9558 Left < LastPromotedIntegralType; ++Left) { 9559 for (unsigned Right = FirstPromotedIntegralType; 9560 Right < LastPromotedIntegralType; ++Right) { 9561 QualType LandR[2] = { ArithmeticTypes[Left], 9562 ArithmeticTypes[Right] }; 9563 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9564 } 9565 } 9566 } 9567 9568 // C++ [over.built]p20: 9569 // 9570 // For every pair (T, VQ), where T is an enumeration or 9571 // pointer to member type and VQ is either volatile or 9572 // empty, there exist candidate operator functions of the form 9573 // 9574 // VQ T& operator=(VQ T&, T); 9575 void addAssignmentMemberPointerOrEnumeralOverloads() { 9576 /// Set of (canonical) types that we've already handled. 9577 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9578 9579 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9580 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9581 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9582 continue; 9583 9584 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 9585 } 9586 9587 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9588 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9589 continue; 9590 9591 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 9592 } 9593 } 9594 } 9595 9596 // C++ [over.built]p19: 9597 // 9598 // For every pair (T, VQ), where T is any type and VQ is either 9599 // volatile or empty, there exist candidate operator functions 9600 // of the form 9601 // 9602 // T*VQ& operator=(T*VQ&, T*); 9603 // 9604 // C++ [over.built]p21: 9605 // 9606 // For every pair (T, VQ), where T is a cv-qualified or 9607 // cv-unqualified object type and VQ is either volatile or 9608 // empty, there exist candidate operator functions of the form 9609 // 9610 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 9611 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 9612 void addAssignmentPointerOverloads(bool isEqualOp) { 9613 /// Set of (canonical) types that we've already handled. 9614 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9615 9616 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9617 // If this is operator=, keep track of the builtin candidates we added. 9618 if (isEqualOp) 9619 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 9620 else if (!PtrTy->getPointeeType()->isObjectType()) 9621 continue; 9622 9623 // non-volatile version 9624 QualType ParamTypes[2] = { 9625 S.Context.getLValueReferenceType(PtrTy), 9626 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 9627 }; 9628 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9629 /*IsAssignmentOperator=*/ isEqualOp); 9630 9631 bool NeedVolatile = !PtrTy.isVolatileQualified() && 9632 VisibleTypeConversionsQuals.hasVolatile(); 9633 if (NeedVolatile) { 9634 // volatile version 9635 ParamTypes[0] = 9636 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 9637 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9638 /*IsAssignmentOperator=*/isEqualOp); 9639 } 9640 9641 if (!PtrTy.isRestrictQualified() && 9642 VisibleTypeConversionsQuals.hasRestrict()) { 9643 // restrict version 9644 ParamTypes[0] = 9645 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 9646 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9647 /*IsAssignmentOperator=*/isEqualOp); 9648 9649 if (NeedVolatile) { 9650 // volatile restrict version 9651 ParamTypes[0] = 9652 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 9653 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 9654 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9655 /*IsAssignmentOperator=*/isEqualOp); 9656 } 9657 } 9658 } 9659 9660 if (isEqualOp) { 9661 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9662 // Make sure we don't add the same candidate twice. 9663 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9664 continue; 9665 9666 QualType ParamTypes[2] = { 9667 S.Context.getLValueReferenceType(PtrTy), 9668 PtrTy, 9669 }; 9670 9671 // non-volatile version 9672 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9673 /*IsAssignmentOperator=*/true); 9674 9675 bool NeedVolatile = !PtrTy.isVolatileQualified() && 9676 VisibleTypeConversionsQuals.hasVolatile(); 9677 if (NeedVolatile) { 9678 // volatile version 9679 ParamTypes[0] = S.Context.getLValueReferenceType( 9680 S.Context.getVolatileType(PtrTy)); 9681 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9682 /*IsAssignmentOperator=*/true); 9683 } 9684 9685 if (!PtrTy.isRestrictQualified() && 9686 VisibleTypeConversionsQuals.hasRestrict()) { 9687 // restrict version 9688 ParamTypes[0] = S.Context.getLValueReferenceType( 9689 S.Context.getRestrictType(PtrTy)); 9690 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9691 /*IsAssignmentOperator=*/true); 9692 9693 if (NeedVolatile) { 9694 // volatile restrict version 9695 ParamTypes[0] = 9696 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 9697 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 9698 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9699 /*IsAssignmentOperator=*/true); 9700 } 9701 } 9702 } 9703 } 9704 } 9705 9706 // C++ [over.built]p18: 9707 // 9708 // For every triple (L, VQ, R), where L is an arithmetic type, 9709 // VQ is either volatile or empty, and R is a promoted 9710 // arithmetic type, there exist candidate operator functions of 9711 // the form 9712 // 9713 // VQ L& operator=(VQ L&, R); 9714 // VQ L& operator*=(VQ L&, R); 9715 // VQ L& operator/=(VQ L&, R); 9716 // VQ L& operator+=(VQ L&, R); 9717 // VQ L& operator-=(VQ L&, R); 9718 void addAssignmentArithmeticOverloads(bool isEqualOp) { 9719 if (!HasArithmeticOrEnumeralCandidateType) 9720 return; 9721 9722 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 9723 for (unsigned Right = FirstPromotedArithmeticType; 9724 Right < LastPromotedArithmeticType; ++Right) { 9725 QualType ParamTypes[2]; 9726 ParamTypes[1] = ArithmeticTypes[Right]; 9727 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9728 S, ArithmeticTypes[Left], Args[0]); 9729 9730 forAllQualifierCombinations( 9731 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9732 ParamTypes[0] = 9733 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9734 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9735 /*IsAssignmentOperator=*/isEqualOp); 9736 }); 9737 } 9738 } 9739 9740 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 9741 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9742 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 9743 QualType ParamTypes[2]; 9744 ParamTypes[1] = Vec2Ty; 9745 // Add this built-in operator as a candidate (VQ is empty). 9746 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 9747 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9748 /*IsAssignmentOperator=*/isEqualOp); 9749 9750 // Add this built-in operator as a candidate (VQ is 'volatile'). 9751 if (VisibleTypeConversionsQuals.hasVolatile()) { 9752 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 9753 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9754 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9755 /*IsAssignmentOperator=*/isEqualOp); 9756 } 9757 } 9758 } 9759 9760 // C++ [over.built]p22: 9761 // 9762 // For every triple (L, VQ, R), where L is an integral type, VQ 9763 // is either volatile or empty, and R is a promoted integral 9764 // type, there exist candidate operator functions of the form 9765 // 9766 // VQ L& operator%=(VQ L&, R); 9767 // VQ L& operator<<=(VQ L&, R); 9768 // VQ L& operator>>=(VQ L&, R); 9769 // VQ L& operator&=(VQ L&, R); 9770 // VQ L& operator^=(VQ L&, R); 9771 // VQ L& operator|=(VQ L&, R); 9772 void addAssignmentIntegralOverloads() { 9773 if (!HasArithmeticOrEnumeralCandidateType) 9774 return; 9775 9776 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 9777 for (unsigned Right = FirstPromotedIntegralType; 9778 Right < LastPromotedIntegralType; ++Right) { 9779 QualType ParamTypes[2]; 9780 ParamTypes[1] = ArithmeticTypes[Right]; 9781 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9782 S, ArithmeticTypes[Left], Args[0]); 9783 9784 forAllQualifierCombinations( 9785 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9786 ParamTypes[0] = 9787 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9788 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9789 }); 9790 } 9791 } 9792 } 9793 9794 // C++ [over.operator]p23: 9795 // 9796 // There also exist candidate operator functions of the form 9797 // 9798 // bool operator!(bool); 9799 // bool operator&&(bool, bool); 9800 // bool operator||(bool, bool); 9801 void addExclaimOverload() { 9802 QualType ParamTy = S.Context.BoolTy; 9803 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9804 /*IsAssignmentOperator=*/false, 9805 /*NumContextualBoolArguments=*/1); 9806 } 9807 void addAmpAmpOrPipePipeOverload() { 9808 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9809 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9810 /*IsAssignmentOperator=*/false, 9811 /*NumContextualBoolArguments=*/2); 9812 } 9813 9814 // C++ [over.built]p13: 9815 // 9816 // For every cv-qualified or cv-unqualified object type T there 9817 // exist candidate operator functions of the form 9818 // 9819 // T* operator+(T*, ptrdiff_t); [ABOVE] 9820 // T& operator[](T*, ptrdiff_t); 9821 // T* operator-(T*, ptrdiff_t); [ABOVE] 9822 // T* operator+(ptrdiff_t, T*); [ABOVE] 9823 // T& operator[](ptrdiff_t, T*); 9824 void addSubscriptOverloads() { 9825 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9826 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9827 QualType PointeeType = PtrTy->getPointeeType(); 9828 if (!PointeeType->isObjectType()) 9829 continue; 9830 9831 // T& operator[](T*, ptrdiff_t) 9832 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9833 } 9834 9835 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9836 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9837 QualType PointeeType = PtrTy->getPointeeType(); 9838 if (!PointeeType->isObjectType()) 9839 continue; 9840 9841 // T& operator[](ptrdiff_t, T*) 9842 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9843 } 9844 } 9845 9846 // C++ [over.built]p11: 9847 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9848 // C1 is the same type as C2 or is a derived class of C2, T is an object 9849 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9850 // there exist candidate operator functions of the form 9851 // 9852 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9853 // 9854 // where CV12 is the union of CV1 and CV2. 9855 void addArrowStarOverloads() { 9856 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9857 QualType C1Ty = PtrTy; 9858 QualType C1; 9859 QualifierCollector Q1; 9860 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9861 if (!isa<RecordType>(C1)) 9862 continue; 9863 // heuristic to reduce number of builtin candidates in the set. 9864 // Add volatile/restrict version only if there are conversions to a 9865 // volatile/restrict type. 9866 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9867 continue; 9868 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9869 continue; 9870 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9871 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9872 QualType C2 = QualType(mptr->getClass(), 0); 9873 C2 = C2.getUnqualifiedType(); 9874 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9875 break; 9876 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9877 // build CV12 T& 9878 QualType T = mptr->getPointeeType(); 9879 if (!VisibleTypeConversionsQuals.hasVolatile() && 9880 T.isVolatileQualified()) 9881 continue; 9882 if (!VisibleTypeConversionsQuals.hasRestrict() && 9883 T.isRestrictQualified()) 9884 continue; 9885 T = Q1.apply(S.Context, T); 9886 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9887 } 9888 } 9889 } 9890 9891 // Note that we don't consider the first argument, since it has been 9892 // contextually converted to bool long ago. The candidates below are 9893 // therefore added as binary. 9894 // 9895 // C++ [over.built]p25: 9896 // For every type T, where T is a pointer, pointer-to-member, or scoped 9897 // enumeration type, there exist candidate operator functions of the form 9898 // 9899 // T operator?(bool, T, T); 9900 // 9901 void addConditionalOperatorOverloads() { 9902 /// Set of (canonical) types that we've already handled. 9903 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9904 9905 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9906 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9907 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9908 continue; 9909 9910 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9911 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9912 } 9913 9914 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9915 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9916 continue; 9917 9918 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9919 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9920 } 9921 9922 if (S.getLangOpts().CPlusPlus11) { 9923 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9924 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9925 continue; 9926 9927 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9928 continue; 9929 9930 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9931 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9932 } 9933 } 9934 } 9935 } 9936 }; 9937 9938 } // end anonymous namespace 9939 9940 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9941 SourceLocation OpLoc, 9942 ArrayRef<Expr *> Args, 9943 OverloadCandidateSet &CandidateSet) { 9944 // Find all of the types that the arguments can convert to, but only 9945 // if the operator we're looking at has built-in operator candidates 9946 // that make use of these types. Also record whether we encounter non-record 9947 // candidate types or either arithmetic or enumeral candidate types. 9948 QualifiersAndAtomic VisibleTypeConversionsQuals; 9949 VisibleTypeConversionsQuals.addConst(); 9950 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9951 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9952 if (Args[ArgIdx]->getType()->isAtomicType()) 9953 VisibleTypeConversionsQuals.addAtomic(); 9954 } 9955 9956 bool HasNonRecordCandidateType = false; 9957 bool HasArithmeticOrEnumeralCandidateType = false; 9958 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9959 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9960 CandidateTypes.emplace_back(*this); 9961 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9962 OpLoc, 9963 true, 9964 (Op == OO_Exclaim || 9965 Op == OO_AmpAmp || 9966 Op == OO_PipePipe), 9967 VisibleTypeConversionsQuals); 9968 HasNonRecordCandidateType = HasNonRecordCandidateType || 9969 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9970 HasArithmeticOrEnumeralCandidateType = 9971 HasArithmeticOrEnumeralCandidateType || 9972 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9973 } 9974 9975 // Exit early when no non-record types have been added to the candidate set 9976 // for any of the arguments to the operator. 9977 // 9978 // We can't exit early for !, ||, or &&, since there we have always have 9979 // 'bool' overloads. 9980 if (!HasNonRecordCandidateType && 9981 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9982 return; 9983 9984 // Setup an object to manage the common state for building overloads. 9985 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9986 VisibleTypeConversionsQuals, 9987 HasArithmeticOrEnumeralCandidateType, 9988 CandidateTypes, CandidateSet); 9989 9990 // Dispatch over the operation to add in only those overloads which apply. 9991 switch (Op) { 9992 case OO_None: 9993 case NUM_OVERLOADED_OPERATORS: 9994 llvm_unreachable("Expected an overloaded operator"); 9995 9996 case OO_New: 9997 case OO_Delete: 9998 case OO_Array_New: 9999 case OO_Array_Delete: 10000 case OO_Call: 10001 llvm_unreachable( 10002 "Special operators don't use AddBuiltinOperatorCandidates"); 10003 10004 case OO_Comma: 10005 case OO_Arrow: 10006 case OO_Coawait: 10007 // C++ [over.match.oper]p3: 10008 // -- For the operator ',', the unary operator '&', the 10009 // operator '->', or the operator 'co_await', the 10010 // built-in candidates set is empty. 10011 break; 10012 10013 case OO_Plus: // '+' is either unary or binary 10014 if (Args.size() == 1) 10015 OpBuilder.addUnaryPlusPointerOverloads(); 10016 [[fallthrough]]; 10017 10018 case OO_Minus: // '-' is either unary or binary 10019 if (Args.size() == 1) { 10020 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 10021 } else { 10022 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 10023 OpBuilder.addGenericBinaryArithmeticOverloads(); 10024 OpBuilder.addMatrixBinaryArithmeticOverloads(); 10025 } 10026 break; 10027 10028 case OO_Star: // '*' is either unary or binary 10029 if (Args.size() == 1) 10030 OpBuilder.addUnaryStarPointerOverloads(); 10031 else { 10032 OpBuilder.addGenericBinaryArithmeticOverloads(); 10033 OpBuilder.addMatrixBinaryArithmeticOverloads(); 10034 } 10035 break; 10036 10037 case OO_Slash: 10038 OpBuilder.addGenericBinaryArithmeticOverloads(); 10039 break; 10040 10041 case OO_PlusPlus: 10042 case OO_MinusMinus: 10043 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 10044 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 10045 break; 10046 10047 case OO_EqualEqual: 10048 case OO_ExclaimEqual: 10049 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 10050 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 10051 OpBuilder.addGenericBinaryArithmeticOverloads(); 10052 break; 10053 10054 case OO_Less: 10055 case OO_Greater: 10056 case OO_LessEqual: 10057 case OO_GreaterEqual: 10058 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 10059 OpBuilder.addGenericBinaryArithmeticOverloads(); 10060 break; 10061 10062 case OO_Spaceship: 10063 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 10064 OpBuilder.addThreeWayArithmeticOverloads(); 10065 break; 10066 10067 case OO_Percent: 10068 case OO_Caret: 10069 case OO_Pipe: 10070 case OO_LessLess: 10071 case OO_GreaterGreater: 10072 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 10073 break; 10074 10075 case OO_Amp: // '&' is either unary or binary 10076 if (Args.size() == 1) 10077 // C++ [over.match.oper]p3: 10078 // -- For the operator ',', the unary operator '&', or the 10079 // operator '->', the built-in candidates set is empty. 10080 break; 10081 10082 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 10083 break; 10084 10085 case OO_Tilde: 10086 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 10087 break; 10088 10089 case OO_Equal: 10090 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 10091 [[fallthrough]]; 10092 10093 case OO_PlusEqual: 10094 case OO_MinusEqual: 10095 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 10096 [[fallthrough]]; 10097 10098 case OO_StarEqual: 10099 case OO_SlashEqual: 10100 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 10101 break; 10102 10103 case OO_PercentEqual: 10104 case OO_LessLessEqual: 10105 case OO_GreaterGreaterEqual: 10106 case OO_AmpEqual: 10107 case OO_CaretEqual: 10108 case OO_PipeEqual: 10109 OpBuilder.addAssignmentIntegralOverloads(); 10110 break; 10111 10112 case OO_Exclaim: 10113 OpBuilder.addExclaimOverload(); 10114 break; 10115 10116 case OO_AmpAmp: 10117 case OO_PipePipe: 10118 OpBuilder.addAmpAmpOrPipePipeOverload(); 10119 break; 10120 10121 case OO_Subscript: 10122 if (Args.size() == 2) 10123 OpBuilder.addSubscriptOverloads(); 10124 break; 10125 10126 case OO_ArrowStar: 10127 OpBuilder.addArrowStarOverloads(); 10128 break; 10129 10130 case OO_Conditional: 10131 OpBuilder.addConditionalOperatorOverloads(); 10132 OpBuilder.addGenericBinaryArithmeticOverloads(); 10133 break; 10134 } 10135 } 10136 10137 void 10138 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 10139 SourceLocation Loc, 10140 ArrayRef<Expr *> Args, 10141 TemplateArgumentListInfo *ExplicitTemplateArgs, 10142 OverloadCandidateSet& CandidateSet, 10143 bool PartialOverloading) { 10144 ADLResult Fns; 10145 10146 // FIXME: This approach for uniquing ADL results (and removing 10147 // redundant candidates from the set) relies on pointer-equality, 10148 // which means we need to key off the canonical decl. However, 10149 // always going back to the canonical decl might not get us the 10150 // right set of default arguments. What default arguments are 10151 // we supposed to consider on ADL candidates, anyway? 10152 10153 // FIXME: Pass in the explicit template arguments? 10154 ArgumentDependentLookup(Name, Loc, Args, Fns); 10155 10156 // Erase all of the candidates we already knew about. 10157 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 10158 CandEnd = CandidateSet.end(); 10159 Cand != CandEnd; ++Cand) 10160 if (Cand->Function) { 10161 FunctionDecl *Fn = Cand->Function; 10162 Fns.erase(Fn); 10163 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) 10164 Fns.erase(FunTmpl); 10165 } 10166 10167 // For each of the ADL candidates we found, add it to the overload 10168 // set. 10169 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 10170 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 10171 10172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 10173 if (ExplicitTemplateArgs) 10174 continue; 10175 10176 AddOverloadCandidate( 10177 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 10178 PartialOverloading, /*AllowExplicit=*/true, 10179 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); 10180 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) { 10181 AddOverloadCandidate( 10182 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 10183 /*SuppressUserConversions=*/false, PartialOverloading, 10184 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, 10185 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed); 10186 } 10187 } else { 10188 auto *FTD = cast<FunctionTemplateDecl>(*I); 10189 AddTemplateOverloadCandidate( 10190 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 10191 /*SuppressUserConversions=*/false, PartialOverloading, 10192 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 10193 if (CandidateSet.getRewriteInfo().shouldAddReversed( 10194 *this, Args, FTD->getTemplatedDecl())) { 10195 AddTemplateOverloadCandidate( 10196 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 10197 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 10198 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 10199 OverloadCandidateParamOrder::Reversed); 10200 } 10201 } 10202 } 10203 } 10204 10205 namespace { 10206 enum class Comparison { Equal, Better, Worse }; 10207 } 10208 10209 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 10210 /// overload resolution. 10211 /// 10212 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 10213 /// Cand1's first N enable_if attributes have precisely the same conditions as 10214 /// Cand2's first N enable_if attributes (where N = the number of enable_if 10215 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 10216 /// 10217 /// Note that you can have a pair of candidates such that Cand1's enable_if 10218 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 10219 /// worse than Cand1's. 10220 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 10221 const FunctionDecl *Cand2) { 10222 // Common case: One (or both) decls don't have enable_if attrs. 10223 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 10224 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 10225 if (!Cand1Attr || !Cand2Attr) { 10226 if (Cand1Attr == Cand2Attr) 10227 return Comparison::Equal; 10228 return Cand1Attr ? Comparison::Better : Comparison::Worse; 10229 } 10230 10231 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 10232 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 10233 10234 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 10235 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 10236 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 10237 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 10238 10239 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 10240 // has fewer enable_if attributes than Cand2, and vice versa. 10241 if (!Cand1A) 10242 return Comparison::Worse; 10243 if (!Cand2A) 10244 return Comparison::Better; 10245 10246 Cand1ID.clear(); 10247 Cand2ID.clear(); 10248 10249 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 10250 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 10251 if (Cand1ID != Cand2ID) 10252 return Comparison::Worse; 10253 } 10254 10255 return Comparison::Equal; 10256 } 10257 10258 static Comparison 10259 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 10260 const OverloadCandidate &Cand2) { 10261 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 10262 !Cand2.Function->isMultiVersion()) 10263 return Comparison::Equal; 10264 10265 // If both are invalid, they are equal. If one of them is invalid, the other 10266 // is better. 10267 if (Cand1.Function->isInvalidDecl()) { 10268 if (Cand2.Function->isInvalidDecl()) 10269 return Comparison::Equal; 10270 return Comparison::Worse; 10271 } 10272 if (Cand2.Function->isInvalidDecl()) 10273 return Comparison::Better; 10274 10275 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 10276 // cpu_dispatch, else arbitrarily based on the identifiers. 10277 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 10278 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 10279 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 10280 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 10281 10282 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 10283 return Comparison::Equal; 10284 10285 if (Cand1CPUDisp && !Cand2CPUDisp) 10286 return Comparison::Better; 10287 if (Cand2CPUDisp && !Cand1CPUDisp) 10288 return Comparison::Worse; 10289 10290 if (Cand1CPUSpec && Cand2CPUSpec) { 10291 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 10292 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 10293 ? Comparison::Better 10294 : Comparison::Worse; 10295 10296 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 10297 FirstDiff = std::mismatch( 10298 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 10299 Cand2CPUSpec->cpus_begin(), 10300 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 10301 return LHS->getName() == RHS->getName(); 10302 }); 10303 10304 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 10305 "Two different cpu-specific versions should not have the same " 10306 "identifier list, otherwise they'd be the same decl!"); 10307 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 10308 ? Comparison::Better 10309 : Comparison::Worse; 10310 } 10311 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 10312 } 10313 10314 /// Compute the type of the implicit object parameter for the given function, 10315 /// if any. Returns std::nullopt if there is no implicit object parameter, and a 10316 /// null QualType if there is a 'matches anything' implicit object parameter. 10317 static std::optional<QualType> 10318 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) { 10319 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 10320 return std::nullopt; 10321 10322 auto *M = cast<CXXMethodDecl>(F); 10323 // Static member functions' object parameters match all types. 10324 if (M->isStatic()) 10325 return QualType(); 10326 return M->getFunctionObjectParameterReferenceType(); 10327 } 10328 10329 // As a Clang extension, allow ambiguity among F1 and F2 if they represent 10330 // represent the same entity. 10331 static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, 10332 const FunctionDecl *F2) { 10333 if (declaresSameEntity(F1, F2)) 10334 return true; 10335 auto PT1 = F1->getPrimaryTemplate(); 10336 auto PT2 = F2->getPrimaryTemplate(); 10337 if (PT1 && PT2) { 10338 if (declaresSameEntity(PT1, PT2) || 10339 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(), 10340 PT2->getInstantiatedFromMemberTemplate())) 10341 return true; 10342 } 10343 // TODO: It is not clear whether comparing parameters is necessary (i.e. 10344 // different functions with same params). Consider removing this (as no test 10345 // fail w/o it). 10346 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 10347 if (First) { 10348 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F)) 10349 return *T; 10350 } 10351 assert(I < F->getNumParams()); 10352 return F->getParamDecl(I++)->getType(); 10353 }; 10354 10355 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1); 10356 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2); 10357 10358 if (F1NumParams != F2NumParams) 10359 return false; 10360 10361 unsigned I1 = 0, I2 = 0; 10362 for (unsigned I = 0; I != F1NumParams; ++I) { 10363 QualType T1 = NextParam(F1, I1, I == 0); 10364 QualType T2 = NextParam(F2, I2, I == 0); 10365 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); 10366 if (!Context.hasSameUnqualifiedType(T1, T2)) 10367 return false; 10368 } 10369 return true; 10370 } 10371 10372 /// We're allowed to use constraints partial ordering only if the candidates 10373 /// have the same parameter types: 10374 /// [over.match.best.general]p2.6 10375 /// F1 and F2 are non-template functions with the same 10376 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...] 10377 static bool sameFunctionParameterTypeLists(Sema &S, 10378 const OverloadCandidate &Cand1, 10379 const OverloadCandidate &Cand2) { 10380 if (!Cand1.Function || !Cand2.Function) 10381 return false; 10382 10383 FunctionDecl *Fn1 = Cand1.Function; 10384 FunctionDecl *Fn2 = Cand2.Function; 10385 10386 if (Fn1->isVariadic() != Fn2->isVariadic()) 10387 return false; 10388 10389 if (!S.FunctionNonObjectParamTypesAreEqual( 10390 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed())) 10391 return false; 10392 10393 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1); 10394 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2); 10395 if (Mem1 && Mem2) { 10396 // if they are member functions, both are direct members of the same class, 10397 // and 10398 if (Mem1->getParent() != Mem2->getParent()) 10399 return false; 10400 // if both are non-static member functions, they have the same types for 10401 // their object parameters 10402 if (Mem1->isInstance() && Mem2->isInstance() && 10403 !S.getASTContext().hasSameType( 10404 Mem1->getFunctionObjectParameterReferenceType(), 10405 Mem1->getFunctionObjectParameterReferenceType())) 10406 return false; 10407 } 10408 return true; 10409 } 10410 10411 /// isBetterOverloadCandidate - Determines whether the first overload 10412 /// candidate is a better candidate than the second (C++ 13.3.3p1). 10413 bool clang::isBetterOverloadCandidate( 10414 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 10415 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 10416 // Define viable functions to be better candidates than non-viable 10417 // functions. 10418 if (!Cand2.Viable) 10419 return Cand1.Viable; 10420 else if (!Cand1.Viable) 10421 return false; 10422 10423 // [CUDA] A function with 'never' preference is marked not viable, therefore 10424 // is never shown up here. The worst preference shown up here is 'wrong side', 10425 // e.g. an H function called by a HD function in device compilation. This is 10426 // valid AST as long as the HD function is not emitted, e.g. it is an inline 10427 // function which is called only by an H function. A deferred diagnostic will 10428 // be triggered if it is emitted. However a wrong-sided function is still 10429 // a viable candidate here. 10430 // 10431 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 10432 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 10433 // can be emitted, Cand1 is not better than Cand2. This rule should have 10434 // precedence over other rules. 10435 // 10436 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 10437 // other rules should be used to determine which is better. This is because 10438 // host/device based overloading resolution is mostly for determining 10439 // viability of a function. If two functions are both viable, other factors 10440 // should take precedence in preference, e.g. the standard-defined preferences 10441 // like argument conversion ranks or enable_if partial-ordering. The 10442 // preference for pass-object-size parameters is probably most similar to a 10443 // type-based-overloading decision and so should take priority. 10444 // 10445 // If other rules cannot determine which is better, CUDA preference will be 10446 // used again to determine which is better. 10447 // 10448 // TODO: Currently IdentifyPreference does not return correct values 10449 // for functions called in global variable initializers due to missing 10450 // correct context about device/host. Therefore we can only enforce this 10451 // rule when there is a caller. We should enforce this rule for functions 10452 // in global variable initializers once proper context is added. 10453 // 10454 // TODO: We can only enable the hostness based overloading resolution when 10455 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 10456 // overloading resolution diagnostics. 10457 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 10458 S.getLangOpts().GPUExcludeWrongSideOverloads) { 10459 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { 10460 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller); 10461 bool IsCand1ImplicitHD = 10462 SemaCUDA::isImplicitHostDeviceFunction(Cand1.Function); 10463 bool IsCand2ImplicitHD = 10464 SemaCUDA::isImplicitHostDeviceFunction(Cand2.Function); 10465 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function); 10466 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function); 10467 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never); 10468 // The implicit HD function may be a function in a system header which 10469 // is forced by pragma. In device compilation, if we prefer HD candidates 10470 // over wrong-sided candidates, overloading resolution may change, which 10471 // may result in non-deferrable diagnostics. As a workaround, we let 10472 // implicit HD candidates take equal preference as wrong-sided candidates. 10473 // This will preserve the overloading resolution. 10474 // TODO: We still need special handling of implicit HD functions since 10475 // they may incur other diagnostics to be deferred. We should make all 10476 // host/device related diagnostics deferrable and remove special handling 10477 // of implicit HD functions. 10478 auto EmitThreshold = 10479 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 10480 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 10481 ? SemaCUDA::CFP_Never 10482 : SemaCUDA::CFP_WrongSide; 10483 auto Cand1Emittable = P1 > EmitThreshold; 10484 auto Cand2Emittable = P2 > EmitThreshold; 10485 if (Cand1Emittable && !Cand2Emittable) 10486 return true; 10487 if (!Cand1Emittable && Cand2Emittable) 10488 return false; 10489 } 10490 } 10491 10492 // C++ [over.match.best]p1: (Changed in C++23) 10493 // 10494 // -- if F is a static member function, ICS1(F) is defined such 10495 // that ICS1(F) is neither better nor worse than ICS1(G) for 10496 // any function G, and, symmetrically, ICS1(G) is neither 10497 // better nor worse than ICS1(F). 10498 unsigned StartArg = 0; 10499 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 10500 StartArg = 1; 10501 10502 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 10503 // We don't allow incompatible pointer conversions in C++. 10504 if (!S.getLangOpts().CPlusPlus) 10505 return ICS.isStandard() && 10506 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 10507 10508 // The only ill-formed conversion we allow in C++ is the string literal to 10509 // char* conversion, which is only considered ill-formed after C++11. 10510 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 10511 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 10512 }; 10513 10514 // Define functions that don't require ill-formed conversions for a given 10515 // argument to be better candidates than functions that do. 10516 unsigned NumArgs = Cand1.Conversions.size(); 10517 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 10518 bool HasBetterConversion = false; 10519 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 10520 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 10521 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 10522 if (Cand1Bad != Cand2Bad) { 10523 if (Cand1Bad) 10524 return false; 10525 HasBetterConversion = true; 10526 } 10527 } 10528 10529 if (HasBetterConversion) 10530 return true; 10531 10532 // C++ [over.match.best]p1: 10533 // A viable function F1 is defined to be a better function than another 10534 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 10535 // conversion sequence than ICSi(F2), and then... 10536 bool HasWorseConversion = false; 10537 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 10538 switch (CompareImplicitConversionSequences(S, Loc, 10539 Cand1.Conversions[ArgIdx], 10540 Cand2.Conversions[ArgIdx])) { 10541 case ImplicitConversionSequence::Better: 10542 // Cand1 has a better conversion sequence. 10543 HasBetterConversion = true; 10544 break; 10545 10546 case ImplicitConversionSequence::Worse: 10547 if (Cand1.Function && Cand2.Function && 10548 Cand1.isReversed() != Cand2.isReversed() && 10549 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) { 10550 // Work around large-scale breakage caused by considering reversed 10551 // forms of operator== in C++20: 10552 // 10553 // When comparing a function against a reversed function, if we have a 10554 // better conversion for one argument and a worse conversion for the 10555 // other, the implicit conversion sequences are treated as being equally 10556 // good. 10557 // 10558 // This prevents a comparison function from being considered ambiguous 10559 // with a reversed form that is written in the same way. 10560 // 10561 // We diagnose this as an extension from CreateOverloadedBinOp. 10562 HasWorseConversion = true; 10563 break; 10564 } 10565 10566 // Cand1 can't be better than Cand2. 10567 return false; 10568 10569 case ImplicitConversionSequence::Indistinguishable: 10570 // Do nothing. 10571 break; 10572 } 10573 } 10574 10575 // -- for some argument j, ICSj(F1) is a better conversion sequence than 10576 // ICSj(F2), or, if not that, 10577 if (HasBetterConversion && !HasWorseConversion) 10578 return true; 10579 10580 // -- the context is an initialization by user-defined conversion 10581 // (see 8.5, 13.3.1.5) and the standard conversion sequence 10582 // from the return type of F1 to the destination type (i.e., 10583 // the type of the entity being initialized) is a better 10584 // conversion sequence than the standard conversion sequence 10585 // from the return type of F2 to the destination type. 10586 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 10587 Cand1.Function && Cand2.Function && 10588 isa<CXXConversionDecl>(Cand1.Function) && 10589 isa<CXXConversionDecl>(Cand2.Function)) { 10590 // First check whether we prefer one of the conversion functions over the 10591 // other. This only distinguishes the results in non-standard, extension 10592 // cases such as the conversion from a lambda closure type to a function 10593 // pointer or block. 10594 ImplicitConversionSequence::CompareKind Result = 10595 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 10596 if (Result == ImplicitConversionSequence::Indistinguishable) 10597 Result = CompareStandardConversionSequences(S, Loc, 10598 Cand1.FinalConversion, 10599 Cand2.FinalConversion); 10600 10601 if (Result != ImplicitConversionSequence::Indistinguishable) 10602 return Result == ImplicitConversionSequence::Better; 10603 10604 // FIXME: Compare kind of reference binding if conversion functions 10605 // convert to a reference type used in direct reference binding, per 10606 // C++14 [over.match.best]p1 section 2 bullet 3. 10607 } 10608 10609 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 10610 // as combined with the resolution to CWG issue 243. 10611 // 10612 // When the context is initialization by constructor ([over.match.ctor] or 10613 // either phase of [over.match.list]), a constructor is preferred over 10614 // a conversion function. 10615 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 10616 Cand1.Function && Cand2.Function && 10617 isa<CXXConstructorDecl>(Cand1.Function) != 10618 isa<CXXConstructorDecl>(Cand2.Function)) 10619 return isa<CXXConstructorDecl>(Cand1.Function); 10620 10621 if (Cand1.HasMatchedPackOnParmToNonPackOnArg != 10622 Cand2.HasMatchedPackOnParmToNonPackOnArg) 10623 return Cand2.HasMatchedPackOnParmToNonPackOnArg; 10624 10625 // -- F1 is a non-template function and F2 is a function template 10626 // specialization, or, if not that, 10627 bool Cand1IsSpecialization = Cand1.Function && 10628 Cand1.Function->getPrimaryTemplate(); 10629 bool Cand2IsSpecialization = Cand2.Function && 10630 Cand2.Function->getPrimaryTemplate(); 10631 if (Cand1IsSpecialization != Cand2IsSpecialization) 10632 return Cand2IsSpecialization; 10633 10634 // -- F1 and F2 are function template specializations, and the function 10635 // template for F1 is more specialized than the template for F2 10636 // according to the partial ordering rules described in 14.5.5.2, or, 10637 // if not that, 10638 if (Cand1IsSpecialization && Cand2IsSpecialization) { 10639 const auto *Obj1Context = 10640 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext()); 10641 const auto *Obj2Context = 10642 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext()); 10643 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 10644 Cand1.Function->getPrimaryTemplate(), 10645 Cand2.Function->getPrimaryTemplate(), Loc, 10646 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 10647 : TPOC_Call, 10648 Cand1.ExplicitCallArguments, 10649 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0) 10650 : QualType{}, 10651 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0) 10652 : QualType{}, 10653 Cand1.isReversed() ^ Cand2.isReversed())) { 10654 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 10655 } 10656 } 10657 10658 // -— F1 and F2 are non-template functions with the same 10659 // parameter-type-lists, and F1 is more constrained than F2 [...], 10660 if (!Cand1IsSpecialization && !Cand2IsSpecialization && 10661 sameFunctionParameterTypeLists(S, Cand1, Cand2) && 10662 S.getMoreConstrainedFunction(Cand1.Function, Cand2.Function) == 10663 Cand1.Function) 10664 return true; 10665 10666 // -- F1 is a constructor for a class D, F2 is a constructor for a base 10667 // class B of D, and for all arguments the corresponding parameters of 10668 // F1 and F2 have the same type. 10669 // FIXME: Implement the "all parameters have the same type" check. 10670 bool Cand1IsInherited = 10671 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 10672 bool Cand2IsInherited = 10673 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 10674 if (Cand1IsInherited != Cand2IsInherited) 10675 return Cand2IsInherited; 10676 else if (Cand1IsInherited) { 10677 assert(Cand2IsInherited); 10678 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 10679 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 10680 if (Cand1Class->isDerivedFrom(Cand2Class)) 10681 return true; 10682 if (Cand2Class->isDerivedFrom(Cand1Class)) 10683 return false; 10684 // Inherited from sibling base classes: still ambiguous. 10685 } 10686 10687 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 10688 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 10689 // with reversed order of parameters and F1 is not 10690 // 10691 // We rank reversed + different operator as worse than just reversed, but 10692 // that comparison can never happen, because we only consider reversing for 10693 // the maximally-rewritten operator (== or <=>). 10694 if (Cand1.RewriteKind != Cand2.RewriteKind) 10695 return Cand1.RewriteKind < Cand2.RewriteKind; 10696 10697 // Check C++17 tie-breakers for deduction guides. 10698 { 10699 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 10700 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 10701 if (Guide1 && Guide2) { 10702 // -- F1 is generated from a deduction-guide and F2 is not 10703 if (Guide1->isImplicit() != Guide2->isImplicit()) 10704 return Guide2->isImplicit(); 10705 10706 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 10707 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy) 10708 return true; 10709 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy) 10710 return false; 10711 10712 // --F1 is generated from a non-template constructor and F2 is generated 10713 // from a constructor template 10714 const auto *Constructor1 = Guide1->getCorrespondingConstructor(); 10715 const auto *Constructor2 = Guide2->getCorrespondingConstructor(); 10716 if (Constructor1 && Constructor2) { 10717 bool isC1Templated = Constructor1->getTemplatedKind() != 10718 FunctionDecl::TemplatedKind::TK_NonTemplate; 10719 bool isC2Templated = Constructor2->getTemplatedKind() != 10720 FunctionDecl::TemplatedKind::TK_NonTemplate; 10721 if (isC1Templated != isC2Templated) 10722 return isC2Templated; 10723 } 10724 } 10725 } 10726 10727 // Check for enable_if value-based overload resolution. 10728 if (Cand1.Function && Cand2.Function) { 10729 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 10730 if (Cmp != Comparison::Equal) 10731 return Cmp == Comparison::Better; 10732 } 10733 10734 bool HasPS1 = Cand1.Function != nullptr && 10735 functionHasPassObjectSizeParams(Cand1.Function); 10736 bool HasPS2 = Cand2.Function != nullptr && 10737 functionHasPassObjectSizeParams(Cand2.Function); 10738 if (HasPS1 != HasPS2 && HasPS1) 10739 return true; 10740 10741 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 10742 if (MV == Comparison::Better) 10743 return true; 10744 if (MV == Comparison::Worse) 10745 return false; 10746 10747 // If other rules cannot determine which is better, CUDA preference is used 10748 // to determine which is better. 10749 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 10750 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10751 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) > 10752 S.CUDA().IdentifyPreference(Caller, Cand2.Function); 10753 } 10754 10755 // General member function overloading is handled above, so this only handles 10756 // constructors with address spaces. 10757 // This only handles address spaces since C++ has no other 10758 // qualifier that can be used with constructors. 10759 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 10760 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 10761 if (CD1 && CD2) { 10762 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 10763 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 10764 if (AS1 != AS2) { 10765 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1, S.getASTContext())) 10766 return true; 10767 if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2, S.getASTContext())) 10768 return false; 10769 } 10770 } 10771 10772 return false; 10773 } 10774 10775 /// Determine whether two declarations are "equivalent" for the purposes of 10776 /// name lookup and overload resolution. This applies when the same internal/no 10777 /// linkage entity is defined by two modules (probably by textually including 10778 /// the same header). In such a case, we don't consider the declarations to 10779 /// declare the same entity, but we also don't want lookups with both 10780 /// declarations visible to be ambiguous in some cases (this happens when using 10781 /// a modularized libstdc++). 10782 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 10783 const NamedDecl *B) { 10784 auto *VA = dyn_cast_or_null<ValueDecl>(A); 10785 auto *VB = dyn_cast_or_null<ValueDecl>(B); 10786 if (!VA || !VB) 10787 return false; 10788 10789 // The declarations must be declaring the same name as an internal linkage 10790 // entity in different modules. 10791 if (!VA->getDeclContext()->getRedeclContext()->Equals( 10792 VB->getDeclContext()->getRedeclContext()) || 10793 getOwningModule(VA) == getOwningModule(VB) || 10794 VA->isExternallyVisible() || VB->isExternallyVisible()) 10795 return false; 10796 10797 // Check that the declarations appear to be equivalent. 10798 // 10799 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 10800 // For constants and functions, we should check the initializer or body is 10801 // the same. For non-constant variables, we shouldn't allow it at all. 10802 if (Context.hasSameType(VA->getType(), VB->getType())) 10803 return true; 10804 10805 // Enum constants within unnamed enumerations will have different types, but 10806 // may still be similar enough to be interchangeable for our purposes. 10807 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 10808 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 10809 // Only handle anonymous enums. If the enumerations were named and 10810 // equivalent, they would have been merged to the same type. 10811 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 10812 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 10813 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 10814 !Context.hasSameType(EnumA->getIntegerType(), 10815 EnumB->getIntegerType())) 10816 return false; 10817 // Allow this only if the value is the same for both enumerators. 10818 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 10819 } 10820 } 10821 10822 // Nothing else is sufficiently similar. 10823 return false; 10824 } 10825 10826 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 10827 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 10828 assert(D && "Unknown declaration"); 10829 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 10830 10831 Module *M = getOwningModule(D); 10832 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 10833 << !M << (M ? M->getFullModuleName() : ""); 10834 10835 for (auto *E : Equiv) { 10836 Module *M = getOwningModule(E); 10837 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 10838 << !M << (M ? M->getFullModuleName() : ""); 10839 } 10840 } 10841 10842 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const { 10843 return FailureKind == ovl_fail_bad_deduction && 10844 static_cast<TemplateDeductionResult>(DeductionFailure.Result) == 10845 TemplateDeductionResult::ConstraintsNotSatisfied && 10846 static_cast<CNSInfo *>(DeductionFailure.Data) 10847 ->Satisfaction.ContainsErrors; 10848 } 10849 10850 /// Computes the best viable function (C++ 13.3.3) 10851 /// within an overload candidate set. 10852 /// 10853 /// \param Loc The location of the function name (or operator symbol) for 10854 /// which overload resolution occurs. 10855 /// 10856 /// \param Best If overload resolution was successful or found a deleted 10857 /// function, \p Best points to the candidate function found. 10858 /// 10859 /// \returns The result of overload resolution. 10860 OverloadingResult 10861 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 10862 iterator &Best) { 10863 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 10864 std::transform(begin(), end(), std::back_inserter(Candidates), 10865 [](OverloadCandidate &Cand) { return &Cand; }); 10866 10867 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 10868 // are accepted by both clang and NVCC. However, during a particular 10869 // compilation mode only one call variant is viable. We need to 10870 // exclude non-viable overload candidates from consideration based 10871 // only on their host/device attributes. Specifically, if one 10872 // candidate call is WrongSide and the other is SameSide, we ignore 10873 // the WrongSide candidate. 10874 // We only need to remove wrong-sided candidates here if 10875 // -fgpu-exclude-wrong-side-overloads is off. When 10876 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 10877 // uniformly in isBetterOverloadCandidate. 10878 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 10879 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10880 bool ContainsSameSideCandidate = 10881 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 10882 // Check viable function only. 10883 return Cand->Viable && Cand->Function && 10884 S.CUDA().IdentifyPreference(Caller, Cand->Function) == 10885 SemaCUDA::CFP_SameSide; 10886 }); 10887 if (ContainsSameSideCandidate) { 10888 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10889 // Check viable function only to avoid unnecessary data copying/moving. 10890 return Cand->Viable && Cand->Function && 10891 S.CUDA().IdentifyPreference(Caller, Cand->Function) == 10892 SemaCUDA::CFP_WrongSide; 10893 }; 10894 llvm::erase_if(Candidates, IsWrongSideCandidate); 10895 } 10896 } 10897 10898 // Find the best viable function. 10899 Best = end(); 10900 for (auto *Cand : Candidates) { 10901 Cand->Best = false; 10902 if (Cand->Viable) { 10903 if (Best == end() || 10904 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10905 Best = Cand; 10906 } else if (Cand->NotValidBecauseConstraintExprHasError()) { 10907 // This candidate has constraint that we were unable to evaluate because 10908 // it referenced an expression that contained an error. Rather than fall 10909 // back onto a potentially unintended candidate (made worse by 10910 // subsuming constraints), treat this as 'no viable candidate'. 10911 Best = end(); 10912 return OR_No_Viable_Function; 10913 } 10914 } 10915 10916 // If we didn't find any viable functions, abort. 10917 if (Best == end()) 10918 return OR_No_Viable_Function; 10919 10920 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10921 10922 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10923 PendingBest.push_back(&*Best); 10924 Best->Best = true; 10925 10926 // Make sure that this function is better than every other viable 10927 // function. If not, we have an ambiguity. 10928 while (!PendingBest.empty()) { 10929 auto *Curr = PendingBest.pop_back_val(); 10930 for (auto *Cand : Candidates) { 10931 if (Cand->Viable && !Cand->Best && 10932 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10933 PendingBest.push_back(Cand); 10934 Cand->Best = true; 10935 10936 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10937 Curr->Function)) 10938 EquivalentCands.push_back(Cand->Function); 10939 else 10940 Best = end(); 10941 } 10942 } 10943 } 10944 10945 // If we found more than one best candidate, this is ambiguous. 10946 if (Best == end()) 10947 return OR_Ambiguous; 10948 10949 // Best is the best viable function. 10950 if (Best->Function && Best->Function->isDeleted()) 10951 return OR_Deleted; 10952 10953 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function); 10954 Kind == CSK_AddressOfOverloadSet && M && 10955 M->isImplicitObjectMemberFunction()) { 10956 return OR_No_Viable_Function; 10957 } 10958 10959 if (!EquivalentCands.empty()) 10960 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10961 EquivalentCands); 10962 10963 return OR_Success; 10964 } 10965 10966 namespace { 10967 10968 enum OverloadCandidateKind { 10969 oc_function, 10970 oc_method, 10971 oc_reversed_binary_operator, 10972 oc_constructor, 10973 oc_implicit_default_constructor, 10974 oc_implicit_copy_constructor, 10975 oc_implicit_move_constructor, 10976 oc_implicit_copy_assignment, 10977 oc_implicit_move_assignment, 10978 oc_implicit_equality_comparison, 10979 oc_inherited_constructor 10980 }; 10981 10982 enum OverloadCandidateSelect { 10983 ocs_non_template, 10984 ocs_template, 10985 ocs_described_template, 10986 }; 10987 10988 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10989 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found, 10990 const FunctionDecl *Fn, 10991 OverloadCandidateRewriteKind CRK, 10992 std::string &Description) { 10993 10994 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10995 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10996 isTemplate = true; 10997 Description = S.getTemplateArgumentBindingsText( 10998 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10999 } 11000 11001 OverloadCandidateSelect Select = [&]() { 11002 if (!Description.empty()) 11003 return ocs_described_template; 11004 return isTemplate ? ocs_template : ocs_non_template; 11005 }(); 11006 11007 OverloadCandidateKind Kind = [&]() { 11008 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 11009 return oc_implicit_equality_comparison; 11010 11011 if (CRK & CRK_Reversed) 11012 return oc_reversed_binary_operator; 11013 11014 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 11015 if (!Ctor->isImplicit()) { 11016 if (isa<ConstructorUsingShadowDecl>(Found)) 11017 return oc_inherited_constructor; 11018 else 11019 return oc_constructor; 11020 } 11021 11022 if (Ctor->isDefaultConstructor()) 11023 return oc_implicit_default_constructor; 11024 11025 if (Ctor->isMoveConstructor()) 11026 return oc_implicit_move_constructor; 11027 11028 assert(Ctor->isCopyConstructor() && 11029 "unexpected sort of implicit constructor"); 11030 return oc_implicit_copy_constructor; 11031 } 11032 11033 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 11034 // This actually gets spelled 'candidate function' for now, but 11035 // it doesn't hurt to split it out. 11036 if (!Meth->isImplicit()) 11037 return oc_method; 11038 11039 if (Meth->isMoveAssignmentOperator()) 11040 return oc_implicit_move_assignment; 11041 11042 if (Meth->isCopyAssignmentOperator()) 11043 return oc_implicit_copy_assignment; 11044 11045 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 11046 return oc_method; 11047 } 11048 11049 return oc_function; 11050 }(); 11051 11052 return std::make_pair(Kind, Select); 11053 } 11054 11055 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) { 11056 // FIXME: It'd be nice to only emit a note once per using-decl per overload 11057 // set. 11058 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 11059 S.Diag(FoundDecl->getLocation(), 11060 diag::note_ovl_candidate_inherited_constructor) 11061 << Shadow->getNominatedBaseClass(); 11062 } 11063 11064 } // end anonymous namespace 11065 11066 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 11067 const FunctionDecl *FD) { 11068 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 11069 bool AlwaysTrue; 11070 if (EnableIf->getCond()->isValueDependent() || 11071 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 11072 return false; 11073 if (!AlwaysTrue) 11074 return false; 11075 } 11076 return true; 11077 } 11078 11079 /// Returns true if we can take the address of the function. 11080 /// 11081 /// \param Complain - If true, we'll emit a diagnostic 11082 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 11083 /// we in overload resolution? 11084 /// \param Loc - The location of the statement we're complaining about. Ignored 11085 /// if we're not complaining, or if we're in overload resolution. 11086 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 11087 bool Complain, 11088 bool InOverloadResolution, 11089 SourceLocation Loc) { 11090 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 11091 if (Complain) { 11092 if (InOverloadResolution) 11093 S.Diag(FD->getBeginLoc(), 11094 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 11095 else 11096 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 11097 } 11098 return false; 11099 } 11100 11101 if (FD->getTrailingRequiresClause()) { 11102 ConstraintSatisfaction Satisfaction; 11103 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 11104 return false; 11105 if (!Satisfaction.IsSatisfied) { 11106 if (Complain) { 11107 if (InOverloadResolution) { 11108 SmallString<128> TemplateArgString; 11109 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { 11110 TemplateArgString += " "; 11111 TemplateArgString += S.getTemplateArgumentBindingsText( 11112 FunTmpl->getTemplateParameters(), 11113 *FD->getTemplateSpecializationArgs()); 11114 } 11115 11116 S.Diag(FD->getBeginLoc(), 11117 diag::note_ovl_candidate_unsatisfied_constraints) 11118 << TemplateArgString; 11119 } else 11120 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 11121 << FD; 11122 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11123 } 11124 return false; 11125 } 11126 } 11127 11128 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 11129 return P->hasAttr<PassObjectSizeAttr>(); 11130 }); 11131 if (I == FD->param_end()) 11132 return true; 11133 11134 if (Complain) { 11135 // Add one to ParamNo because it's user-facing 11136 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 11137 if (InOverloadResolution) 11138 S.Diag(FD->getLocation(), 11139 diag::note_ovl_candidate_has_pass_object_size_params) 11140 << ParamNo; 11141 else 11142 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 11143 << FD << ParamNo; 11144 } 11145 return false; 11146 } 11147 11148 static bool checkAddressOfCandidateIsAvailable(Sema &S, 11149 const FunctionDecl *FD) { 11150 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 11151 /*InOverloadResolution=*/true, 11152 /*Loc=*/SourceLocation()); 11153 } 11154 11155 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 11156 bool Complain, 11157 SourceLocation Loc) { 11158 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 11159 /*InOverloadResolution=*/false, 11160 Loc); 11161 } 11162 11163 // Don't print candidates other than the one that matches the calling 11164 // convention of the call operator, since that is guaranteed to exist. 11165 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) { 11166 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 11167 11168 if (!ConvD) 11169 return false; 11170 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 11171 if (!RD->isLambda()) 11172 return false; 11173 11174 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 11175 CallingConv CallOpCC = 11176 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 11177 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 11178 CallingConv ConvToCC = 11179 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 11180 11181 return ConvToCC != CallOpCC; 11182 } 11183 11184 // Notes the location of an overload candidate. 11185 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, 11186 OverloadCandidateRewriteKind RewriteKind, 11187 QualType DestType, bool TakingAddress) { 11188 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 11189 return; 11190 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 11191 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 11192 return; 11193 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() && 11194 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion()) 11195 return; 11196 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11197 return; 11198 11199 std::string FnDesc; 11200 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 11201 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 11202 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 11203 << (unsigned)KSPair.first << (unsigned)KSPair.second 11204 << Fn << FnDesc; 11205 11206 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 11207 Diag(Fn->getLocation(), PD); 11208 MaybeEmitInheritedConstructorNote(*this, Found); 11209 } 11210 11211 static void 11212 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 11213 // Perhaps the ambiguity was caused by two atomic constraints that are 11214 // 'identical' but not equivalent: 11215 // 11216 // void foo() requires (sizeof(T) > 4) { } // #1 11217 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 11218 // 11219 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 11220 // #2 to subsume #1, but these constraint are not considered equivalent 11221 // according to the subsumption rules because they are not the same 11222 // source-level construct. This behavior is quite confusing and we should try 11223 // to help the user figure out what happened. 11224 11225 SmallVector<const Expr *, 3> FirstAC, SecondAC; 11226 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 11227 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11228 if (!I->Function) 11229 continue; 11230 SmallVector<const Expr *, 3> AC; 11231 if (auto *Template = I->Function->getPrimaryTemplate()) 11232 Template->getAssociatedConstraints(AC); 11233 else 11234 I->Function->getAssociatedConstraints(AC); 11235 if (AC.empty()) 11236 continue; 11237 if (FirstCand == nullptr) { 11238 FirstCand = I->Function; 11239 FirstAC = AC; 11240 } else if (SecondCand == nullptr) { 11241 SecondCand = I->Function; 11242 SecondAC = AC; 11243 } else { 11244 // We have more than one pair of constrained functions - this check is 11245 // expensive and we'd rather not try to diagnose it. 11246 return; 11247 } 11248 } 11249 if (!SecondCand) 11250 return; 11251 // The diagnostic can only happen if there are associated constraints on 11252 // both sides (there needs to be some identical atomic constraint). 11253 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 11254 SecondCand, SecondAC)) 11255 // Just show the user one diagnostic, they'll probably figure it out 11256 // from here. 11257 return; 11258 } 11259 11260 // Notes the location of all overload candidates designated through 11261 // OverloadedExpr 11262 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 11263 bool TakingAddress) { 11264 assert(OverloadedExpr->getType() == Context.OverloadTy); 11265 11266 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 11267 OverloadExpr *OvlExpr = Ovl.Expression; 11268 11269 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11270 IEnd = OvlExpr->decls_end(); 11271 I != IEnd; ++I) { 11272 if (FunctionTemplateDecl *FunTmpl = 11273 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 11274 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 11275 TakingAddress); 11276 } else if (FunctionDecl *Fun 11277 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 11278 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 11279 } 11280 } 11281 } 11282 11283 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 11284 /// "lead" diagnostic; it will be given two arguments, the source and 11285 /// target types of the conversion. 11286 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 11287 Sema &S, 11288 SourceLocation CaretLoc, 11289 const PartialDiagnostic &PDiag) const { 11290 S.Diag(CaretLoc, PDiag) 11291 << Ambiguous.getFromType() << Ambiguous.getToType(); 11292 unsigned CandsShown = 0; 11293 AmbiguousConversionSequence::const_iterator I, E; 11294 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 11295 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 11296 break; 11297 ++CandsShown; 11298 S.NoteOverloadCandidate(I->first, I->second); 11299 } 11300 S.Diags.overloadCandidatesShown(CandsShown); 11301 if (I != E) 11302 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 11303 } 11304 11305 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 11306 unsigned I, bool TakingCandidateAddress) { 11307 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 11308 assert(Conv.isBad()); 11309 assert(Cand->Function && "for now, candidate must be a function"); 11310 FunctionDecl *Fn = Cand->Function; 11311 11312 // There's a conversion slot for the object argument if this is a 11313 // non-constructor method. Note that 'I' corresponds the 11314 // conversion-slot index. 11315 bool isObjectArgument = false; 11316 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 11317 if (I == 0) 11318 isObjectArgument = true; 11319 else if (!Fn->hasCXXExplicitFunctionObjectParameter()) 11320 I--; 11321 } 11322 11323 std::string FnDesc; 11324 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11325 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 11326 FnDesc); 11327 11328 Expr *FromExpr = Conv.Bad.FromExpr; 11329 QualType FromTy = Conv.Bad.getFromType(); 11330 QualType ToTy = Conv.Bad.getToType(); 11331 SourceRange ToParamRange; 11332 11333 // FIXME: In presence of parameter packs we can't determine parameter range 11334 // reliably, as we don't have access to instantiation. 11335 bool HasParamPack = 11336 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) { 11337 return Parm->isParameterPack(); 11338 }); 11339 if (!isObjectArgument && !HasParamPack) 11340 ToParamRange = Fn->getParamDecl(I)->getSourceRange(); 11341 11342 if (FromTy == S.Context.OverloadTy) { 11343 assert(FromExpr && "overload set argument came from implicit argument?"); 11344 Expr *E = FromExpr->IgnoreParens(); 11345 if (isa<UnaryOperator>(E)) 11346 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11347 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 11348 11349 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 11350 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11351 << ToParamRange << ToTy << Name << I + 1; 11352 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11353 return; 11354 } 11355 11356 // Do some hand-waving analysis to see if the non-viability is due 11357 // to a qualifier mismatch. 11358 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 11359 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 11360 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 11361 CToTy = RT->getPointeeType(); 11362 else { 11363 // TODO: detect and diagnose the full richness of const mismatches. 11364 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 11365 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 11366 CFromTy = FromPT->getPointeeType(); 11367 CToTy = ToPT->getPointeeType(); 11368 } 11369 } 11370 11371 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 11372 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) { 11373 Qualifiers FromQs = CFromTy.getQualifiers(); 11374 Qualifiers ToQs = CToTy.getQualifiers(); 11375 11376 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 11377 if (isObjectArgument) 11378 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 11379 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11380 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 11381 else 11382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 11383 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11384 << FnDesc << ToParamRange << FromQs.getAddressSpace() 11385 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1; 11386 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11387 return; 11388 } 11389 11390 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 11391 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 11392 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11393 << ToParamRange << FromTy << FromQs.getObjCLifetime() 11394 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1; 11395 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11396 return; 11397 } 11398 11399 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 11400 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 11401 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11402 << ToParamRange << FromTy << FromQs.getObjCGCAttr() 11403 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1; 11404 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11405 return; 11406 } 11407 11408 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 11409 assert(CVR && "expected qualifiers mismatch"); 11410 11411 if (isObjectArgument) { 11412 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 11413 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11414 << FromTy << (CVR - 1); 11415 } else { 11416 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 11417 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11418 << ToParamRange << FromTy << (CVR - 1) << I + 1; 11419 } 11420 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11421 return; 11422 } 11423 11424 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 11425 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 11426 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 11427 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11428 << (unsigned)isObjectArgument << I + 1 11429 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 11430 << ToParamRange; 11431 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11432 return; 11433 } 11434 11435 // Special diagnostic for failure to convert an initializer list, since 11436 // telling the user that it has type void is not useful. 11437 if (FromExpr && isa<InitListExpr>(FromExpr)) { 11438 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 11439 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11440 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11441 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 11442 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers 11443 ? 2 11444 : 0); 11445 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11446 return; 11447 } 11448 11449 // Diagnose references or pointers to incomplete types differently, 11450 // since it's far from impossible that the incompleteness triggered 11451 // the failure. 11452 QualType TempFromTy = FromTy.getNonReferenceType(); 11453 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 11454 TempFromTy = PTy->getPointeeType(); 11455 if (TempFromTy->isIncompleteType()) { 11456 // Emit the generic diagnostic and, optionally, add the hints to it. 11457 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 11458 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11459 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11460 << (unsigned)(Cand->Fix.Kind); 11461 11462 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11463 return; 11464 } 11465 11466 // Diagnose base -> derived pointer conversions. 11467 unsigned BaseToDerivedConversion = 0; 11468 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 11469 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 11470 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 11471 FromPtrTy->getPointeeType(), S.getASTContext()) && 11472 !FromPtrTy->getPointeeType()->isIncompleteType() && 11473 !ToPtrTy->getPointeeType()->isIncompleteType() && 11474 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 11475 FromPtrTy->getPointeeType())) 11476 BaseToDerivedConversion = 1; 11477 } 11478 } else if (const ObjCObjectPointerType *FromPtrTy 11479 = FromTy->getAs<ObjCObjectPointerType>()) { 11480 if (const ObjCObjectPointerType *ToPtrTy 11481 = ToTy->getAs<ObjCObjectPointerType>()) 11482 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 11483 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 11484 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 11485 FromPtrTy->getPointeeType(), S.getASTContext()) && 11486 FromIface->isSuperClassOf(ToIface)) 11487 BaseToDerivedConversion = 2; 11488 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 11489 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy, 11490 S.getASTContext()) && 11491 !FromTy->isIncompleteType() && 11492 !ToRefTy->getPointeeType()->isIncompleteType() && 11493 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 11494 BaseToDerivedConversion = 3; 11495 } 11496 } 11497 11498 if (BaseToDerivedConversion) { 11499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 11500 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11501 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy 11502 << I + 1; 11503 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11504 return; 11505 } 11506 11507 if (isa<ObjCObjectPointerType>(CFromTy) && 11508 isa<PointerType>(CToTy)) { 11509 Qualifiers FromQs = CFromTy.getQualifiers(); 11510 Qualifiers ToQs = CToTy.getQualifiers(); 11511 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 11512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 11513 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11514 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument 11515 << I + 1; 11516 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11517 return; 11518 } 11519 } 11520 11521 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn)) 11522 return; 11523 11524 // Emit the generic diagnostic and, optionally, add the hints to it. 11525 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 11526 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11527 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11528 << (unsigned)(Cand->Fix.Kind); 11529 11530 // Check that location of Fn is not in system header. 11531 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) { 11532 // If we can fix the conversion, suggest the FixIts. 11533 for (const FixItHint &HI : Cand->Fix.Hints) 11534 FDiag << HI; 11535 } 11536 11537 S.Diag(Fn->getLocation(), FDiag); 11538 11539 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11540 } 11541 11542 /// Additional arity mismatch diagnosis specific to a function overload 11543 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 11544 /// over a candidate in any candidate set. 11545 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 11546 unsigned NumArgs, bool IsAddressOf = false) { 11547 assert(Cand->Function && "Candidate is required to be a function."); 11548 FunctionDecl *Fn = Cand->Function; 11549 unsigned MinParams = Fn->getMinRequiredExplicitArguments() + 11550 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0); 11551 11552 // With invalid overloaded operators, it's possible that we think we 11553 // have an arity mismatch when in fact it looks like we have the 11554 // right number of arguments, because only overloaded operators have 11555 // the weird behavior of overloading member and non-member functions. 11556 // Just don't report anything. 11557 if (Fn->isInvalidDecl() && 11558 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 11559 return true; 11560 11561 if (NumArgs < MinParams) { 11562 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 11563 (Cand->FailureKind == ovl_fail_bad_deduction && 11564 Cand->DeductionFailure.getResult() == 11565 TemplateDeductionResult::TooFewArguments)); 11566 } else { 11567 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 11568 (Cand->FailureKind == ovl_fail_bad_deduction && 11569 Cand->DeductionFailure.getResult() == 11570 TemplateDeductionResult::TooManyArguments)); 11571 } 11572 11573 return false; 11574 } 11575 11576 /// General arity mismatch diagnosis over a candidate in a candidate set. 11577 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 11578 unsigned NumFormalArgs, 11579 bool IsAddressOf = false) { 11580 assert(isa<FunctionDecl>(D) && 11581 "The templated declaration should at least be a function" 11582 " when diagnosing bad template argument deduction due to too many" 11583 " or too few arguments"); 11584 11585 FunctionDecl *Fn = cast<FunctionDecl>(D); 11586 11587 // TODO: treat calls to a missing default constructor as a special case 11588 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 11589 unsigned MinParams = Fn->getMinRequiredExplicitArguments() + 11590 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0); 11591 11592 // at least / at most / exactly 11593 bool HasExplicitObjectParam = 11594 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter(); 11595 11596 unsigned ParamCount = 11597 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0); 11598 unsigned mode, modeCount; 11599 11600 if (NumFormalArgs < MinParams) { 11601 if (MinParams != ParamCount || FnTy->isVariadic() || 11602 FnTy->isTemplateVariadic()) 11603 mode = 0; // "at least" 11604 else 11605 mode = 2; // "exactly" 11606 modeCount = MinParams; 11607 } else { 11608 if (MinParams != ParamCount) 11609 mode = 1; // "at most" 11610 else 11611 mode = 2; // "exactly" 11612 modeCount = ParamCount; 11613 } 11614 11615 std::string Description; 11616 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11617 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 11618 11619 if (modeCount == 1 && !IsAddressOf && 11620 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName()) 11621 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 11622 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11623 << Description << mode 11624 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs 11625 << HasExplicitObjectParam << Fn->getParametersSourceRange(); 11626 else 11627 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 11628 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11629 << Description << mode << modeCount << NumFormalArgs 11630 << HasExplicitObjectParam << Fn->getParametersSourceRange(); 11631 11632 MaybeEmitInheritedConstructorNote(S, Found); 11633 } 11634 11635 /// Arity mismatch diagnosis specific to a function overload candidate. 11636 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 11637 unsigned NumFormalArgs) { 11638 assert(Cand->Function && "Candidate must be a function"); 11639 FunctionDecl *Fn = Cand->Function; 11640 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload)) 11641 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs, 11642 Cand->TookAddressOfOverload); 11643 } 11644 11645 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 11646 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 11647 return TD; 11648 llvm_unreachable("Unsupported: Getting the described template declaration" 11649 " for bad deduction diagnosis"); 11650 } 11651 11652 /// Diagnose a failed template-argument deduction. 11653 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 11654 DeductionFailureInfo &DeductionFailure, 11655 unsigned NumArgs, 11656 bool TakingCandidateAddress) { 11657 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 11658 NamedDecl *ParamD; 11659 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 11660 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 11661 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 11662 switch (DeductionFailure.getResult()) { 11663 case TemplateDeductionResult::Success: 11664 llvm_unreachable( 11665 "TemplateDeductionResult::Success while diagnosing bad deduction"); 11666 case TemplateDeductionResult::NonDependentConversionFailure: 11667 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure " 11668 "while diagnosing bad deduction"); 11669 case TemplateDeductionResult::Invalid: 11670 case TemplateDeductionResult::AlreadyDiagnosed: 11671 return; 11672 11673 case TemplateDeductionResult::Incomplete: { 11674 assert(ParamD && "no parameter found for incomplete deduction result"); 11675 S.Diag(Templated->getLocation(), 11676 diag::note_ovl_candidate_incomplete_deduction) 11677 << ParamD->getDeclName(); 11678 MaybeEmitInheritedConstructorNote(S, Found); 11679 return; 11680 } 11681 11682 case TemplateDeductionResult::IncompletePack: { 11683 assert(ParamD && "no parameter found for incomplete deduction result"); 11684 S.Diag(Templated->getLocation(), 11685 diag::note_ovl_candidate_incomplete_deduction_pack) 11686 << ParamD->getDeclName() 11687 << (DeductionFailure.getFirstArg()->pack_size() + 1) 11688 << *DeductionFailure.getFirstArg(); 11689 MaybeEmitInheritedConstructorNote(S, Found); 11690 return; 11691 } 11692 11693 case TemplateDeductionResult::Underqualified: { 11694 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 11695 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 11696 11697 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 11698 11699 // Param will have been canonicalized, but it should just be a 11700 // qualified version of ParamD, so move the qualifiers to that. 11701 QualifierCollector Qs; 11702 Qs.strip(Param); 11703 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 11704 assert(S.Context.hasSameType(Param, NonCanonParam)); 11705 11706 // Arg has also been canonicalized, but there's nothing we can do 11707 // about that. It also doesn't matter as much, because it won't 11708 // have any template parameters in it (because deduction isn't 11709 // done on dependent types). 11710 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 11711 11712 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 11713 << ParamD->getDeclName() << Arg << NonCanonParam; 11714 MaybeEmitInheritedConstructorNote(S, Found); 11715 return; 11716 } 11717 11718 case TemplateDeductionResult::Inconsistent: { 11719 assert(ParamD && "no parameter found for inconsistent deduction result"); 11720 int which = 0; 11721 if (isa<TemplateTypeParmDecl>(ParamD)) 11722 which = 0; 11723 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 11724 // Deduction might have failed because we deduced arguments of two 11725 // different types for a non-type template parameter. 11726 // FIXME: Use a different TDK value for this. 11727 QualType T1 = 11728 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 11729 QualType T2 = 11730 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 11731 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 11732 S.Diag(Templated->getLocation(), 11733 diag::note_ovl_candidate_inconsistent_deduction_types) 11734 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 11735 << *DeductionFailure.getSecondArg() << T2; 11736 MaybeEmitInheritedConstructorNote(S, Found); 11737 return; 11738 } 11739 11740 which = 1; 11741 } else { 11742 which = 2; 11743 } 11744 11745 // Tweak the diagnostic if the problem is that we deduced packs of 11746 // different arities. We'll print the actual packs anyway in case that 11747 // includes additional useful information. 11748 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 11749 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 11750 DeductionFailure.getFirstArg()->pack_size() != 11751 DeductionFailure.getSecondArg()->pack_size()) { 11752 which = 3; 11753 } 11754 11755 S.Diag(Templated->getLocation(), 11756 diag::note_ovl_candidate_inconsistent_deduction) 11757 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 11758 << *DeductionFailure.getSecondArg(); 11759 MaybeEmitInheritedConstructorNote(S, Found); 11760 return; 11761 } 11762 11763 case TemplateDeductionResult::InvalidExplicitArguments: 11764 assert(ParamD && "no parameter found for invalid explicit arguments"); 11765 if (ParamD->getDeclName()) 11766 S.Diag(Templated->getLocation(), 11767 diag::note_ovl_candidate_explicit_arg_mismatch_named) 11768 << ParamD->getDeclName(); 11769 else { 11770 int index = 0; 11771 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 11772 index = TTP->getIndex(); 11773 else if (NonTypeTemplateParmDecl *NTTP 11774 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 11775 index = NTTP->getIndex(); 11776 else 11777 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 11778 S.Diag(Templated->getLocation(), 11779 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 11780 << (index + 1); 11781 } 11782 MaybeEmitInheritedConstructorNote(S, Found); 11783 return; 11784 11785 case TemplateDeductionResult::ConstraintsNotSatisfied: { 11786 // Format the template argument list into the argument string. 11787 SmallString<128> TemplateArgString; 11788 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 11789 TemplateArgString = " "; 11790 TemplateArgString += S.getTemplateArgumentBindingsText( 11791 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11792 if (TemplateArgString.size() == 1) 11793 TemplateArgString.clear(); 11794 S.Diag(Templated->getLocation(), 11795 diag::note_ovl_candidate_unsatisfied_constraints) 11796 << TemplateArgString; 11797 11798 S.DiagnoseUnsatisfiedConstraint( 11799 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 11800 return; 11801 } 11802 case TemplateDeductionResult::TooManyArguments: 11803 case TemplateDeductionResult::TooFewArguments: 11804 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 11805 return; 11806 11807 case TemplateDeductionResult::InstantiationDepth: 11808 S.Diag(Templated->getLocation(), 11809 diag::note_ovl_candidate_instantiation_depth); 11810 MaybeEmitInheritedConstructorNote(S, Found); 11811 return; 11812 11813 case TemplateDeductionResult::SubstitutionFailure: { 11814 // Format the template argument list into the argument string. 11815 SmallString<128> TemplateArgString; 11816 if (TemplateArgumentList *Args = 11817 DeductionFailure.getTemplateArgumentList()) { 11818 TemplateArgString = " "; 11819 TemplateArgString += S.getTemplateArgumentBindingsText( 11820 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11821 if (TemplateArgString.size() == 1) 11822 TemplateArgString.clear(); 11823 } 11824 11825 // If this candidate was disabled by enable_if, say so. 11826 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 11827 if (PDiag && PDiag->second.getDiagID() == 11828 diag::err_typename_nested_not_found_enable_if) { 11829 // FIXME: Use the source range of the condition, and the fully-qualified 11830 // name of the enable_if template. These are both present in PDiag. 11831 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 11832 << "'enable_if'" << TemplateArgString; 11833 return; 11834 } 11835 11836 // We found a specific requirement that disabled the enable_if. 11837 if (PDiag && PDiag->second.getDiagID() == 11838 diag::err_typename_nested_not_found_requirement) { 11839 S.Diag(Templated->getLocation(), 11840 diag::note_ovl_candidate_disabled_by_requirement) 11841 << PDiag->second.getStringArg(0) << TemplateArgString; 11842 return; 11843 } 11844 11845 // Format the SFINAE diagnostic into the argument string. 11846 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 11847 // formatted message in another diagnostic. 11848 SmallString<128> SFINAEArgString; 11849 SourceRange R; 11850 if (PDiag) { 11851 SFINAEArgString = ": "; 11852 R = SourceRange(PDiag->first, PDiag->first); 11853 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 11854 } 11855 11856 S.Diag(Templated->getLocation(), 11857 diag::note_ovl_candidate_substitution_failure) 11858 << TemplateArgString << SFINAEArgString << R; 11859 MaybeEmitInheritedConstructorNote(S, Found); 11860 return; 11861 } 11862 11863 case TemplateDeductionResult::DeducedMismatch: 11864 case TemplateDeductionResult::DeducedMismatchNested: { 11865 // Format the template argument list into the argument string. 11866 SmallString<128> TemplateArgString; 11867 if (TemplateArgumentList *Args = 11868 DeductionFailure.getTemplateArgumentList()) { 11869 TemplateArgString = " "; 11870 TemplateArgString += S.getTemplateArgumentBindingsText( 11871 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11872 if (TemplateArgString.size() == 1) 11873 TemplateArgString.clear(); 11874 } 11875 11876 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 11877 << (*DeductionFailure.getCallArgIndex() + 1) 11878 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 11879 << TemplateArgString 11880 << (DeductionFailure.getResult() == 11881 TemplateDeductionResult::DeducedMismatchNested); 11882 break; 11883 } 11884 11885 case TemplateDeductionResult::NonDeducedMismatch: { 11886 // FIXME: Provide a source location to indicate what we couldn't match. 11887 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 11888 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 11889 if (FirstTA.getKind() == TemplateArgument::Template && 11890 SecondTA.getKind() == TemplateArgument::Template) { 11891 TemplateName FirstTN = FirstTA.getAsTemplate(); 11892 TemplateName SecondTN = SecondTA.getAsTemplate(); 11893 if (FirstTN.getKind() == TemplateName::Template && 11894 SecondTN.getKind() == TemplateName::Template) { 11895 if (FirstTN.getAsTemplateDecl()->getName() == 11896 SecondTN.getAsTemplateDecl()->getName()) { 11897 // FIXME: This fixes a bad diagnostic where both templates are named 11898 // the same. This particular case is a bit difficult since: 11899 // 1) It is passed as a string to the diagnostic printer. 11900 // 2) The diagnostic printer only attempts to find a better 11901 // name for types, not decls. 11902 // Ideally, this should folded into the diagnostic printer. 11903 S.Diag(Templated->getLocation(), 11904 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 11905 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 11906 return; 11907 } 11908 } 11909 } 11910 11911 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 11912 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 11913 return; 11914 11915 // FIXME: For generic lambda parameters, check if the function is a lambda 11916 // call operator, and if so, emit a prettier and more informative 11917 // diagnostic that mentions 'auto' and lambda in addition to 11918 // (or instead of?) the canonical template type parameters. 11919 S.Diag(Templated->getLocation(), 11920 diag::note_ovl_candidate_non_deduced_mismatch) 11921 << FirstTA << SecondTA; 11922 return; 11923 } 11924 // TODO: diagnose these individually, then kill off 11925 // note_ovl_candidate_bad_deduction, which is uselessly vague. 11926 case TemplateDeductionResult::MiscellaneousDeductionFailure: 11927 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 11928 MaybeEmitInheritedConstructorNote(S, Found); 11929 return; 11930 case TemplateDeductionResult::CUDATargetMismatch: 11931 S.Diag(Templated->getLocation(), 11932 diag::note_cuda_ovl_candidate_target_mismatch); 11933 return; 11934 } 11935 } 11936 11937 /// Diagnose a failed template-argument deduction, for function calls. 11938 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 11939 unsigned NumArgs, 11940 bool TakingCandidateAddress) { 11941 assert(Cand->Function && "Candidate must be a function"); 11942 FunctionDecl *Fn = Cand->Function; 11943 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult(); 11944 if (TDK == TemplateDeductionResult::TooFewArguments || 11945 TDK == TemplateDeductionResult::TooManyArguments) { 11946 if (CheckArityMismatch(S, Cand, NumArgs)) 11947 return; 11948 } 11949 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern 11950 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11951 } 11952 11953 /// CUDA: diagnose an invalid call across targets. 11954 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11955 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 11956 assert(Cand->Function && "Candidate must be a Function."); 11957 FunctionDecl *Callee = Cand->Function; 11958 11959 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller), 11960 CalleeTarget = S.CUDA().IdentifyTarget(Callee); 11961 11962 std::string FnDesc; 11963 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11964 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11965 Cand->getRewriteKind(), FnDesc); 11966 11967 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11968 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11969 << FnDesc /* Ignored */ 11970 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget); 11971 11972 // This could be an implicit constructor for which we could not infer the 11973 // target due to a collsion. Diagnose that case. 11974 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11975 if (Meth != nullptr && Meth->isImplicit()) { 11976 CXXRecordDecl *ParentClass = Meth->getParent(); 11977 CXXSpecialMemberKind CSM; 11978 11979 switch (FnKindPair.first) { 11980 default: 11981 return; 11982 case oc_implicit_default_constructor: 11983 CSM = CXXSpecialMemberKind::DefaultConstructor; 11984 break; 11985 case oc_implicit_copy_constructor: 11986 CSM = CXXSpecialMemberKind::CopyConstructor; 11987 break; 11988 case oc_implicit_move_constructor: 11989 CSM = CXXSpecialMemberKind::MoveConstructor; 11990 break; 11991 case oc_implicit_copy_assignment: 11992 CSM = CXXSpecialMemberKind::CopyAssignment; 11993 break; 11994 case oc_implicit_move_assignment: 11995 CSM = CXXSpecialMemberKind::MoveAssignment; 11996 break; 11997 }; 11998 11999 bool ConstRHS = false; 12000 if (Meth->getNumParams()) { 12001 if (const ReferenceType *RT = 12002 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 12003 ConstRHS = RT->getPointeeType().isConstQualified(); 12004 } 12005 } 12006 12007 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth, 12008 /* ConstRHS */ ConstRHS, 12009 /* Diagnose */ true); 12010 } 12011 } 12012 12013 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 12014 assert(Cand->Function && "Candidate must be a function"); 12015 FunctionDecl *Callee = Cand->Function; 12016 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 12017 12018 S.Diag(Callee->getLocation(), 12019 diag::note_ovl_candidate_disabled_by_function_cond_attr) 12020 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12021 } 12022 12023 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 12024 assert(Cand->Function && "Candidate must be a function"); 12025 FunctionDecl *Fn = Cand->Function; 12026 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Fn); 12027 assert(ES.isExplicit() && "not an explicit candidate"); 12028 12029 unsigned Kind; 12030 switch (Fn->getDeclKind()) { 12031 case Decl::Kind::CXXConstructor: 12032 Kind = 0; 12033 break; 12034 case Decl::Kind::CXXConversion: 12035 Kind = 1; 12036 break; 12037 case Decl::Kind::CXXDeductionGuide: 12038 Kind = Fn->isImplicit() ? 0 : 2; 12039 break; 12040 default: 12041 llvm_unreachable("invalid Decl"); 12042 } 12043 12044 // Note the location of the first (in-class) declaration; a redeclaration 12045 // (particularly an out-of-class definition) will typically lack the 12046 // 'explicit' specifier. 12047 // FIXME: This is probably a good thing to do for all 'candidate' notes. 12048 FunctionDecl *First = Fn->getFirstDecl(); 12049 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 12050 First = Pattern->getFirstDecl(); 12051 12052 S.Diag(First->getLocation(), 12053 diag::note_ovl_candidate_explicit) 12054 << Kind << (ES.getExpr() ? 1 : 0) 12055 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 12056 } 12057 12058 static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) { 12059 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn); 12060 if (!DG) 12061 return; 12062 TemplateDecl *OriginTemplate = 12063 DG->getDeclName().getCXXDeductionGuideTemplate(); 12064 // We want to always print synthesized deduction guides for type aliases. 12065 // They would retain the explicit bit of the corresponding constructor. 12066 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias()))) 12067 return; 12068 std::string FunctionProto; 12069 llvm::raw_string_ostream OS(FunctionProto); 12070 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate(); 12071 if (!Template) { 12072 // This also could be an instantiation. Find out the primary template. 12073 FunctionDecl *Pattern = 12074 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false); 12075 if (!Pattern) { 12076 // The implicit deduction guide is built on an explicit non-template 12077 // deduction guide. Currently, this might be the case only for type 12078 // aliases. 12079 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686 12080 // gets merged. 12081 assert(OriginTemplate->isTypeAlias() && 12082 "Non-template implicit deduction guides are only possible for " 12083 "type aliases"); 12084 DG->print(OS); 12085 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide) 12086 << FunctionProto; 12087 return; 12088 } 12089 Template = Pattern->getDescribedFunctionTemplate(); 12090 assert(Template && "Cannot find the associated function template of " 12091 "CXXDeductionGuideDecl?"); 12092 } 12093 Template->print(OS); 12094 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide) 12095 << FunctionProto; 12096 } 12097 12098 /// Generates a 'note' diagnostic for an overload candidate. We've 12099 /// already generated a primary error at the call site. 12100 /// 12101 /// It really does need to be a single diagnostic with its caret 12102 /// pointed at the candidate declaration. Yes, this creates some 12103 /// major challenges of technical writing. Yes, this makes pointing 12104 /// out problems with specific arguments quite awkward. It's still 12105 /// better than generating twenty screens of text for every failed 12106 /// overload. 12107 /// 12108 /// It would be great to be able to express per-candidate problems 12109 /// more richly for those diagnostic clients that cared, but we'd 12110 /// still have to be just as careful with the default diagnostics. 12111 /// \param CtorDestAS Addr space of object being constructed (for ctor 12112 /// candidates only). 12113 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 12114 unsigned NumArgs, 12115 bool TakingCandidateAddress, 12116 LangAS CtorDestAS = LangAS::Default) { 12117 assert(Cand->Function && "Candidate must be a function"); 12118 FunctionDecl *Fn = Cand->Function; 12119 if (shouldSkipNotingLambdaConversionDecl(Fn)) 12120 return; 12121 12122 // There is no physical candidate declaration to point to for OpenCL builtins. 12123 // Except for failed conversions, the notes are identical for each candidate, 12124 // so do not generate such notes. 12125 if (S.getLangOpts().OpenCL && Fn->isImplicit() && 12126 Cand->FailureKind != ovl_fail_bad_conversion) 12127 return; 12128 12129 // Skip implicit member functions when trying to resolve 12130 // the address of a an overload set for a function pointer. 12131 if (Cand->TookAddressOfOverload && 12132 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic()) 12133 return; 12134 12135 // Note deleted candidates, but only if they're viable. 12136 if (Cand->Viable) { 12137 if (Fn->isDeleted()) { 12138 std::string FnDesc; 12139 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 12140 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 12141 Cand->getRewriteKind(), FnDesc); 12142 12143 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 12144 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 12145 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 12146 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 12147 return; 12148 } 12149 12150 // We don't really have anything else to say about viable candidates. 12151 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 12152 return; 12153 } 12154 12155 // If this is a synthesized deduction guide we're deducing against, add a note 12156 // for it. These deduction guides are not explicitly spelled in the source 12157 // code, so simply printing a deduction failure note mentioning synthesized 12158 // template parameters or pointing to the header of the surrounding RecordDecl 12159 // would be confusing. 12160 // 12161 // We prefer adding such notes at the end of the deduction failure because 12162 // duplicate code snippets appearing in the diagnostic would likely become 12163 // noisy. 12164 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); }); 12165 12166 switch (Cand->FailureKind) { 12167 case ovl_fail_too_many_arguments: 12168 case ovl_fail_too_few_arguments: 12169 return DiagnoseArityMismatch(S, Cand, NumArgs); 12170 12171 case ovl_fail_bad_deduction: 12172 return DiagnoseBadDeduction(S, Cand, NumArgs, 12173 TakingCandidateAddress); 12174 12175 case ovl_fail_illegal_constructor: { 12176 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 12177 << (Fn->getPrimaryTemplate() ? 1 : 0); 12178 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 12179 return; 12180 } 12181 12182 case ovl_fail_object_addrspace_mismatch: { 12183 Qualifiers QualsForPrinting; 12184 QualsForPrinting.setAddressSpace(CtorDestAS); 12185 S.Diag(Fn->getLocation(), 12186 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 12187 << QualsForPrinting; 12188 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 12189 return; 12190 } 12191 12192 case ovl_fail_trivial_conversion: 12193 case ovl_fail_bad_final_conversion: 12194 case ovl_fail_final_conversion_not_exact: 12195 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 12196 12197 case ovl_fail_bad_conversion: { 12198 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 12199 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 12200 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad()) 12201 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 12202 12203 // FIXME: this currently happens when we're called from SemaInit 12204 // when user-conversion overload fails. Figure out how to handle 12205 // those conditions and diagnose them well. 12206 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 12207 } 12208 12209 case ovl_fail_bad_target: 12210 return DiagnoseBadTarget(S, Cand); 12211 12212 case ovl_fail_enable_if: 12213 return DiagnoseFailedEnableIfAttr(S, Cand); 12214 12215 case ovl_fail_explicit: 12216 return DiagnoseFailedExplicitSpec(S, Cand); 12217 12218 case ovl_fail_inhctor_slice: 12219 // It's generally not interesting to note copy/move constructors here. 12220 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 12221 return; 12222 S.Diag(Fn->getLocation(), 12223 diag::note_ovl_candidate_inherited_constructor_slice) 12224 << (Fn->getPrimaryTemplate() ? 1 : 0) 12225 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 12226 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 12227 return; 12228 12229 case ovl_fail_addr_not_available: { 12230 bool Available = checkAddressOfCandidateIsAvailable(S, Fn); 12231 (void)Available; 12232 assert(!Available); 12233 break; 12234 } 12235 case ovl_non_default_multiversion_function: 12236 // Do nothing, these should simply be ignored. 12237 break; 12238 12239 case ovl_fail_constraints_not_satisfied: { 12240 std::string FnDesc; 12241 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 12242 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 12243 Cand->getRewriteKind(), FnDesc); 12244 12245 S.Diag(Fn->getLocation(), 12246 diag::note_ovl_candidate_constraints_not_satisfied) 12247 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 12248 << FnDesc /* Ignored */; 12249 ConstraintSatisfaction Satisfaction; 12250 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 12251 break; 12252 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 12253 } 12254 } 12255 } 12256 12257 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 12258 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 12259 return; 12260 12261 // Desugar the type of the surrogate down to a function type, 12262 // retaining as many typedefs as possible while still showing 12263 // the function type (and, therefore, its parameter types). 12264 QualType FnType = Cand->Surrogate->getConversionType(); 12265 bool isLValueReference = false; 12266 bool isRValueReference = false; 12267 bool isPointer = false; 12268 if (const LValueReferenceType *FnTypeRef = 12269 FnType->getAs<LValueReferenceType>()) { 12270 FnType = FnTypeRef->getPointeeType(); 12271 isLValueReference = true; 12272 } else if (const RValueReferenceType *FnTypeRef = 12273 FnType->getAs<RValueReferenceType>()) { 12274 FnType = FnTypeRef->getPointeeType(); 12275 isRValueReference = true; 12276 } 12277 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 12278 FnType = FnTypePtr->getPointeeType(); 12279 isPointer = true; 12280 } 12281 // Desugar down to a function type. 12282 FnType = QualType(FnType->getAs<FunctionType>(), 0); 12283 // Reconstruct the pointer/reference as appropriate. 12284 if (isPointer) FnType = S.Context.getPointerType(FnType); 12285 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 12286 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 12287 12288 if (!Cand->Viable && 12289 Cand->FailureKind == ovl_fail_constraints_not_satisfied) { 12290 S.Diag(Cand->Surrogate->getLocation(), 12291 diag::note_ovl_surrogate_constraints_not_satisfied) 12292 << Cand->Surrogate; 12293 ConstraintSatisfaction Satisfaction; 12294 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction)) 12295 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 12296 } else { 12297 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 12298 << FnType; 12299 } 12300 } 12301 12302 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 12303 SourceLocation OpLoc, 12304 OverloadCandidate *Cand) { 12305 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 12306 std::string TypeStr("operator"); 12307 TypeStr += Opc; 12308 TypeStr += "("; 12309 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 12310 if (Cand->Conversions.size() == 1) { 12311 TypeStr += ")"; 12312 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 12313 } else { 12314 TypeStr += ", "; 12315 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 12316 TypeStr += ")"; 12317 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 12318 } 12319 } 12320 12321 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 12322 OverloadCandidate *Cand) { 12323 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 12324 if (ICS.isBad()) break; // all meaningless after first invalid 12325 if (!ICS.isAmbiguous()) continue; 12326 12327 ICS.DiagnoseAmbiguousConversion( 12328 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 12329 } 12330 } 12331 12332 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 12333 if (Cand->Function) 12334 return Cand->Function->getLocation(); 12335 if (Cand->IsSurrogate) 12336 return Cand->Surrogate->getLocation(); 12337 return SourceLocation(); 12338 } 12339 12340 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 12341 switch (static_cast<TemplateDeductionResult>(DFI.Result)) { 12342 case TemplateDeductionResult::Success: 12343 case TemplateDeductionResult::NonDependentConversionFailure: 12344 case TemplateDeductionResult::AlreadyDiagnosed: 12345 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 12346 12347 case TemplateDeductionResult::Invalid: 12348 case TemplateDeductionResult::Incomplete: 12349 case TemplateDeductionResult::IncompletePack: 12350 return 1; 12351 12352 case TemplateDeductionResult::Underqualified: 12353 case TemplateDeductionResult::Inconsistent: 12354 return 2; 12355 12356 case TemplateDeductionResult::SubstitutionFailure: 12357 case TemplateDeductionResult::DeducedMismatch: 12358 case TemplateDeductionResult::ConstraintsNotSatisfied: 12359 case TemplateDeductionResult::DeducedMismatchNested: 12360 case TemplateDeductionResult::NonDeducedMismatch: 12361 case TemplateDeductionResult::MiscellaneousDeductionFailure: 12362 case TemplateDeductionResult::CUDATargetMismatch: 12363 return 3; 12364 12365 case TemplateDeductionResult::InstantiationDepth: 12366 return 4; 12367 12368 case TemplateDeductionResult::InvalidExplicitArguments: 12369 return 5; 12370 12371 case TemplateDeductionResult::TooManyArguments: 12372 case TemplateDeductionResult::TooFewArguments: 12373 return 6; 12374 } 12375 llvm_unreachable("Unhandled deduction result"); 12376 } 12377 12378 namespace { 12379 12380 struct CompareOverloadCandidatesForDisplay { 12381 Sema &S; 12382 SourceLocation Loc; 12383 size_t NumArgs; 12384 OverloadCandidateSet::CandidateSetKind CSK; 12385 12386 CompareOverloadCandidatesForDisplay( 12387 Sema &S, SourceLocation Loc, size_t NArgs, 12388 OverloadCandidateSet::CandidateSetKind CSK) 12389 : S(S), NumArgs(NArgs), CSK(CSK) {} 12390 12391 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 12392 // If there are too many or too few arguments, that's the high-order bit we 12393 // want to sort by, even if the immediate failure kind was something else. 12394 if (C->FailureKind == ovl_fail_too_many_arguments || 12395 C->FailureKind == ovl_fail_too_few_arguments) 12396 return static_cast<OverloadFailureKind>(C->FailureKind); 12397 12398 if (C->Function) { 12399 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 12400 return ovl_fail_too_many_arguments; 12401 if (NumArgs < C->Function->getMinRequiredArguments()) 12402 return ovl_fail_too_few_arguments; 12403 } 12404 12405 return static_cast<OverloadFailureKind>(C->FailureKind); 12406 } 12407 12408 bool operator()(const OverloadCandidate *L, 12409 const OverloadCandidate *R) { 12410 // Fast-path this check. 12411 if (L == R) return false; 12412 12413 // Order first by viability. 12414 if (L->Viable) { 12415 if (!R->Viable) return true; 12416 12417 if (int Ord = CompareConversions(*L, *R)) 12418 return Ord < 0; 12419 // Use other tie breakers. 12420 } else if (R->Viable) 12421 return false; 12422 12423 assert(L->Viable == R->Viable); 12424 12425 // Criteria by which we can sort non-viable candidates: 12426 if (!L->Viable) { 12427 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 12428 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 12429 12430 // 1. Arity mismatches come after other candidates. 12431 if (LFailureKind == ovl_fail_too_many_arguments || 12432 LFailureKind == ovl_fail_too_few_arguments) { 12433 if (RFailureKind == ovl_fail_too_many_arguments || 12434 RFailureKind == ovl_fail_too_few_arguments) { 12435 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 12436 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 12437 if (LDist == RDist) { 12438 if (LFailureKind == RFailureKind) 12439 // Sort non-surrogates before surrogates. 12440 return !L->IsSurrogate && R->IsSurrogate; 12441 // Sort candidates requiring fewer parameters than there were 12442 // arguments given after candidates requiring more parameters 12443 // than there were arguments given. 12444 return LFailureKind == ovl_fail_too_many_arguments; 12445 } 12446 return LDist < RDist; 12447 } 12448 return false; 12449 } 12450 if (RFailureKind == ovl_fail_too_many_arguments || 12451 RFailureKind == ovl_fail_too_few_arguments) 12452 return true; 12453 12454 // 2. Bad conversions come first and are ordered by the number 12455 // of bad conversions and quality of good conversions. 12456 if (LFailureKind == ovl_fail_bad_conversion) { 12457 if (RFailureKind != ovl_fail_bad_conversion) 12458 return true; 12459 12460 // The conversion that can be fixed with a smaller number of changes, 12461 // comes first. 12462 unsigned numLFixes = L->Fix.NumConversionsFixed; 12463 unsigned numRFixes = R->Fix.NumConversionsFixed; 12464 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 12465 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 12466 if (numLFixes != numRFixes) { 12467 return numLFixes < numRFixes; 12468 } 12469 12470 // If there's any ordering between the defined conversions... 12471 if (int Ord = CompareConversions(*L, *R)) 12472 return Ord < 0; 12473 } else if (RFailureKind == ovl_fail_bad_conversion) 12474 return false; 12475 12476 if (LFailureKind == ovl_fail_bad_deduction) { 12477 if (RFailureKind != ovl_fail_bad_deduction) 12478 return true; 12479 12480 if (L->DeductionFailure.Result != R->DeductionFailure.Result) { 12481 unsigned LRank = RankDeductionFailure(L->DeductionFailure); 12482 unsigned RRank = RankDeductionFailure(R->DeductionFailure); 12483 if (LRank != RRank) 12484 return LRank < RRank; 12485 } 12486 } else if (RFailureKind == ovl_fail_bad_deduction) 12487 return false; 12488 12489 // TODO: others? 12490 } 12491 12492 // Sort everything else by location. 12493 SourceLocation LLoc = GetLocationForCandidate(L); 12494 SourceLocation RLoc = GetLocationForCandidate(R); 12495 12496 // Put candidates without locations (e.g. builtins) at the end. 12497 if (LLoc.isValid() && RLoc.isValid()) 12498 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 12499 if (LLoc.isValid() && !RLoc.isValid()) 12500 return true; 12501 if (RLoc.isValid() && !LLoc.isValid()) 12502 return false; 12503 assert(!LLoc.isValid() && !RLoc.isValid()); 12504 // For builtins and other functions without locations, fallback to the order 12505 // in which they were added into the candidate set. 12506 return L < R; 12507 } 12508 12509 private: 12510 struct ConversionSignals { 12511 unsigned KindRank = 0; 12512 ImplicitConversionRank Rank = ICR_Exact_Match; 12513 12514 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) { 12515 ConversionSignals Sig; 12516 Sig.KindRank = Seq.getKindRank(); 12517 if (Seq.isStandard()) 12518 Sig.Rank = Seq.Standard.getRank(); 12519 else if (Seq.isUserDefined()) 12520 Sig.Rank = Seq.UserDefined.After.getRank(); 12521 // We intend StaticObjectArgumentConversion to compare the same as 12522 // StandardConversion with ICR_ExactMatch rank. 12523 return Sig; 12524 } 12525 12526 static ConversionSignals ForObjectArgument() { 12527 // We intend StaticObjectArgumentConversion to compare the same as 12528 // StandardConversion with ICR_ExactMatch rank. Default give us that. 12529 return {}; 12530 } 12531 }; 12532 12533 // Returns -1 if conversions in L are considered better. 12534 // 0 if they are considered indistinguishable. 12535 // 1 if conversions in R are better. 12536 int CompareConversions(const OverloadCandidate &L, 12537 const OverloadCandidate &R) { 12538 // We cannot use `isBetterOverloadCandidate` because it is defined 12539 // according to the C++ standard and provides a partial order, but we need 12540 // a total order as this function is used in sort. 12541 assert(L.Conversions.size() == R.Conversions.size()); 12542 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) { 12543 auto LS = L.IgnoreObjectArgument && I == 0 12544 ? ConversionSignals::ForObjectArgument() 12545 : ConversionSignals::ForSequence(L.Conversions[I]); 12546 auto RS = R.IgnoreObjectArgument 12547 ? ConversionSignals::ForObjectArgument() 12548 : ConversionSignals::ForSequence(R.Conversions[I]); 12549 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank)) 12550 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank) 12551 ? -1 12552 : 1; 12553 } 12554 // FIXME: find a way to compare templates for being more or less 12555 // specialized that provides a strict weak ordering. 12556 return 0; 12557 } 12558 }; 12559 } 12560 12561 /// CompleteNonViableCandidate - Normally, overload resolution only 12562 /// computes up to the first bad conversion. Produces the FixIt set if 12563 /// possible. 12564 static void 12565 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 12566 ArrayRef<Expr *> Args, 12567 OverloadCandidateSet::CandidateSetKind CSK) { 12568 assert(!Cand->Viable); 12569 12570 // Don't do anything on failures other than bad conversion. 12571 if (Cand->FailureKind != ovl_fail_bad_conversion) 12572 return; 12573 12574 // We only want the FixIts if all the arguments can be corrected. 12575 bool Unfixable = false; 12576 // Use a implicit copy initialization to check conversion fixes. 12577 Cand->Fix.setConversionChecker(TryCopyInitialization); 12578 12579 // Attempt to fix the bad conversion. 12580 unsigned ConvCount = Cand->Conversions.size(); 12581 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 12582 ++ConvIdx) { 12583 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 12584 if (Cand->Conversions[ConvIdx].isInitialized() && 12585 Cand->Conversions[ConvIdx].isBad()) { 12586 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 12587 break; 12588 } 12589 } 12590 12591 // FIXME: this should probably be preserved from the overload 12592 // operation somehow. 12593 bool SuppressUserConversions = false; 12594 12595 unsigned ConvIdx = 0; 12596 unsigned ArgIdx = 0; 12597 ArrayRef<QualType> ParamTypes; 12598 bool Reversed = Cand->isReversed(); 12599 12600 if (Cand->IsSurrogate) { 12601 QualType ConvType 12602 = Cand->Surrogate->getConversionType().getNonReferenceType(); 12603 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12604 ConvType = ConvPtrType->getPointeeType(); 12605 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 12606 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 12607 ConvIdx = 1; 12608 } else if (Cand->Function) { 12609 ParamTypes = 12610 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 12611 if (isa<CXXMethodDecl>(Cand->Function) && 12612 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 12613 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 12614 ConvIdx = 1; 12615 if (CSK == OverloadCandidateSet::CSK_Operator && 12616 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && 12617 Cand->Function->getDeclName().getCXXOverloadedOperator() != 12618 OO_Subscript) 12619 // Argument 0 is 'this', which doesn't have a corresponding parameter. 12620 ArgIdx = 1; 12621 } 12622 } else { 12623 // Builtin operator. 12624 assert(ConvCount <= 3); 12625 ParamTypes = Cand->BuiltinParamTypes; 12626 } 12627 12628 // Fill in the rest of the conversions. 12629 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 12630 ConvIdx != ConvCount; 12631 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 12632 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 12633 if (Cand->Conversions[ConvIdx].isInitialized()) { 12634 // We've already checked this conversion. 12635 } else if (ParamIdx < ParamTypes.size()) { 12636 if (ParamTypes[ParamIdx]->isDependentType()) 12637 Cand->Conversions[ConvIdx].setAsIdentityConversion( 12638 Args[ArgIdx]->getType()); 12639 else { 12640 Cand->Conversions[ConvIdx] = 12641 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 12642 SuppressUserConversions, 12643 /*InOverloadResolution=*/true, 12644 /*AllowObjCWritebackConversion=*/ 12645 S.getLangOpts().ObjCAutoRefCount); 12646 // Store the FixIt in the candidate if it exists. 12647 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 12648 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 12649 } 12650 } else 12651 Cand->Conversions[ConvIdx].setEllipsis(); 12652 } 12653 } 12654 12655 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 12656 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 12657 SourceLocation OpLoc, 12658 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 12659 // Sort the candidates by viability and position. Sorting directly would 12660 // be prohibitive, so we make a set of pointers and sort those. 12661 SmallVector<OverloadCandidate*, 32> Cands; 12662 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 12663 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 12664 if (!Filter(*Cand)) 12665 continue; 12666 switch (OCD) { 12667 case OCD_AllCandidates: 12668 if (!Cand->Viable) { 12669 if (!Cand->Function && !Cand->IsSurrogate) { 12670 // This a non-viable builtin candidate. We do not, in general, 12671 // want to list every possible builtin candidate. 12672 continue; 12673 } 12674 CompleteNonViableCandidate(S, Cand, Args, Kind); 12675 } 12676 break; 12677 12678 case OCD_ViableCandidates: 12679 if (!Cand->Viable) 12680 continue; 12681 break; 12682 12683 case OCD_AmbiguousCandidates: 12684 if (!Cand->Best) 12685 continue; 12686 break; 12687 } 12688 12689 Cands.push_back(Cand); 12690 } 12691 12692 llvm::stable_sort( 12693 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 12694 12695 return Cands; 12696 } 12697 12698 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 12699 SourceLocation OpLoc) { 12700 bool DeferHint = false; 12701 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 12702 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 12703 // host device candidates. 12704 auto WrongSidedCands = 12705 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 12706 return (Cand.Viable == false && 12707 Cand.FailureKind == ovl_fail_bad_target) || 12708 (Cand.Function && 12709 Cand.Function->template hasAttr<CUDAHostAttr>() && 12710 Cand.Function->template hasAttr<CUDADeviceAttr>()); 12711 }); 12712 DeferHint = !WrongSidedCands.empty(); 12713 } 12714 return DeferHint; 12715 } 12716 12717 /// When overload resolution fails, prints diagnostic messages containing the 12718 /// candidates in the candidate set. 12719 void OverloadCandidateSet::NoteCandidates( 12720 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 12721 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 12722 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 12723 12724 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 12725 12726 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 12727 12728 // In WebAssembly we don't want to emit further diagnostics if a table is 12729 // passed as an argument to a function. 12730 bool NoteCands = true; 12731 for (const Expr *Arg : Args) { 12732 if (Arg->getType()->isWebAssemblyTableType()) 12733 NoteCands = false; 12734 } 12735 12736 if (NoteCands) 12737 NoteCandidates(S, Args, Cands, Opc, OpLoc); 12738 12739 if (OCD == OCD_AmbiguousCandidates) 12740 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 12741 } 12742 12743 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 12744 ArrayRef<OverloadCandidate *> Cands, 12745 StringRef Opc, SourceLocation OpLoc) { 12746 bool ReportedAmbiguousConversions = false; 12747 12748 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 12749 unsigned CandsShown = 0; 12750 auto I = Cands.begin(), E = Cands.end(); 12751 for (; I != E; ++I) { 12752 OverloadCandidate *Cand = *I; 12753 12754 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 12755 ShowOverloads == Ovl_Best) { 12756 break; 12757 } 12758 ++CandsShown; 12759 12760 if (Cand->Function) 12761 NoteFunctionCandidate(S, Cand, Args.size(), 12762 /*TakingCandidateAddress=*/false, DestAS); 12763 else if (Cand->IsSurrogate) 12764 NoteSurrogateCandidate(S, Cand); 12765 else { 12766 assert(Cand->Viable && 12767 "Non-viable built-in candidates are not added to Cands."); 12768 // Generally we only see ambiguities including viable builtin 12769 // operators if overload resolution got screwed up by an 12770 // ambiguous user-defined conversion. 12771 // 12772 // FIXME: It's quite possible for different conversions to see 12773 // different ambiguities, though. 12774 if (!ReportedAmbiguousConversions) { 12775 NoteAmbiguousUserConversions(S, OpLoc, Cand); 12776 ReportedAmbiguousConversions = true; 12777 } 12778 12779 // If this is a viable builtin, print it. 12780 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 12781 } 12782 } 12783 12784 // Inform S.Diags that we've shown an overload set with N elements. This may 12785 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 12786 S.Diags.overloadCandidatesShown(CandsShown); 12787 12788 if (I != E) 12789 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 12790 shouldDeferDiags(S, Args, OpLoc)) 12791 << int(E - I); 12792 } 12793 12794 static SourceLocation 12795 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 12796 return Cand->Specialization ? Cand->Specialization->getLocation() 12797 : SourceLocation(); 12798 } 12799 12800 namespace { 12801 struct CompareTemplateSpecCandidatesForDisplay { 12802 Sema &S; 12803 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 12804 12805 bool operator()(const TemplateSpecCandidate *L, 12806 const TemplateSpecCandidate *R) { 12807 // Fast-path this check. 12808 if (L == R) 12809 return false; 12810 12811 // Assuming that both candidates are not matches... 12812 12813 // Sort by the ranking of deduction failures. 12814 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 12815 return RankDeductionFailure(L->DeductionFailure) < 12816 RankDeductionFailure(R->DeductionFailure); 12817 12818 // Sort everything else by location. 12819 SourceLocation LLoc = GetLocationForCandidate(L); 12820 SourceLocation RLoc = GetLocationForCandidate(R); 12821 12822 // Put candidates without locations (e.g. builtins) at the end. 12823 if (LLoc.isInvalid()) 12824 return false; 12825 if (RLoc.isInvalid()) 12826 return true; 12827 12828 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 12829 } 12830 }; 12831 } 12832 12833 /// Diagnose a template argument deduction failure. 12834 /// We are treating these failures as overload failures due to bad 12835 /// deductions. 12836 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 12837 bool ForTakingAddress) { 12838 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 12839 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 12840 } 12841 12842 void TemplateSpecCandidateSet::destroyCandidates() { 12843 for (iterator i = begin(), e = end(); i != e; ++i) { 12844 i->DeductionFailure.Destroy(); 12845 } 12846 } 12847 12848 void TemplateSpecCandidateSet::clear() { 12849 destroyCandidates(); 12850 Candidates.clear(); 12851 } 12852 12853 /// NoteCandidates - When no template specialization match is found, prints 12854 /// diagnostic messages containing the non-matching specializations that form 12855 /// the candidate set. 12856 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 12857 /// OCD == OCD_AllCandidates and Cand->Viable == false. 12858 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 12859 // Sort the candidates by position (assuming no candidate is a match). 12860 // Sorting directly would be prohibitive, so we make a set of pointers 12861 // and sort those. 12862 SmallVector<TemplateSpecCandidate *, 32> Cands; 12863 Cands.reserve(size()); 12864 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 12865 if (Cand->Specialization) 12866 Cands.push_back(Cand); 12867 // Otherwise, this is a non-matching builtin candidate. We do not, 12868 // in general, want to list every possible builtin candidate. 12869 } 12870 12871 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 12872 12873 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 12874 // for generalization purposes (?). 12875 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 12876 12877 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 12878 unsigned CandsShown = 0; 12879 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 12880 TemplateSpecCandidate *Cand = *I; 12881 12882 // Set an arbitrary limit on the number of candidates we'll spam 12883 // the user with. FIXME: This limit should depend on details of the 12884 // candidate list. 12885 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 12886 break; 12887 ++CandsShown; 12888 12889 assert(Cand->Specialization && 12890 "Non-matching built-in candidates are not added to Cands."); 12891 Cand->NoteDeductionFailure(S, ForTakingAddress); 12892 } 12893 12894 if (I != E) 12895 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 12896 } 12897 12898 // [PossiblyAFunctionType] --> [Return] 12899 // NonFunctionType --> NonFunctionType 12900 // R (A) --> R(A) 12901 // R (*)(A) --> R (A) 12902 // R (&)(A) --> R (A) 12903 // R (S::*)(A) --> R (A) 12904 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 12905 QualType Ret = PossiblyAFunctionType; 12906 if (const PointerType *ToTypePtr = 12907 PossiblyAFunctionType->getAs<PointerType>()) 12908 Ret = ToTypePtr->getPointeeType(); 12909 else if (const ReferenceType *ToTypeRef = 12910 PossiblyAFunctionType->getAs<ReferenceType>()) 12911 Ret = ToTypeRef->getPointeeType(); 12912 else if (const MemberPointerType *MemTypePtr = 12913 PossiblyAFunctionType->getAs<MemberPointerType>()) 12914 Ret = MemTypePtr->getPointeeType(); 12915 Ret = 12916 Context.getCanonicalType(Ret).getUnqualifiedType(); 12917 return Ret; 12918 } 12919 12920 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 12921 bool Complain = true) { 12922 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 12923 S.DeduceReturnType(FD, Loc, Complain)) 12924 return true; 12925 12926 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 12927 if (S.getLangOpts().CPlusPlus17 && 12928 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 12929 !S.ResolveExceptionSpec(Loc, FPT)) 12930 return true; 12931 12932 return false; 12933 } 12934 12935 namespace { 12936 // A helper class to help with address of function resolution 12937 // - allows us to avoid passing around all those ugly parameters 12938 class AddressOfFunctionResolver { 12939 Sema& S; 12940 Expr* SourceExpr; 12941 const QualType& TargetType; 12942 QualType TargetFunctionType; // Extracted function type from target type 12943 12944 bool Complain; 12945 //DeclAccessPair& ResultFunctionAccessPair; 12946 ASTContext& Context; 12947 12948 bool TargetTypeIsNonStaticMemberFunction; 12949 bool FoundNonTemplateFunction; 12950 bool StaticMemberFunctionFromBoundPointer; 12951 bool HasComplained; 12952 12953 OverloadExpr::FindResult OvlExprInfo; 12954 OverloadExpr *OvlExpr; 12955 TemplateArgumentListInfo OvlExplicitTemplateArgs; 12956 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 12957 TemplateSpecCandidateSet FailedCandidates; 12958 12959 public: 12960 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 12961 const QualType &TargetType, bool Complain) 12962 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 12963 Complain(Complain), Context(S.getASTContext()), 12964 TargetTypeIsNonStaticMemberFunction( 12965 !!TargetType->getAs<MemberPointerType>()), 12966 FoundNonTemplateFunction(false), 12967 StaticMemberFunctionFromBoundPointer(false), 12968 HasComplained(false), 12969 OvlExprInfo(OverloadExpr::find(SourceExpr)), 12970 OvlExpr(OvlExprInfo.Expression), 12971 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 12972 ExtractUnqualifiedFunctionTypeFromTargetType(); 12973 12974 if (TargetFunctionType->isFunctionType()) { 12975 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 12976 if (!UME->isImplicitAccess() && 12977 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 12978 StaticMemberFunctionFromBoundPointer = true; 12979 } else if (OvlExpr->hasExplicitTemplateArgs()) { 12980 DeclAccessPair dap; 12981 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 12982 OvlExpr, false, &dap)) { 12983 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 12984 if (!Method->isStatic()) { 12985 // If the target type is a non-function type and the function found 12986 // is a non-static member function, pretend as if that was the 12987 // target, it's the only possible type to end up with. 12988 TargetTypeIsNonStaticMemberFunction = true; 12989 12990 // And skip adding the function if its not in the proper form. 12991 // We'll diagnose this due to an empty set of functions. 12992 if (!OvlExprInfo.HasFormOfMemberPointer) 12993 return; 12994 } 12995 12996 Matches.push_back(std::make_pair(dap, Fn)); 12997 } 12998 return; 12999 } 13000 13001 if (OvlExpr->hasExplicitTemplateArgs()) 13002 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 13003 13004 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 13005 // C++ [over.over]p4: 13006 // If more than one function is selected, [...] 13007 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 13008 if (FoundNonTemplateFunction) 13009 EliminateAllTemplateMatches(); 13010 else 13011 EliminateAllExceptMostSpecializedTemplate(); 13012 } 13013 } 13014 13015 if (S.getLangOpts().CUDA && Matches.size() > 1) 13016 EliminateSuboptimalCudaMatches(); 13017 } 13018 13019 bool hasComplained() const { return HasComplained; } 13020 13021 private: 13022 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 13023 QualType Discard; 13024 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 13025 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 13026 } 13027 13028 /// \return true if A is considered a better overload candidate for the 13029 /// desired type than B. 13030 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 13031 // If A doesn't have exactly the correct type, we don't want to classify it 13032 // as "better" than anything else. This way, the user is required to 13033 // disambiguate for us if there are multiple candidates and no exact match. 13034 return candidateHasExactlyCorrectType(A) && 13035 (!candidateHasExactlyCorrectType(B) || 13036 compareEnableIfAttrs(S, A, B) == Comparison::Better); 13037 } 13038 13039 /// \return true if we were able to eliminate all but one overload candidate, 13040 /// false otherwise. 13041 bool eliminiateSuboptimalOverloadCandidates() { 13042 // Same algorithm as overload resolution -- one pass to pick the "best", 13043 // another pass to be sure that nothing is better than the best. 13044 auto Best = Matches.begin(); 13045 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 13046 if (isBetterCandidate(I->second, Best->second)) 13047 Best = I; 13048 13049 const FunctionDecl *BestFn = Best->second; 13050 auto IsBestOrInferiorToBest = [this, BestFn]( 13051 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 13052 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 13053 }; 13054 13055 // Note: We explicitly leave Matches unmodified if there isn't a clear best 13056 // option, so we can potentially give the user a better error 13057 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 13058 return false; 13059 Matches[0] = *Best; 13060 Matches.resize(1); 13061 return true; 13062 } 13063 13064 bool isTargetTypeAFunction() const { 13065 return TargetFunctionType->isFunctionType(); 13066 } 13067 13068 // [ToType] [Return] 13069 13070 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 13071 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 13072 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 13073 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 13074 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 13075 } 13076 13077 // return true if any matching specializations were found 13078 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 13079 const DeclAccessPair& CurAccessFunPair) { 13080 if (CXXMethodDecl *Method 13081 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 13082 // Skip non-static function templates when converting to pointer, and 13083 // static when converting to member pointer. 13084 bool CanConvertToFunctionPointer = 13085 Method->isStatic() || Method->isExplicitObjectMemberFunction(); 13086 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) 13087 return false; 13088 } 13089 else if (TargetTypeIsNonStaticMemberFunction) 13090 return false; 13091 13092 // C++ [over.over]p2: 13093 // If the name is a function template, template argument deduction is 13094 // done (14.8.2.2), and if the argument deduction succeeds, the 13095 // resulting template argument list is used to generate a single 13096 // function template specialization, which is added to the set of 13097 // overloaded functions considered. 13098 FunctionDecl *Specialization = nullptr; 13099 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 13100 if (TemplateDeductionResult Result = S.DeduceTemplateArguments( 13101 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType, 13102 Specialization, Info, /*IsAddressOfFunction*/ true); 13103 Result != TemplateDeductionResult::Success) { 13104 // Make a note of the failed deduction for diagnostics. 13105 FailedCandidates.addCandidate() 13106 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 13107 MakeDeductionFailureInfo(Context, Result, Info)); 13108 return false; 13109 } 13110 13111 // Template argument deduction ensures that we have an exact match or 13112 // compatible pointer-to-function arguments that would be adjusted by ICS. 13113 // This function template specicalization works. 13114 assert(S.isSameOrCompatibleFunctionType( 13115 Context.getCanonicalType(Specialization->getType()), 13116 Context.getCanonicalType(TargetFunctionType))); 13117 13118 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 13119 return false; 13120 13121 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 13122 return true; 13123 } 13124 13125 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 13126 const DeclAccessPair& CurAccessFunPair) { 13127 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13128 // Skip non-static functions when converting to pointer, and static 13129 // when converting to member pointer. 13130 bool CanConvertToFunctionPointer = 13131 Method->isStatic() || Method->isExplicitObjectMemberFunction(); 13132 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) 13133 return false; 13134 } 13135 else if (TargetTypeIsNonStaticMemberFunction) 13136 return false; 13137 13138 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 13139 if (S.getLangOpts().CUDA) { 13140 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 13141 if (!(Caller && Caller->isImplicit()) && 13142 !S.CUDA().IsAllowedCall(Caller, FunDecl)) 13143 return false; 13144 } 13145 if (FunDecl->isMultiVersion()) { 13146 const auto *TA = FunDecl->getAttr<TargetAttr>(); 13147 if (TA && !TA->isDefaultVersion()) 13148 return false; 13149 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>(); 13150 if (TVA && !TVA->isDefaultVersion()) 13151 return false; 13152 } 13153 13154 // If any candidate has a placeholder return type, trigger its deduction 13155 // now. 13156 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 13157 Complain)) { 13158 HasComplained |= Complain; 13159 return false; 13160 } 13161 13162 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 13163 return false; 13164 13165 // If we're in C, we need to support types that aren't exactly identical. 13166 if (!S.getLangOpts().CPlusPlus || 13167 candidateHasExactlyCorrectType(FunDecl)) { 13168 Matches.push_back(std::make_pair( 13169 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 13170 FoundNonTemplateFunction = true; 13171 return true; 13172 } 13173 } 13174 13175 return false; 13176 } 13177 13178 bool FindAllFunctionsThatMatchTargetTypeExactly() { 13179 bool Ret = false; 13180 13181 // If the overload expression doesn't have the form of a pointer to 13182 // member, don't try to convert it to a pointer-to-member type. 13183 if (IsInvalidFormOfPointerToMemberFunction()) 13184 return false; 13185 13186 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 13187 E = OvlExpr->decls_end(); 13188 I != E; ++I) { 13189 // Look through any using declarations to find the underlying function. 13190 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 13191 13192 // C++ [over.over]p3: 13193 // Non-member functions and static member functions match 13194 // targets of type "pointer-to-function" or "reference-to-function." 13195 // Nonstatic member functions match targets of 13196 // type "pointer-to-member-function." 13197 // Note that according to DR 247, the containing class does not matter. 13198 if (FunctionTemplateDecl *FunctionTemplate 13199 = dyn_cast<FunctionTemplateDecl>(Fn)) { 13200 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 13201 Ret = true; 13202 } 13203 // If we have explicit template arguments supplied, skip non-templates. 13204 else if (!OvlExpr->hasExplicitTemplateArgs() && 13205 AddMatchingNonTemplateFunction(Fn, I.getPair())) 13206 Ret = true; 13207 } 13208 assert(Ret || Matches.empty()); 13209 return Ret; 13210 } 13211 13212 void EliminateAllExceptMostSpecializedTemplate() { 13213 // [...] and any given function template specialization F1 is 13214 // eliminated if the set contains a second function template 13215 // specialization whose function template is more specialized 13216 // than the function template of F1 according to the partial 13217 // ordering rules of 14.5.5.2. 13218 13219 // The algorithm specified above is quadratic. We instead use a 13220 // two-pass algorithm (similar to the one used to identify the 13221 // best viable function in an overload set) that identifies the 13222 // best function template (if it exists). 13223 13224 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 13225 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 13226 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 13227 13228 // TODO: It looks like FailedCandidates does not serve much purpose 13229 // here, since the no_viable diagnostic has index 0. 13230 UnresolvedSetIterator Result = S.getMostSpecialized( 13231 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 13232 SourceExpr->getBeginLoc(), S.PDiag(), 13233 S.PDiag(diag::err_addr_ovl_ambiguous) 13234 << Matches[0].second->getDeclName(), 13235 S.PDiag(diag::note_ovl_candidate) 13236 << (unsigned)oc_function << (unsigned)ocs_described_template, 13237 Complain, TargetFunctionType); 13238 13239 if (Result != MatchesCopy.end()) { 13240 // Make it the first and only element 13241 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 13242 Matches[0].second = cast<FunctionDecl>(*Result); 13243 Matches.resize(1); 13244 } else 13245 HasComplained |= Complain; 13246 } 13247 13248 void EliminateAllTemplateMatches() { 13249 // [...] any function template specializations in the set are 13250 // eliminated if the set also contains a non-template function, [...] 13251 for (unsigned I = 0, N = Matches.size(); I != N; ) { 13252 if (Matches[I].second->getPrimaryTemplate() == nullptr) 13253 ++I; 13254 else { 13255 Matches[I] = Matches[--N]; 13256 Matches.resize(N); 13257 } 13258 } 13259 } 13260 13261 void EliminateSuboptimalCudaMatches() { 13262 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), 13263 Matches); 13264 } 13265 13266 public: 13267 void ComplainNoMatchesFound() const { 13268 assert(Matches.empty()); 13269 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 13270 << OvlExpr->getName() << TargetFunctionType 13271 << OvlExpr->getSourceRange(); 13272 if (FailedCandidates.empty()) 13273 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 13274 /*TakingAddress=*/true); 13275 else { 13276 // We have some deduction failure messages. Use them to diagnose 13277 // the function templates, and diagnose the non-template candidates 13278 // normally. 13279 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 13280 IEnd = OvlExpr->decls_end(); 13281 I != IEnd; ++I) 13282 if (FunctionDecl *Fun = 13283 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 13284 if (!functionHasPassObjectSizeParams(Fun)) 13285 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 13286 /*TakingAddress=*/true); 13287 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 13288 } 13289 } 13290 13291 bool IsInvalidFormOfPointerToMemberFunction() const { 13292 return TargetTypeIsNonStaticMemberFunction && 13293 !OvlExprInfo.HasFormOfMemberPointer; 13294 } 13295 13296 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 13297 // TODO: Should we condition this on whether any functions might 13298 // have matched, or is it more appropriate to do that in callers? 13299 // TODO: a fixit wouldn't hurt. 13300 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 13301 << TargetType << OvlExpr->getSourceRange(); 13302 } 13303 13304 bool IsStaticMemberFunctionFromBoundPointer() const { 13305 return StaticMemberFunctionFromBoundPointer; 13306 } 13307 13308 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 13309 S.Diag(OvlExpr->getBeginLoc(), 13310 diag::err_invalid_form_pointer_member_function) 13311 << OvlExpr->getSourceRange(); 13312 } 13313 13314 void ComplainOfInvalidConversion() const { 13315 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 13316 << OvlExpr->getName() << TargetType; 13317 } 13318 13319 void ComplainMultipleMatchesFound() const { 13320 assert(Matches.size() > 1); 13321 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 13322 << OvlExpr->getName() << OvlExpr->getSourceRange(); 13323 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 13324 /*TakingAddress=*/true); 13325 } 13326 13327 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 13328 13329 int getNumMatches() const { return Matches.size(); } 13330 13331 FunctionDecl* getMatchingFunctionDecl() const { 13332 if (Matches.size() != 1) return nullptr; 13333 return Matches[0].second; 13334 } 13335 13336 const DeclAccessPair* getMatchingFunctionAccessPair() const { 13337 if (Matches.size() != 1) return nullptr; 13338 return &Matches[0].first; 13339 } 13340 }; 13341 } 13342 13343 FunctionDecl * 13344 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 13345 QualType TargetType, 13346 bool Complain, 13347 DeclAccessPair &FoundResult, 13348 bool *pHadMultipleCandidates) { 13349 assert(AddressOfExpr->getType() == Context.OverloadTy); 13350 13351 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 13352 Complain); 13353 int NumMatches = Resolver.getNumMatches(); 13354 FunctionDecl *Fn = nullptr; 13355 bool ShouldComplain = Complain && !Resolver.hasComplained(); 13356 if (NumMatches == 0 && ShouldComplain) { 13357 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 13358 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 13359 else 13360 Resolver.ComplainNoMatchesFound(); 13361 } 13362 else if (NumMatches > 1 && ShouldComplain) 13363 Resolver.ComplainMultipleMatchesFound(); 13364 else if (NumMatches == 1) { 13365 Fn = Resolver.getMatchingFunctionDecl(); 13366 assert(Fn); 13367 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13368 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 13369 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 13370 if (Complain) { 13371 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 13372 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 13373 else 13374 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 13375 } 13376 } 13377 13378 if (pHadMultipleCandidates) 13379 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 13380 return Fn; 13381 } 13382 13383 FunctionDecl * 13384 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 13385 OverloadExpr::FindResult R = OverloadExpr::find(E); 13386 OverloadExpr *Ovl = R.Expression; 13387 bool IsResultAmbiguous = false; 13388 FunctionDecl *Result = nullptr; 13389 DeclAccessPair DAP; 13390 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 13391 13392 // Return positive for better, negative for worse, 0 for equal preference. 13393 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) { 13394 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); 13395 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) - 13396 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2)); 13397 }; 13398 13399 // Don't use the AddressOfResolver because we're specifically looking for 13400 // cases where we have one overload candidate that lacks 13401 // enable_if/pass_object_size/... 13402 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 13403 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 13404 if (!FD) 13405 return nullptr; 13406 13407 if (!checkAddressOfFunctionIsAvailable(FD)) 13408 continue; 13409 13410 // If we found a better result, update Result. 13411 auto FoundBetter = [&]() { 13412 IsResultAmbiguous = false; 13413 DAP = I.getPair(); 13414 Result = FD; 13415 }; 13416 13417 // We have more than one result - see if it is more constrained than the 13418 // previous one. 13419 if (Result) { 13420 // Check CUDA preference first. If the candidates have differennt CUDA 13421 // preference, choose the one with higher CUDA preference. Otherwise, 13422 // choose the one with more constraints. 13423 if (getLangOpts().CUDA) { 13424 int PreferenceByCUDA = CheckCUDAPreference(FD, Result); 13425 // FD has different preference than Result. 13426 if (PreferenceByCUDA != 0) { 13427 // FD is more preferable than Result. 13428 if (PreferenceByCUDA > 0) 13429 FoundBetter(); 13430 continue; 13431 } 13432 } 13433 // FD has the same CUDA prefernece than Result. Continue check 13434 // constraints. 13435 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result); 13436 if (MoreConstrained != FD) { 13437 if (!MoreConstrained) { 13438 IsResultAmbiguous = true; 13439 AmbiguousDecls.push_back(FD); 13440 } 13441 continue; 13442 } 13443 // FD is more constrained - replace Result with it. 13444 } 13445 FoundBetter(); 13446 } 13447 13448 if (IsResultAmbiguous) 13449 return nullptr; 13450 13451 if (Result) { 13452 SmallVector<const Expr *, 1> ResultAC; 13453 // We skipped over some ambiguous declarations which might be ambiguous with 13454 // the selected result. 13455 for (FunctionDecl *Skipped : AmbiguousDecls) { 13456 // If skipped candidate has different CUDA preference than the result, 13457 // there is no ambiguity. Otherwise check whether they have different 13458 // constraints. 13459 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0) 13460 continue; 13461 if (!getMoreConstrainedFunction(Skipped, Result)) 13462 return nullptr; 13463 } 13464 Pair = DAP; 13465 } 13466 return Result; 13467 } 13468 13469 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 13470 ExprResult &SrcExpr, bool DoFunctionPointerConversion) { 13471 Expr *E = SrcExpr.get(); 13472 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 13473 13474 DeclAccessPair DAP; 13475 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 13476 if (!Found || Found->isCPUDispatchMultiVersion() || 13477 Found->isCPUSpecificMultiVersion()) 13478 return false; 13479 13480 // Emitting multiple diagnostics for a function that is both inaccessible and 13481 // unavailable is consistent with our behavior elsewhere. So, always check 13482 // for both. 13483 DiagnoseUseOfDecl(Found, E->getExprLoc()); 13484 CheckAddressOfMemberAccess(E, DAP); 13485 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found); 13486 if (Res.isInvalid()) 13487 return false; 13488 Expr *Fixed = Res.get(); 13489 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType()) 13490 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 13491 else 13492 SrcExpr = Fixed; 13493 return true; 13494 } 13495 13496 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization( 13497 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult, 13498 TemplateSpecCandidateSet *FailedTSC) { 13499 // C++ [over.over]p1: 13500 // [...] [Note: any redundant set of parentheses surrounding the 13501 // overloaded function name is ignored (5.1). ] 13502 // C++ [over.over]p1: 13503 // [...] The overloaded function name can be preceded by the & 13504 // operator. 13505 13506 // If we didn't actually find any template-ids, we're done. 13507 if (!ovl->hasExplicitTemplateArgs()) 13508 return nullptr; 13509 13510 TemplateArgumentListInfo ExplicitTemplateArgs; 13511 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 13512 13513 // Look through all of the overloaded functions, searching for one 13514 // whose type matches exactly. 13515 FunctionDecl *Matched = nullptr; 13516 for (UnresolvedSetIterator I = ovl->decls_begin(), 13517 E = ovl->decls_end(); I != E; ++I) { 13518 // C++0x [temp.arg.explicit]p3: 13519 // [...] In contexts where deduction is done and fails, or in contexts 13520 // where deduction is not done, if a template argument list is 13521 // specified and it, along with any default template arguments, 13522 // identifies a single function template specialization, then the 13523 // template-id is an lvalue for the function template specialization. 13524 FunctionTemplateDecl *FunctionTemplate 13525 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 13526 13527 // C++ [over.over]p2: 13528 // If the name is a function template, template argument deduction is 13529 // done (14.8.2.2), and if the argument deduction succeeds, the 13530 // resulting template argument list is used to generate a single 13531 // function template specialization, which is added to the set of 13532 // overloaded functions considered. 13533 FunctionDecl *Specialization = nullptr; 13534 TemplateDeductionInfo Info(ovl->getNameLoc()); 13535 if (TemplateDeductionResult Result = DeduceTemplateArguments( 13536 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info, 13537 /*IsAddressOfFunction*/ true); 13538 Result != TemplateDeductionResult::Success) { 13539 // Make a note of the failed deduction for diagnostics. 13540 if (FailedTSC) 13541 FailedTSC->addCandidate().set( 13542 I.getPair(), FunctionTemplate->getTemplatedDecl(), 13543 MakeDeductionFailureInfo(Context, Result, Info)); 13544 continue; 13545 } 13546 13547 assert(Specialization && "no specialization and no error?"); 13548 13549 // Multiple matches; we can't resolve to a single declaration. 13550 if (Matched) { 13551 if (Complain) { 13552 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 13553 << ovl->getName(); 13554 NoteAllOverloadCandidates(ovl); 13555 } 13556 return nullptr; 13557 } 13558 13559 Matched = Specialization; 13560 if (FoundResult) *FoundResult = I.getPair(); 13561 } 13562 13563 if (Matched && 13564 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 13565 return nullptr; 13566 13567 return Matched; 13568 } 13569 13570 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 13571 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain, 13572 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining, 13573 unsigned DiagIDForComplaining) { 13574 assert(SrcExpr.get()->getType() == Context.OverloadTy); 13575 13576 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 13577 13578 DeclAccessPair found; 13579 ExprResult SingleFunctionExpression; 13580 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 13581 ovl.Expression, /*complain*/ false, &found)) { 13582 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 13583 SrcExpr = ExprError(); 13584 return true; 13585 } 13586 13587 // It is only correct to resolve to an instance method if we're 13588 // resolving a form that's permitted to be a pointer to member. 13589 // Otherwise we'll end up making a bound member expression, which 13590 // is illegal in all the contexts we resolve like this. 13591 if (!ovl.HasFormOfMemberPointer && 13592 isa<CXXMethodDecl>(fn) && 13593 cast<CXXMethodDecl>(fn)->isInstance()) { 13594 if (!complain) return false; 13595 13596 Diag(ovl.Expression->getExprLoc(), 13597 diag::err_bound_member_function) 13598 << 0 << ovl.Expression->getSourceRange(); 13599 13600 // TODO: I believe we only end up here if there's a mix of 13601 // static and non-static candidates (otherwise the expression 13602 // would have 'bound member' type, not 'overload' type). 13603 // Ideally we would note which candidate was chosen and why 13604 // the static candidates were rejected. 13605 SrcExpr = ExprError(); 13606 return true; 13607 } 13608 13609 // Fix the expression to refer to 'fn'. 13610 SingleFunctionExpression = 13611 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 13612 13613 // If desired, do function-to-pointer decay. 13614 if (doFunctionPointerConversion) { 13615 SingleFunctionExpression = 13616 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 13617 if (SingleFunctionExpression.isInvalid()) { 13618 SrcExpr = ExprError(); 13619 return true; 13620 } 13621 } 13622 } 13623 13624 if (!SingleFunctionExpression.isUsable()) { 13625 if (complain) { 13626 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 13627 << ovl.Expression->getName() 13628 << DestTypeForComplaining 13629 << OpRangeForComplaining 13630 << ovl.Expression->getQualifierLoc().getSourceRange(); 13631 NoteAllOverloadCandidates(SrcExpr.get()); 13632 13633 SrcExpr = ExprError(); 13634 return true; 13635 } 13636 13637 return false; 13638 } 13639 13640 SrcExpr = SingleFunctionExpression; 13641 return true; 13642 } 13643 13644 /// Add a single candidate to the overload set. 13645 static void AddOverloadedCallCandidate(Sema &S, 13646 DeclAccessPair FoundDecl, 13647 TemplateArgumentListInfo *ExplicitTemplateArgs, 13648 ArrayRef<Expr *> Args, 13649 OverloadCandidateSet &CandidateSet, 13650 bool PartialOverloading, 13651 bool KnownValid) { 13652 NamedDecl *Callee = FoundDecl.getDecl(); 13653 if (isa<UsingShadowDecl>(Callee)) 13654 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 13655 13656 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 13657 if (ExplicitTemplateArgs) { 13658 assert(!KnownValid && "Explicit template arguments?"); 13659 return; 13660 } 13661 // Prevent ill-formed function decls to be added as overload candidates. 13662 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 13663 return; 13664 13665 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 13666 /*SuppressUserConversions=*/false, 13667 PartialOverloading); 13668 return; 13669 } 13670 13671 if (FunctionTemplateDecl *FuncTemplate 13672 = dyn_cast<FunctionTemplateDecl>(Callee)) { 13673 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 13674 ExplicitTemplateArgs, Args, CandidateSet, 13675 /*SuppressUserConversions=*/false, 13676 PartialOverloading); 13677 return; 13678 } 13679 13680 assert(!KnownValid && "unhandled case in overloaded call candidate"); 13681 } 13682 13683 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 13684 ArrayRef<Expr *> Args, 13685 OverloadCandidateSet &CandidateSet, 13686 bool PartialOverloading) { 13687 13688 #ifndef NDEBUG 13689 // Verify that ArgumentDependentLookup is consistent with the rules 13690 // in C++0x [basic.lookup.argdep]p3: 13691 // 13692 // Let X be the lookup set produced by unqualified lookup (3.4.1) 13693 // and let Y be the lookup set produced by argument dependent 13694 // lookup (defined as follows). If X contains 13695 // 13696 // -- a declaration of a class member, or 13697 // 13698 // -- a block-scope function declaration that is not a 13699 // using-declaration, or 13700 // 13701 // -- a declaration that is neither a function or a function 13702 // template 13703 // 13704 // then Y is empty. 13705 13706 if (ULE->requiresADL()) { 13707 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 13708 E = ULE->decls_end(); I != E; ++I) { 13709 assert(!(*I)->getDeclContext()->isRecord()); 13710 assert(isa<UsingShadowDecl>(*I) || 13711 !(*I)->getDeclContext()->isFunctionOrMethod()); 13712 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 13713 } 13714 } 13715 #endif 13716 13717 // It would be nice to avoid this copy. 13718 TemplateArgumentListInfo TABuffer; 13719 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13720 if (ULE->hasExplicitTemplateArgs()) { 13721 ULE->copyTemplateArgumentsInto(TABuffer); 13722 ExplicitTemplateArgs = &TABuffer; 13723 } 13724 13725 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 13726 E = ULE->decls_end(); I != E; ++I) 13727 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 13728 CandidateSet, PartialOverloading, 13729 /*KnownValid*/ true); 13730 13731 if (ULE->requiresADL()) 13732 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 13733 Args, ExplicitTemplateArgs, 13734 CandidateSet, PartialOverloading); 13735 } 13736 13737 void Sema::AddOverloadedCallCandidates( 13738 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 13739 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 13740 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 13741 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 13742 CandidateSet, false, /*KnownValid*/ false); 13743 } 13744 13745 /// Determine whether a declaration with the specified name could be moved into 13746 /// a different namespace. 13747 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 13748 switch (Name.getCXXOverloadedOperator()) { 13749 case OO_New: case OO_Array_New: 13750 case OO_Delete: case OO_Array_Delete: 13751 return false; 13752 13753 default: 13754 return true; 13755 } 13756 } 13757 13758 /// Attempt to recover from an ill-formed use of a non-dependent name in a 13759 /// template, where the non-dependent name was declared after the template 13760 /// was defined. This is common in code written for a compilers which do not 13761 /// correctly implement two-stage name lookup. 13762 /// 13763 /// Returns true if a viable candidate was found and a diagnostic was issued. 13764 static bool DiagnoseTwoPhaseLookup( 13765 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 13766 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 13767 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 13768 CXXRecordDecl **FoundInClass = nullptr) { 13769 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 13770 return false; 13771 13772 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 13773 if (DC->isTransparentContext()) 13774 continue; 13775 13776 SemaRef.LookupQualifiedName(R, DC); 13777 13778 if (!R.empty()) { 13779 R.suppressDiagnostics(); 13780 13781 OverloadCandidateSet Candidates(FnLoc, CSK); 13782 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 13783 Candidates); 13784 13785 OverloadCandidateSet::iterator Best; 13786 OverloadingResult OR = 13787 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 13788 13789 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 13790 // We either found non-function declarations or a best viable function 13791 // at class scope. A class-scope lookup result disables ADL. Don't 13792 // look past this, but let the caller know that we found something that 13793 // either is, or might be, usable in this class. 13794 if (FoundInClass) { 13795 *FoundInClass = RD; 13796 if (OR == OR_Success) { 13797 R.clear(); 13798 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 13799 R.resolveKind(); 13800 } 13801 } 13802 return false; 13803 } 13804 13805 if (OR != OR_Success) { 13806 // There wasn't a unique best function or function template. 13807 return false; 13808 } 13809 13810 // Find the namespaces where ADL would have looked, and suggest 13811 // declaring the function there instead. 13812 Sema::AssociatedNamespaceSet AssociatedNamespaces; 13813 Sema::AssociatedClassSet AssociatedClasses; 13814 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 13815 AssociatedNamespaces, 13816 AssociatedClasses); 13817 Sema::AssociatedNamespaceSet SuggestedNamespaces; 13818 if (canBeDeclaredInNamespace(R.getLookupName())) { 13819 DeclContext *Std = SemaRef.getStdNamespace(); 13820 for (Sema::AssociatedNamespaceSet::iterator 13821 it = AssociatedNamespaces.begin(), 13822 end = AssociatedNamespaces.end(); it != end; ++it) { 13823 // Never suggest declaring a function within namespace 'std'. 13824 if (Std && Std->Encloses(*it)) 13825 continue; 13826 13827 // Never suggest declaring a function within a namespace with a 13828 // reserved name, like __gnu_cxx. 13829 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 13830 if (NS && 13831 NS->getQualifiedNameAsString().find("__") != std::string::npos) 13832 continue; 13833 13834 SuggestedNamespaces.insert(*it); 13835 } 13836 } 13837 13838 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 13839 << R.getLookupName(); 13840 if (SuggestedNamespaces.empty()) { 13841 SemaRef.Diag(Best->Function->getLocation(), 13842 diag::note_not_found_by_two_phase_lookup) 13843 << R.getLookupName() << 0; 13844 } else if (SuggestedNamespaces.size() == 1) { 13845 SemaRef.Diag(Best->Function->getLocation(), 13846 diag::note_not_found_by_two_phase_lookup) 13847 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 13848 } else { 13849 // FIXME: It would be useful to list the associated namespaces here, 13850 // but the diagnostics infrastructure doesn't provide a way to produce 13851 // a localized representation of a list of items. 13852 SemaRef.Diag(Best->Function->getLocation(), 13853 diag::note_not_found_by_two_phase_lookup) 13854 << R.getLookupName() << 2; 13855 } 13856 13857 // Try to recover by calling this function. 13858 return true; 13859 } 13860 13861 R.clear(); 13862 } 13863 13864 return false; 13865 } 13866 13867 /// Attempt to recover from ill-formed use of a non-dependent operator in a 13868 /// template, where the non-dependent operator was declared after the template 13869 /// was defined. 13870 /// 13871 /// Returns true if a viable candidate was found and a diagnostic was issued. 13872 static bool 13873 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 13874 SourceLocation OpLoc, 13875 ArrayRef<Expr *> Args) { 13876 DeclarationName OpName = 13877 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 13878 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 13879 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 13880 OverloadCandidateSet::CSK_Operator, 13881 /*ExplicitTemplateArgs=*/nullptr, Args); 13882 } 13883 13884 namespace { 13885 class BuildRecoveryCallExprRAII { 13886 Sema &SemaRef; 13887 Sema::SatisfactionStackResetRAII SatStack; 13888 13889 public: 13890 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) { 13891 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 13892 SemaRef.IsBuildingRecoveryCallExpr = true; 13893 } 13894 13895 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; } 13896 }; 13897 } 13898 13899 /// Attempts to recover from a call where no functions were found. 13900 /// 13901 /// This function will do one of three things: 13902 /// * Diagnose, recover, and return a recovery expression. 13903 /// * Diagnose, fail to recover, and return ExprError(). 13904 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 13905 /// expected to diagnose as appropriate. 13906 static ExprResult 13907 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13908 UnresolvedLookupExpr *ULE, 13909 SourceLocation LParenLoc, 13910 MutableArrayRef<Expr *> Args, 13911 SourceLocation RParenLoc, 13912 bool EmptyLookup, bool AllowTypoCorrection) { 13913 // Do not try to recover if it is already building a recovery call. 13914 // This stops infinite loops for template instantiations like 13915 // 13916 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 13917 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 13918 if (SemaRef.IsBuildingRecoveryCallExpr) 13919 return ExprResult(); 13920 BuildRecoveryCallExprRAII RCE(SemaRef); 13921 13922 CXXScopeSpec SS; 13923 SS.Adopt(ULE->getQualifierLoc()); 13924 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 13925 13926 TemplateArgumentListInfo TABuffer; 13927 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13928 if (ULE->hasExplicitTemplateArgs()) { 13929 ULE->copyTemplateArgumentsInto(TABuffer); 13930 ExplicitTemplateArgs = &TABuffer; 13931 } 13932 13933 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 13934 Sema::LookupOrdinaryName); 13935 CXXRecordDecl *FoundInClass = nullptr; 13936 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 13937 OverloadCandidateSet::CSK_Normal, 13938 ExplicitTemplateArgs, Args, &FoundInClass)) { 13939 // OK, diagnosed a two-phase lookup issue. 13940 } else if (EmptyLookup) { 13941 // Try to recover from an empty lookup with typo correction. 13942 R.clear(); 13943 NoTypoCorrectionCCC NoTypoValidator{}; 13944 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 13945 ExplicitTemplateArgs != nullptr, 13946 dyn_cast<MemberExpr>(Fn)); 13947 CorrectionCandidateCallback &Validator = 13948 AllowTypoCorrection 13949 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 13950 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 13951 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 13952 Args)) 13953 return ExprError(); 13954 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 13955 // We found a usable declaration of the name in a dependent base of some 13956 // enclosing class. 13957 // FIXME: We should also explain why the candidates found by name lookup 13958 // were not viable. 13959 if (SemaRef.DiagnoseDependentMemberLookup(R)) 13960 return ExprError(); 13961 } else { 13962 // We had viable candidates and couldn't recover; let the caller diagnose 13963 // this. 13964 return ExprResult(); 13965 } 13966 13967 // If we get here, we should have issued a diagnostic and formed a recovery 13968 // lookup result. 13969 assert(!R.empty() && "lookup results empty despite recovery"); 13970 13971 // If recovery created an ambiguity, just bail out. 13972 if (R.isAmbiguous()) { 13973 R.suppressDiagnostics(); 13974 return ExprError(); 13975 } 13976 13977 // Build an implicit member call if appropriate. Just drop the 13978 // casts and such from the call, we don't really care. 13979 ExprResult NewFn = ExprError(); 13980 if ((*R.begin())->isCXXClassMember()) 13981 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 13982 ExplicitTemplateArgs, S); 13983 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 13984 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 13985 ExplicitTemplateArgs); 13986 else 13987 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 13988 13989 if (NewFn.isInvalid()) 13990 return ExprError(); 13991 13992 // This shouldn't cause an infinite loop because we're giving it 13993 // an expression with viable lookup results, which should never 13994 // end up here. 13995 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 13996 MultiExprArg(Args.data(), Args.size()), 13997 RParenLoc); 13998 } 13999 14000 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 14001 UnresolvedLookupExpr *ULE, 14002 MultiExprArg Args, 14003 SourceLocation RParenLoc, 14004 OverloadCandidateSet *CandidateSet, 14005 ExprResult *Result) { 14006 #ifndef NDEBUG 14007 if (ULE->requiresADL()) { 14008 // To do ADL, we must have found an unqualified name. 14009 assert(!ULE->getQualifier() && "qualified name with ADL"); 14010 14011 // We don't perform ADL for implicit declarations of builtins. 14012 // Verify that this was correctly set up. 14013 FunctionDecl *F; 14014 if (ULE->decls_begin() != ULE->decls_end() && 14015 ULE->decls_begin() + 1 == ULE->decls_end() && 14016 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 14017 F->getBuiltinID() && F->isImplicit()) 14018 llvm_unreachable("performing ADL for builtin"); 14019 14020 // We don't perform ADL in C. 14021 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 14022 } 14023 #endif 14024 14025 UnbridgedCastsSet UnbridgedCasts; 14026 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 14027 *Result = ExprError(); 14028 return true; 14029 } 14030 14031 // Add the functions denoted by the callee to the set of candidate 14032 // functions, including those from argument-dependent lookup. 14033 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 14034 14035 if (getLangOpts().MSVCCompat && 14036 CurContext->isDependentContext() && !isSFINAEContext() && 14037 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 14038 14039 OverloadCandidateSet::iterator Best; 14040 if (CandidateSet->empty() || 14041 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 14042 OR_No_Viable_Function) { 14043 // In Microsoft mode, if we are inside a template class member function 14044 // then create a type dependent CallExpr. The goal is to postpone name 14045 // lookup to instantiation time to be able to search into type dependent 14046 // base classes. 14047 CallExpr *CE = 14048 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 14049 RParenLoc, CurFPFeatureOverrides()); 14050 CE->markDependentForPostponedNameLookup(); 14051 *Result = CE; 14052 return true; 14053 } 14054 } 14055 14056 if (CandidateSet->empty()) 14057 return false; 14058 14059 UnbridgedCasts.restore(); 14060 return false; 14061 } 14062 14063 // Guess at what the return type for an unresolvable overload should be. 14064 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 14065 OverloadCandidateSet::iterator *Best) { 14066 std::optional<QualType> Result; 14067 // Adjust Type after seeing a candidate. 14068 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 14069 if (!Candidate.Function) 14070 return; 14071 if (Candidate.Function->isInvalidDecl()) 14072 return; 14073 QualType T = Candidate.Function->getReturnType(); 14074 if (T.isNull()) 14075 return; 14076 if (!Result) 14077 Result = T; 14078 else if (Result != T) 14079 Result = QualType(); 14080 }; 14081 14082 // Look for an unambiguous type from a progressively larger subset. 14083 // e.g. if types disagree, but all *viable* overloads return int, choose int. 14084 // 14085 // First, consider only the best candidate. 14086 if (Best && *Best != CS.end()) 14087 ConsiderCandidate(**Best); 14088 // Next, consider only viable candidates. 14089 if (!Result) 14090 for (const auto &C : CS) 14091 if (C.Viable) 14092 ConsiderCandidate(C); 14093 // Finally, consider all candidates. 14094 if (!Result) 14095 for (const auto &C : CS) 14096 ConsiderCandidate(C); 14097 14098 if (!Result) 14099 return QualType(); 14100 auto Value = *Result; 14101 if (Value.isNull() || Value->isUndeducedType()) 14102 return QualType(); 14103 return Value; 14104 } 14105 14106 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 14107 /// the completed call expression. If overload resolution fails, emits 14108 /// diagnostics and returns ExprError() 14109 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 14110 UnresolvedLookupExpr *ULE, 14111 SourceLocation LParenLoc, 14112 MultiExprArg Args, 14113 SourceLocation RParenLoc, 14114 Expr *ExecConfig, 14115 OverloadCandidateSet *CandidateSet, 14116 OverloadCandidateSet::iterator *Best, 14117 OverloadingResult OverloadResult, 14118 bool AllowTypoCorrection) { 14119 switch (OverloadResult) { 14120 case OR_Success: { 14121 FunctionDecl *FDecl = (*Best)->Function; 14122 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 14123 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 14124 return ExprError(); 14125 ExprResult Res = 14126 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 14127 if (Res.isInvalid()) 14128 return ExprError(); 14129 return SemaRef.BuildResolvedCallExpr( 14130 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, 14131 /*IsExecConfig=*/false, 14132 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate)); 14133 } 14134 14135 case OR_No_Viable_Function: { 14136 if (*Best != CandidateSet->end() && 14137 CandidateSet->getKind() == 14138 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) { 14139 if (CXXMethodDecl *M = 14140 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function); 14141 M && M->isImplicitObjectMemberFunction()) { 14142 CandidateSet->NoteCandidates( 14143 PartialDiagnosticAt( 14144 Fn->getBeginLoc(), 14145 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M), 14146 SemaRef, OCD_AmbiguousCandidates, Args); 14147 return ExprError(); 14148 } 14149 } 14150 14151 // Try to recover by looking for viable functions which the user might 14152 // have meant to call. 14153 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 14154 Args, RParenLoc, 14155 CandidateSet->empty(), 14156 AllowTypoCorrection); 14157 if (Recovery.isInvalid() || Recovery.isUsable()) 14158 return Recovery; 14159 14160 // If the user passes in a function that we can't take the address of, we 14161 // generally end up emitting really bad error messages. Here, we attempt to 14162 // emit better ones. 14163 for (const Expr *Arg : Args) { 14164 if (!Arg->getType()->isFunctionType()) 14165 continue; 14166 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 14167 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14168 if (FD && 14169 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 14170 Arg->getExprLoc())) 14171 return ExprError(); 14172 } 14173 } 14174 14175 CandidateSet->NoteCandidates( 14176 PartialDiagnosticAt( 14177 Fn->getBeginLoc(), 14178 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 14179 << ULE->getName() << Fn->getSourceRange()), 14180 SemaRef, OCD_AllCandidates, Args); 14181 break; 14182 } 14183 14184 case OR_Ambiguous: 14185 CandidateSet->NoteCandidates( 14186 PartialDiagnosticAt(Fn->getBeginLoc(), 14187 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 14188 << ULE->getName() << Fn->getSourceRange()), 14189 SemaRef, OCD_AmbiguousCandidates, Args); 14190 break; 14191 14192 case OR_Deleted: { 14193 FunctionDecl *FDecl = (*Best)->Function; 14194 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(), 14195 Fn->getSourceRange(), ULE->getName(), 14196 *CandidateSet, FDecl, Args); 14197 14198 // We emitted an error for the unavailable/deleted function call but keep 14199 // the call in the AST. 14200 ExprResult Res = 14201 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 14202 if (Res.isInvalid()) 14203 return ExprError(); 14204 return SemaRef.BuildResolvedCallExpr( 14205 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, 14206 /*IsExecConfig=*/false, 14207 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate)); 14208 } 14209 } 14210 14211 // Overload resolution failed, try to recover. 14212 SmallVector<Expr *, 8> SubExprs = {Fn}; 14213 SubExprs.append(Args.begin(), Args.end()); 14214 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 14215 chooseRecoveryType(*CandidateSet, Best)); 14216 } 14217 14218 static void markUnaddressableCandidatesUnviable(Sema &S, 14219 OverloadCandidateSet &CS) { 14220 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 14221 if (I->Viable && 14222 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 14223 I->Viable = false; 14224 I->FailureKind = ovl_fail_addr_not_available; 14225 } 14226 } 14227 } 14228 14229 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 14230 UnresolvedLookupExpr *ULE, 14231 SourceLocation LParenLoc, 14232 MultiExprArg Args, 14233 SourceLocation RParenLoc, 14234 Expr *ExecConfig, 14235 bool AllowTypoCorrection, 14236 bool CalleesAddressIsTaken) { 14237 OverloadCandidateSet CandidateSet( 14238 Fn->getExprLoc(), CalleesAddressIsTaken 14239 ? OverloadCandidateSet::CSK_AddressOfOverloadSet 14240 : OverloadCandidateSet::CSK_Normal); 14241 ExprResult result; 14242 14243 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 14244 &result)) 14245 return result; 14246 14247 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 14248 // functions that aren't addressible are considered unviable. 14249 if (CalleesAddressIsTaken) 14250 markUnaddressableCandidatesUnviable(*this, CandidateSet); 14251 14252 OverloadCandidateSet::iterator Best; 14253 OverloadingResult OverloadResult = 14254 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 14255 14256 // Model the case with a call to a templated function whose definition 14257 // encloses the call and whose return type contains a placeholder type as if 14258 // the UnresolvedLookupExpr was type-dependent. 14259 if (OverloadResult == OR_Success) { 14260 const FunctionDecl *FDecl = Best->Function; 14261 if (FDecl && FDecl->isTemplateInstantiation() && 14262 FDecl->getReturnType()->isUndeducedType()) { 14263 if (const auto *TP = 14264 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false); 14265 TP && TP->willHaveBody()) { 14266 return CallExpr::Create(Context, Fn, Args, Context.DependentTy, 14267 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 14268 } 14269 } 14270 } 14271 14272 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 14273 ExecConfig, &CandidateSet, &Best, 14274 OverloadResult, AllowTypoCorrection); 14275 } 14276 14277 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 14278 NestedNameSpecifierLoc NNSLoc, 14279 DeclarationNameInfo DNI, 14280 const UnresolvedSetImpl &Fns, 14281 bool PerformADL) { 14282 return UnresolvedLookupExpr::Create( 14283 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(), 14284 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false); 14285 } 14286 14287 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 14288 CXXConversionDecl *Method, 14289 bool HadMultipleCandidates) { 14290 // Convert the expression to match the conversion function's implicit object 14291 // parameter. 14292 ExprResult Exp; 14293 if (Method->isExplicitObjectMemberFunction()) 14294 Exp = InitializeExplicitObjectArgument(*this, E, Method); 14295 else 14296 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 14297 FoundDecl, Method); 14298 if (Exp.isInvalid()) 14299 return true; 14300 14301 if (Method->getParent()->isLambda() && 14302 Method->getConversionType()->isBlockPointerType()) { 14303 // This is a lambda conversion to block pointer; check if the argument 14304 // was a LambdaExpr. 14305 Expr *SubE = E; 14306 auto *CE = dyn_cast<CastExpr>(SubE); 14307 if (CE && CE->getCastKind() == CK_NoOp) 14308 SubE = CE->getSubExpr(); 14309 SubE = SubE->IgnoreParens(); 14310 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 14311 SubE = BE->getSubExpr(); 14312 if (isa<LambdaExpr>(SubE)) { 14313 // For the conversion to block pointer on a lambda expression, we 14314 // construct a special BlockLiteral instead; this doesn't really make 14315 // a difference in ARC, but outside of ARC the resulting block literal 14316 // follows the normal lifetime rules for block literals instead of being 14317 // autoreleased. 14318 PushExpressionEvaluationContext( 14319 ExpressionEvaluationContext::PotentiallyEvaluated); 14320 ExprResult BlockExp = BuildBlockForLambdaConversion( 14321 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); 14322 PopExpressionEvaluationContext(); 14323 14324 // FIXME: This note should be produced by a CodeSynthesisContext. 14325 if (BlockExp.isInvalid()) 14326 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); 14327 return BlockExp; 14328 } 14329 } 14330 CallExpr *CE; 14331 QualType ResultType = Method->getReturnType(); 14332 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14333 ResultType = ResultType.getNonLValueExprType(Context); 14334 if (Method->isExplicitObjectMemberFunction()) { 14335 ExprResult FnExpr = 14336 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(), 14337 HadMultipleCandidates, E->getBeginLoc()); 14338 if (FnExpr.isInvalid()) 14339 return ExprError(); 14340 Expr *ObjectParam = Exp.get(); 14341 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1), 14342 ResultType, VK, Exp.get()->getEndLoc(), 14343 CurFPFeatureOverrides()); 14344 } else { 14345 MemberExpr *ME = 14346 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), 14347 NestedNameSpecifierLoc(), SourceLocation(), Method, 14348 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), 14349 HadMultipleCandidates, DeclarationNameInfo(), 14350 Context.BoundMemberTy, VK_PRValue, OK_Ordinary); 14351 14352 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK, 14353 Exp.get()->getEndLoc(), 14354 CurFPFeatureOverrides()); 14355 } 14356 14357 if (CheckFunctionCall(Method, CE, 14358 Method->getType()->castAs<FunctionProtoType>())) 14359 return ExprError(); 14360 14361 return CheckForImmediateInvocation(CE, CE->getDirectCallee()); 14362 } 14363 14364 ExprResult 14365 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 14366 const UnresolvedSetImpl &Fns, 14367 Expr *Input, bool PerformADL) { 14368 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 14369 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 14370 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14371 // TODO: provide better source location info. 14372 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 14373 14374 if (checkPlaceholderForOverload(*this, Input)) 14375 return ExprError(); 14376 14377 Expr *Args[2] = { Input, nullptr }; 14378 unsigned NumArgs = 1; 14379 14380 // For post-increment and post-decrement, add the implicit '0' as 14381 // the second argument, so that we know this is a post-increment or 14382 // post-decrement. 14383 if (Opc == UO_PostInc || Opc == UO_PostDec) { 14384 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 14385 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 14386 SourceLocation()); 14387 NumArgs = 2; 14388 } 14389 14390 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 14391 14392 if (Input->isTypeDependent()) { 14393 ExprValueKind VK = ExprValueKind::VK_PRValue; 14394 // [C++26][expr.unary.op][expr.pre.incr] 14395 // The * operator yields an lvalue of type 14396 // The pre/post increment operators yied an lvalue. 14397 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref) 14398 VK = VK_LValue; 14399 14400 if (Fns.empty()) 14401 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK, 14402 OK_Ordinary, OpLoc, false, 14403 CurFPFeatureOverrides()); 14404 14405 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14406 ExprResult Fn = CreateUnresolvedLookupExpr( 14407 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 14408 if (Fn.isInvalid()) 14409 return ExprError(); 14410 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 14411 Context.DependentTy, VK_PRValue, OpLoc, 14412 CurFPFeatureOverrides()); 14413 } 14414 14415 // Build an empty overload set. 14416 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 14417 14418 // Add the candidates from the given function set. 14419 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 14420 14421 // Add operator candidates that are member functions. 14422 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 14423 14424 // Add candidates from ADL. 14425 if (PerformADL) { 14426 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 14427 /*ExplicitTemplateArgs*/nullptr, 14428 CandidateSet); 14429 } 14430 14431 // Add builtin operator candidates. 14432 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 14433 14434 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14435 14436 // Perform overload resolution. 14437 OverloadCandidateSet::iterator Best; 14438 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14439 case OR_Success: { 14440 // We found a built-in operator or an overloaded operator. 14441 FunctionDecl *FnDecl = Best->Function; 14442 14443 if (FnDecl) { 14444 Expr *Base = nullptr; 14445 // We matched an overloaded operator. Build a call to that 14446 // operator. 14447 14448 // Convert the arguments. 14449 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 14450 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl); 14451 14452 ExprResult InputInit; 14453 if (Method->isExplicitObjectMemberFunction()) 14454 InputInit = InitializeExplicitObjectArgument(*this, Input, Method); 14455 else 14456 InputInit = PerformImplicitObjectArgumentInitialization( 14457 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14458 if (InputInit.isInvalid()) 14459 return ExprError(); 14460 Base = Input = InputInit.get(); 14461 } else { 14462 // Convert the arguments. 14463 ExprResult InputInit 14464 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14465 Context, 14466 FnDecl->getParamDecl(0)), 14467 SourceLocation(), 14468 Input); 14469 if (InputInit.isInvalid()) 14470 return ExprError(); 14471 Input = InputInit.get(); 14472 } 14473 14474 // Build the actual expression node. 14475 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 14476 Base, HadMultipleCandidates, 14477 OpLoc); 14478 if (FnExpr.isInvalid()) 14479 return ExprError(); 14480 14481 // Determine the result type. 14482 QualType ResultTy = FnDecl->getReturnType(); 14483 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14484 ResultTy = ResultTy.getNonLValueExprType(Context); 14485 14486 Args[0] = Input; 14487 CallExpr *TheCall = CXXOperatorCallExpr::Create( 14488 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 14489 CurFPFeatureOverrides(), 14490 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate)); 14491 14492 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 14493 return ExprError(); 14494 14495 if (CheckFunctionCall(FnDecl, TheCall, 14496 FnDecl->getType()->castAs<FunctionProtoType>())) 14497 return ExprError(); 14498 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 14499 } else { 14500 // We matched a built-in operator. Convert the arguments, then 14501 // break out so that we will build the appropriate built-in 14502 // operator node. 14503 ExprResult InputRes = PerformImplicitConversion( 14504 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], 14505 AssignmentAction::Passing, 14506 CheckedConversionKind::ForBuiltinOverloadedOp); 14507 if (InputRes.isInvalid()) 14508 return ExprError(); 14509 Input = InputRes.get(); 14510 break; 14511 } 14512 } 14513 14514 case OR_No_Viable_Function: 14515 // This is an erroneous use of an operator which can be overloaded by 14516 // a non-member function. Check for non-member operators which were 14517 // defined too late to be candidates. 14518 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 14519 // FIXME: Recover by calling the found function. 14520 return ExprError(); 14521 14522 // No viable function; fall through to handling this as a 14523 // built-in operator, which will produce an error message for us. 14524 break; 14525 14526 case OR_Ambiguous: 14527 CandidateSet.NoteCandidates( 14528 PartialDiagnosticAt(OpLoc, 14529 PDiag(diag::err_ovl_ambiguous_oper_unary) 14530 << UnaryOperator::getOpcodeStr(Opc) 14531 << Input->getType() << Input->getSourceRange()), 14532 *this, OCD_AmbiguousCandidates, ArgsArray, 14533 UnaryOperator::getOpcodeStr(Opc), OpLoc); 14534 return ExprError(); 14535 14536 case OR_Deleted: { 14537 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the 14538 // object whose method was called. Later in NoteCandidates size of ArgsArray 14539 // is passed further and it eventually ends up compared to number of 14540 // function candidate parameters which never includes the object parameter, 14541 // so slice ArgsArray to make sure apples are compared to apples. 14542 StringLiteral *Msg = Best->Function->getDeletedMessage(); 14543 CandidateSet.NoteCandidates( 14544 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14545 << UnaryOperator::getOpcodeStr(Opc) 14546 << (Msg != nullptr) 14547 << (Msg ? Msg->getString() : StringRef()) 14548 << Input->getSourceRange()), 14549 *this, OCD_AllCandidates, ArgsArray.drop_front(), 14550 UnaryOperator::getOpcodeStr(Opc), OpLoc); 14551 return ExprError(); 14552 } 14553 } 14554 14555 // Either we found no viable overloaded operator or we matched a 14556 // built-in operator. In either case, fall through to trying to 14557 // build a built-in operation. 14558 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14559 } 14560 14561 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 14562 OverloadedOperatorKind Op, 14563 const UnresolvedSetImpl &Fns, 14564 ArrayRef<Expr *> Args, bool PerformADL) { 14565 SourceLocation OpLoc = CandidateSet.getLocation(); 14566 14567 OverloadedOperatorKind ExtraOp = 14568 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 14569 ? getRewrittenOverloadedOperator(Op) 14570 : OO_None; 14571 14572 // Add the candidates from the given function set. This also adds the 14573 // rewritten candidates using these functions if necessary. 14574 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 14575 14576 // Add operator candidates that are member functions. 14577 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 14578 if (CandidateSet.getRewriteInfo().allowsReversed(Op)) 14579 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 14580 OverloadCandidateParamOrder::Reversed); 14581 14582 // In C++20, also add any rewritten member candidates. 14583 if (ExtraOp) { 14584 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 14585 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp)) 14586 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 14587 CandidateSet, 14588 OverloadCandidateParamOrder::Reversed); 14589 } 14590 14591 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 14592 // performed for an assignment operator (nor for operator[] nor operator->, 14593 // which don't get here). 14594 if (Op != OO_Equal && PerformADL) { 14595 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14596 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 14597 /*ExplicitTemplateArgs*/ nullptr, 14598 CandidateSet); 14599 if (ExtraOp) { 14600 DeclarationName ExtraOpName = 14601 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 14602 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 14603 /*ExplicitTemplateArgs*/ nullptr, 14604 CandidateSet); 14605 } 14606 } 14607 14608 // Add builtin operator candidates. 14609 // 14610 // FIXME: We don't add any rewritten candidates here. This is strictly 14611 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 14612 // resulting in our selecting a rewritten builtin candidate. For example: 14613 // 14614 // enum class E { e }; 14615 // bool operator!=(E, E) requires false; 14616 // bool k = E::e != E::e; 14617 // 14618 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 14619 // it seems unreasonable to consider rewritten builtin candidates. A core 14620 // issue has been filed proposing to removed this requirement. 14621 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 14622 } 14623 14624 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 14625 BinaryOperatorKind Opc, 14626 const UnresolvedSetImpl &Fns, Expr *LHS, 14627 Expr *RHS, bool PerformADL, 14628 bool AllowRewrittenCandidates, 14629 FunctionDecl *DefaultedFn) { 14630 Expr *Args[2] = { LHS, RHS }; 14631 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 14632 14633 if (!getLangOpts().CPlusPlus20) 14634 AllowRewrittenCandidates = false; 14635 14636 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 14637 14638 // If either side is type-dependent, create an appropriate dependent 14639 // expression. 14640 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 14641 if (Fns.empty()) { 14642 // If there are no functions to store, just build a dependent 14643 // BinaryOperator or CompoundAssignment. 14644 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14645 return CompoundAssignOperator::Create( 14646 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 14647 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 14648 Context.DependentTy); 14649 return BinaryOperator::Create( 14650 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 14651 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 14652 } 14653 14654 // FIXME: save results of ADL from here? 14655 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14656 // TODO: provide better source location info in DNLoc component. 14657 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14658 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 14659 ExprResult Fn = CreateUnresolvedLookupExpr( 14660 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 14661 if (Fn.isInvalid()) 14662 return ExprError(); 14663 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 14664 Context.DependentTy, VK_PRValue, OpLoc, 14665 CurFPFeatureOverrides()); 14666 } 14667 14668 // If this is the .* operator, which is not overloadable, just 14669 // create a built-in binary operator. 14670 if (Opc == BO_PtrMemD) { 14671 auto CheckPlaceholder = [&](Expr *&Arg) { 14672 ExprResult Res = CheckPlaceholderExpr(Arg); 14673 if (Res.isUsable()) 14674 Arg = Res.get(); 14675 return !Res.isUsable(); 14676 }; 14677 14678 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*' 14679 // expression that contains placeholders (in either the LHS or RHS). 14680 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1])) 14681 return ExprError(); 14682 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14683 } 14684 14685 // Always do placeholder-like conversions on the RHS. 14686 if (checkPlaceholderForOverload(*this, Args[1])) 14687 return ExprError(); 14688 14689 // Do placeholder-like conversion on the LHS; note that we should 14690 // not get here with a PseudoObject LHS. 14691 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 14692 if (checkPlaceholderForOverload(*this, Args[0])) 14693 return ExprError(); 14694 14695 // If this is the assignment operator, we only perform overload resolution 14696 // if the left-hand side is a class or enumeration type. This is actually 14697 // a hack. The standard requires that we do overload resolution between the 14698 // various built-in candidates, but as DR507 points out, this can lead to 14699 // problems. So we do it this way, which pretty much follows what GCC does. 14700 // Note that we go the traditional code path for compound assignment forms. 14701 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 14702 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14703 14704 // Build the overload set. 14705 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator, 14706 OverloadCandidateSet::OperatorRewriteInfo( 14707 Op, OpLoc, AllowRewrittenCandidates)); 14708 if (DefaultedFn) 14709 CandidateSet.exclude(DefaultedFn); 14710 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 14711 14712 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14713 14714 // Perform overload resolution. 14715 OverloadCandidateSet::iterator Best; 14716 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14717 case OR_Success: { 14718 // We found a built-in operator or an overloaded operator. 14719 FunctionDecl *FnDecl = Best->Function; 14720 14721 bool IsReversed = Best->isReversed(); 14722 if (IsReversed) 14723 std::swap(Args[0], Args[1]); 14724 14725 if (FnDecl) { 14726 14727 if (FnDecl->isInvalidDecl()) 14728 return ExprError(); 14729 14730 Expr *Base = nullptr; 14731 // We matched an overloaded operator. Build a call to that 14732 // operator. 14733 14734 OverloadedOperatorKind ChosenOp = 14735 FnDecl->getDeclName().getCXXOverloadedOperator(); 14736 14737 // C++2a [over.match.oper]p9: 14738 // If a rewritten operator== candidate is selected by overload 14739 // resolution for an operator@, its return type shall be cv bool 14740 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 14741 !FnDecl->getReturnType()->isBooleanType()) { 14742 bool IsExtension = 14743 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 14744 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 14745 : diag::err_ovl_rewrite_equalequal_not_bool) 14746 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 14747 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14748 Diag(FnDecl->getLocation(), diag::note_declared_at); 14749 if (!IsExtension) 14750 return ExprError(); 14751 } 14752 14753 if (AllowRewrittenCandidates && !IsReversed && 14754 CandidateSet.getRewriteInfo().isReversible()) { 14755 // We could have reversed this operator, but didn't. Check if some 14756 // reversed form was a viable candidate, and if so, if it had a 14757 // better conversion for either parameter. If so, this call is 14758 // formally ambiguous, and allowing it is an extension. 14759 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 14760 for (OverloadCandidate &Cand : CandidateSet) { 14761 if (Cand.Viable && Cand.Function && Cand.isReversed() && 14762 allowAmbiguity(Context, Cand.Function, FnDecl)) { 14763 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 14764 if (CompareImplicitConversionSequences( 14765 *this, OpLoc, Cand.Conversions[ArgIdx], 14766 Best->Conversions[ArgIdx]) == 14767 ImplicitConversionSequence::Better) { 14768 AmbiguousWith.push_back(Cand.Function); 14769 break; 14770 } 14771 } 14772 } 14773 } 14774 14775 if (!AmbiguousWith.empty()) { 14776 bool AmbiguousWithSelf = 14777 AmbiguousWith.size() == 1 && 14778 declaresSameEntity(AmbiguousWith.front(), FnDecl); 14779 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 14780 << BinaryOperator::getOpcodeStr(Opc) 14781 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 14782 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14783 if (AmbiguousWithSelf) { 14784 Diag(FnDecl->getLocation(), 14785 diag::note_ovl_ambiguous_oper_binary_reversed_self); 14786 // Mark member== const or provide matching != to disallow reversed 14787 // args. Eg. 14788 // struct S { bool operator==(const S&); }; 14789 // S()==S(); 14790 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl)) 14791 if (Op == OverloadedOperatorKind::OO_EqualEqual && 14792 !MD->isConst() && 14793 !MD->hasCXXExplicitFunctionObjectParameter() && 14794 Context.hasSameUnqualifiedType( 14795 MD->getFunctionObjectParameterType(), 14796 MD->getParamDecl(0)->getType().getNonReferenceType()) && 14797 Context.hasSameUnqualifiedType( 14798 MD->getFunctionObjectParameterType(), 14799 Args[0]->getType()) && 14800 Context.hasSameUnqualifiedType( 14801 MD->getFunctionObjectParameterType(), 14802 Args[1]->getType())) 14803 Diag(FnDecl->getLocation(), 14804 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const); 14805 } else { 14806 Diag(FnDecl->getLocation(), 14807 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 14808 for (auto *F : AmbiguousWith) 14809 Diag(F->getLocation(), 14810 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 14811 } 14812 } 14813 } 14814 14815 // Check for nonnull = nullable. 14816 // This won't be caught in the arg's initialization: the parameter to 14817 // the assignment operator is not marked nonnull. 14818 if (Op == OO_Equal) 14819 diagnoseNullableToNonnullConversion(Args[0]->getType(), 14820 Args[1]->getType(), OpLoc); 14821 14822 // Convert the arguments. 14823 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 14824 // Best->Access is only meaningful for class members. 14825 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 14826 14827 ExprResult Arg0, Arg1; 14828 unsigned ParamIdx = 0; 14829 if (Method->isExplicitObjectMemberFunction()) { 14830 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl); 14831 ParamIdx = 1; 14832 } else { 14833 Arg0 = PerformImplicitObjectArgumentInitialization( 14834 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14835 } 14836 Arg1 = PerformCopyInitialization( 14837 InitializedEntity::InitializeParameter( 14838 Context, FnDecl->getParamDecl(ParamIdx)), 14839 SourceLocation(), Args[1]); 14840 if (Arg0.isInvalid() || Arg1.isInvalid()) 14841 return ExprError(); 14842 14843 Base = Args[0] = Arg0.getAs<Expr>(); 14844 Args[1] = RHS = Arg1.getAs<Expr>(); 14845 } else { 14846 // Convert the arguments. 14847 ExprResult Arg0 = PerformCopyInitialization( 14848 InitializedEntity::InitializeParameter(Context, 14849 FnDecl->getParamDecl(0)), 14850 SourceLocation(), Args[0]); 14851 if (Arg0.isInvalid()) 14852 return ExprError(); 14853 14854 ExprResult Arg1 = 14855 PerformCopyInitialization( 14856 InitializedEntity::InitializeParameter(Context, 14857 FnDecl->getParamDecl(1)), 14858 SourceLocation(), Args[1]); 14859 if (Arg1.isInvalid()) 14860 return ExprError(); 14861 Args[0] = LHS = Arg0.getAs<Expr>(); 14862 Args[1] = RHS = Arg1.getAs<Expr>(); 14863 } 14864 14865 // Build the actual expression node. 14866 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14867 Best->FoundDecl, Base, 14868 HadMultipleCandidates, OpLoc); 14869 if (FnExpr.isInvalid()) 14870 return ExprError(); 14871 14872 // Determine the result type. 14873 QualType ResultTy = FnDecl->getReturnType(); 14874 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14875 ResultTy = ResultTy.getNonLValueExprType(Context); 14876 14877 CallExpr *TheCall; 14878 ArrayRef<const Expr *> ArgsArray(Args, 2); 14879 const Expr *ImplicitThis = nullptr; 14880 14881 // We always create a CXXOperatorCallExpr, even for explicit object 14882 // members; CodeGen should take care not to emit the this pointer. 14883 TheCall = CXXOperatorCallExpr::Create( 14884 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 14885 CurFPFeatureOverrides(), 14886 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate)); 14887 14888 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl); 14889 Method && Method->isImplicitObjectMemberFunction()) { 14890 // Cut off the implicit 'this'. 14891 ImplicitThis = ArgsArray[0]; 14892 ArgsArray = ArgsArray.slice(1); 14893 } 14894 14895 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 14896 FnDecl)) 14897 return ExprError(); 14898 14899 if (Op == OO_Equal) { 14900 // Check for a self move. 14901 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 14902 // lifetime check. 14903 checkAssignmentLifetime( 14904 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)}, 14905 Args[1]); 14906 } 14907 if (ImplicitThis) { 14908 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 14909 QualType ThisTypeFromDecl = Context.getPointerType( 14910 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType()); 14911 14912 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 14913 ThisTypeFromDecl); 14914 } 14915 14916 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 14917 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 14918 VariadicDoesNotApply); 14919 14920 ExprResult R = MaybeBindToTemporary(TheCall); 14921 if (R.isInvalid()) 14922 return ExprError(); 14923 14924 R = CheckForImmediateInvocation(R, FnDecl); 14925 if (R.isInvalid()) 14926 return ExprError(); 14927 14928 // For a rewritten candidate, we've already reversed the arguments 14929 // if needed. Perform the rest of the rewrite now. 14930 if ((Best->RewriteKind & CRK_DifferentOperator) || 14931 (Op == OO_Spaceship && IsReversed)) { 14932 if (Op == OO_ExclaimEqual) { 14933 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 14934 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 14935 } else { 14936 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 14937 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 14938 Expr *ZeroLiteral = 14939 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 14940 14941 Sema::CodeSynthesisContext Ctx; 14942 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 14943 Ctx.Entity = FnDecl; 14944 pushCodeSynthesisContext(Ctx); 14945 14946 R = CreateOverloadedBinOp( 14947 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 14948 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true, 14949 /*AllowRewrittenCandidates=*/false); 14950 14951 popCodeSynthesisContext(); 14952 } 14953 if (R.isInvalid()) 14954 return ExprError(); 14955 } else { 14956 assert(ChosenOp == Op && "unexpected operator name"); 14957 } 14958 14959 // Make a note in the AST if we did any rewriting. 14960 if (Best->RewriteKind != CRK_None) 14961 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 14962 14963 return R; 14964 } else { 14965 // We matched a built-in operator. Convert the arguments, then 14966 // break out so that we will build the appropriate built-in 14967 // operator node. 14968 ExprResult ArgsRes0 = PerformImplicitConversion( 14969 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14970 AssignmentAction::Passing, 14971 CheckedConversionKind::ForBuiltinOverloadedOp); 14972 if (ArgsRes0.isInvalid()) 14973 return ExprError(); 14974 Args[0] = ArgsRes0.get(); 14975 14976 ExprResult ArgsRes1 = PerformImplicitConversion( 14977 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14978 AssignmentAction::Passing, 14979 CheckedConversionKind::ForBuiltinOverloadedOp); 14980 if (ArgsRes1.isInvalid()) 14981 return ExprError(); 14982 Args[1] = ArgsRes1.get(); 14983 break; 14984 } 14985 } 14986 14987 case OR_No_Viable_Function: { 14988 // C++ [over.match.oper]p9: 14989 // If the operator is the operator , [...] and there are no 14990 // viable functions, then the operator is assumed to be the 14991 // built-in operator and interpreted according to clause 5. 14992 if (Opc == BO_Comma) 14993 break; 14994 14995 // When defaulting an 'operator<=>', we can try to synthesize a three-way 14996 // compare result using '==' and '<'. 14997 if (DefaultedFn && Opc == BO_Cmp) { 14998 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 14999 Args[1], DefaultedFn); 15000 if (E.isInvalid() || E.isUsable()) 15001 return E; 15002 } 15003 15004 // For class as left operand for assignment or compound assignment 15005 // operator do not fall through to handling in built-in, but report that 15006 // no overloaded assignment operator found 15007 ExprResult Result = ExprError(); 15008 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 15009 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 15010 Args, OpLoc); 15011 DeferDiagsRAII DDR(*this, 15012 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 15013 if (Args[0]->getType()->isRecordType() && 15014 Opc >= BO_Assign && Opc <= BO_OrAssign) { 15015 Diag(OpLoc, diag::err_ovl_no_viable_oper) 15016 << BinaryOperator::getOpcodeStr(Opc) 15017 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 15018 if (Args[0]->getType()->isIncompleteType()) { 15019 Diag(OpLoc, diag::note_assign_lhs_incomplete) 15020 << Args[0]->getType() 15021 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 15022 } 15023 } else { 15024 // This is an erroneous use of an operator which can be overloaded by 15025 // a non-member function. Check for non-member operators which were 15026 // defined too late to be candidates. 15027 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 15028 // FIXME: Recover by calling the found function. 15029 return ExprError(); 15030 15031 // No viable function; try to create a built-in operation, which will 15032 // produce an error. Then, show the non-viable candidates. 15033 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 15034 } 15035 assert(Result.isInvalid() && 15036 "C++ binary operator overloading is missing candidates!"); 15037 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 15038 return Result; 15039 } 15040 15041 case OR_Ambiguous: 15042 CandidateSet.NoteCandidates( 15043 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 15044 << BinaryOperator::getOpcodeStr(Opc) 15045 << Args[0]->getType() 15046 << Args[1]->getType() 15047 << Args[0]->getSourceRange() 15048 << Args[1]->getSourceRange()), 15049 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 15050 OpLoc); 15051 return ExprError(); 15052 15053 case OR_Deleted: { 15054 if (isImplicitlyDeleted(Best->Function)) { 15055 FunctionDecl *DeletedFD = Best->Function; 15056 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 15057 if (DFK.isSpecialMember()) { 15058 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 15059 << Args[0]->getType() 15060 << llvm::to_underlying(DFK.asSpecialMember()); 15061 } else { 15062 assert(DFK.isComparison()); 15063 Diag(OpLoc, diag::err_ovl_deleted_comparison) 15064 << Args[0]->getType() << DeletedFD; 15065 } 15066 15067 // The user probably meant to call this special member. Just 15068 // explain why it's deleted. 15069 NoteDeletedFunction(DeletedFD); 15070 return ExprError(); 15071 } 15072 15073 StringLiteral *Msg = Best->Function->getDeletedMessage(); 15074 CandidateSet.NoteCandidates( 15075 PartialDiagnosticAt( 15076 OpLoc, 15077 PDiag(diag::err_ovl_deleted_oper) 15078 << getOperatorSpelling(Best->Function->getDeclName() 15079 .getCXXOverloadedOperator()) 15080 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()) 15081 << Args[0]->getSourceRange() << Args[1]->getSourceRange()), 15082 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 15083 OpLoc); 15084 return ExprError(); 15085 } 15086 } 15087 15088 // We matched a built-in operator; build it. 15089 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 15090 } 15091 15092 ExprResult Sema::BuildSynthesizedThreeWayComparison( 15093 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 15094 FunctionDecl *DefaultedFn) { 15095 const ComparisonCategoryInfo *Info = 15096 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 15097 // If we're not producing a known comparison category type, we can't 15098 // synthesize a three-way comparison. Let the caller diagnose this. 15099 if (!Info) 15100 return ExprResult((Expr*)nullptr); 15101 15102 // If we ever want to perform this synthesis more generally, we will need to 15103 // apply the temporary materialization conversion to the operands. 15104 assert(LHS->isGLValue() && RHS->isGLValue() && 15105 "cannot use prvalue expressions more than once"); 15106 Expr *OrigLHS = LHS; 15107 Expr *OrigRHS = RHS; 15108 15109 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 15110 // each of them multiple times below. 15111 LHS = new (Context) 15112 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 15113 LHS->getObjectKind(), LHS); 15114 RHS = new (Context) 15115 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 15116 RHS->getObjectKind(), RHS); 15117 15118 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 15119 DefaultedFn); 15120 if (Eq.isInvalid()) 15121 return ExprError(); 15122 15123 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 15124 true, DefaultedFn); 15125 if (Less.isInvalid()) 15126 return ExprError(); 15127 15128 ExprResult Greater; 15129 if (Info->isPartial()) { 15130 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 15131 DefaultedFn); 15132 if (Greater.isInvalid()) 15133 return ExprError(); 15134 } 15135 15136 // Form the list of comparisons we're going to perform. 15137 struct Comparison { 15138 ExprResult Cmp; 15139 ComparisonCategoryResult Result; 15140 } Comparisons[4] = 15141 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 15142 : ComparisonCategoryResult::Equivalent}, 15143 {Less, ComparisonCategoryResult::Less}, 15144 {Greater, ComparisonCategoryResult::Greater}, 15145 {ExprResult(), ComparisonCategoryResult::Unordered}, 15146 }; 15147 15148 int I = Info->isPartial() ? 3 : 2; 15149 15150 // Combine the comparisons with suitable conditional expressions. 15151 ExprResult Result; 15152 for (; I >= 0; --I) { 15153 // Build a reference to the comparison category constant. 15154 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 15155 // FIXME: Missing a constant for a comparison category. Diagnose this? 15156 if (!VI) 15157 return ExprResult((Expr*)nullptr); 15158 ExprResult ThisResult = 15159 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 15160 if (ThisResult.isInvalid()) 15161 return ExprError(); 15162 15163 // Build a conditional unless this is the final case. 15164 if (Result.get()) { 15165 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 15166 ThisResult.get(), Result.get()); 15167 if (Result.isInvalid()) 15168 return ExprError(); 15169 } else { 15170 Result = ThisResult; 15171 } 15172 } 15173 15174 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 15175 // bind the OpaqueValueExprs before they're (repeatedly) used. 15176 Expr *SyntacticForm = BinaryOperator::Create( 15177 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 15178 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 15179 CurFPFeatureOverrides()); 15180 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 15181 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 15182 } 15183 15184 static bool PrepareArgumentsForCallToObjectOfClassType( 15185 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, 15186 MultiExprArg Args, SourceLocation LParenLoc) { 15187 15188 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 15189 unsigned NumParams = Proto->getNumParams(); 15190 unsigned NumArgsSlots = 15191 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); 15192 // Build the full argument list for the method call (the implicit object 15193 // parameter is placed at the beginning of the list). 15194 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); 15195 bool IsError = false; 15196 // Initialize the implicit object parameter. 15197 // Check the argument types. 15198 for (unsigned i = 0; i != NumParams; i++) { 15199 Expr *Arg; 15200 if (i < Args.size()) { 15201 Arg = Args[i]; 15202 ExprResult InputInit = 15203 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 15204 S.Context, Method->getParamDecl(i)), 15205 SourceLocation(), Arg); 15206 IsError |= InputInit.isInvalid(); 15207 Arg = InputInit.getAs<Expr>(); 15208 } else { 15209 ExprResult DefArg = 15210 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 15211 if (DefArg.isInvalid()) { 15212 IsError = true; 15213 break; 15214 } 15215 Arg = DefArg.getAs<Expr>(); 15216 } 15217 15218 MethodArgs.push_back(Arg); 15219 } 15220 return IsError; 15221 } 15222 15223 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 15224 SourceLocation RLoc, 15225 Expr *Base, 15226 MultiExprArg ArgExpr) { 15227 SmallVector<Expr *, 2> Args; 15228 Args.push_back(Base); 15229 for (auto *e : ArgExpr) { 15230 Args.push_back(e); 15231 } 15232 DeclarationName OpName = 15233 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 15234 15235 SourceRange Range = ArgExpr.empty() 15236 ? SourceRange{} 15237 : SourceRange(ArgExpr.front()->getBeginLoc(), 15238 ArgExpr.back()->getEndLoc()); 15239 15240 // If either side is type-dependent, create an appropriate dependent 15241 // expression. 15242 if (Expr::hasAnyTypeDependentArguments(Args)) { 15243 15244 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 15245 // CHECKME: no 'operator' keyword? 15246 DeclarationNameInfo OpNameInfo(OpName, LLoc); 15247 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 15248 ExprResult Fn = CreateUnresolvedLookupExpr( 15249 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 15250 if (Fn.isInvalid()) 15251 return ExprError(); 15252 // Can't add any actual overloads yet 15253 15254 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 15255 Context.DependentTy, VK_PRValue, RLoc, 15256 CurFPFeatureOverrides()); 15257 } 15258 15259 // Handle placeholders 15260 UnbridgedCastsSet UnbridgedCasts; 15261 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 15262 return ExprError(); 15263 } 15264 // Build an empty overload set. 15265 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 15266 15267 // Subscript can only be overloaded as a member function. 15268 15269 // Add operator candidates that are member functions. 15270 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 15271 15272 // Add builtin operator candidates. 15273 if (Args.size() == 2) 15274 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 15275 15276 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15277 15278 // Perform overload resolution. 15279 OverloadCandidateSet::iterator Best; 15280 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 15281 case OR_Success: { 15282 // We found a built-in operator or an overloaded operator. 15283 FunctionDecl *FnDecl = Best->Function; 15284 15285 if (FnDecl) { 15286 // We matched an overloaded operator. Build a call to that 15287 // operator. 15288 15289 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); 15290 15291 // Convert the arguments. 15292 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 15293 SmallVector<Expr *, 2> MethodArgs; 15294 15295 // Initialize the object parameter. 15296 if (Method->isExplicitObjectMemberFunction()) { 15297 ExprResult Res = 15298 InitializeExplicitObjectArgument(*this, Args[0], Method); 15299 if (Res.isInvalid()) 15300 return ExprError(); 15301 Args[0] = Res.get(); 15302 ArgExpr = Args; 15303 } else { 15304 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization( 15305 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 15306 if (Arg0.isInvalid()) 15307 return ExprError(); 15308 15309 MethodArgs.push_back(Arg0.get()); 15310 } 15311 15312 bool IsError = PrepareArgumentsForCallToObjectOfClassType( 15313 *this, MethodArgs, Method, ArgExpr, LLoc); 15314 if (IsError) 15315 return ExprError(); 15316 15317 // Build the actual expression node. 15318 DeclarationNameInfo OpLocInfo(OpName, LLoc); 15319 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 15320 ExprResult FnExpr = CreateFunctionRefExpr( 15321 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, 15322 OpLocInfo.getLoc(), OpLocInfo.getInfo()); 15323 if (FnExpr.isInvalid()) 15324 return ExprError(); 15325 15326 // Determine the result type 15327 QualType ResultTy = FnDecl->getReturnType(); 15328 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15329 ResultTy = ResultTy.getNonLValueExprType(Context); 15330 15331 CallExpr *TheCall = CXXOperatorCallExpr::Create( 15332 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc, 15333 CurFPFeatureOverrides()); 15334 15335 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 15336 return ExprError(); 15337 15338 if (CheckFunctionCall(Method, TheCall, 15339 Method->getType()->castAs<FunctionProtoType>())) 15340 return ExprError(); 15341 15342 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 15343 FnDecl); 15344 } else { 15345 // We matched a built-in operator. Convert the arguments, then 15346 // break out so that we will build the appropriate built-in 15347 // operator node. 15348 ExprResult ArgsRes0 = PerformImplicitConversion( 15349 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 15350 AssignmentAction::Passing, 15351 CheckedConversionKind::ForBuiltinOverloadedOp); 15352 if (ArgsRes0.isInvalid()) 15353 return ExprError(); 15354 Args[0] = ArgsRes0.get(); 15355 15356 ExprResult ArgsRes1 = PerformImplicitConversion( 15357 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 15358 AssignmentAction::Passing, 15359 CheckedConversionKind::ForBuiltinOverloadedOp); 15360 if (ArgsRes1.isInvalid()) 15361 return ExprError(); 15362 Args[1] = ArgsRes1.get(); 15363 15364 break; 15365 } 15366 } 15367 15368 case OR_No_Viable_Function: { 15369 PartialDiagnostic PD = 15370 CandidateSet.empty() 15371 ? (PDiag(diag::err_ovl_no_oper) 15372 << Args[0]->getType() << /*subscript*/ 0 15373 << Args[0]->getSourceRange() << Range) 15374 : (PDiag(diag::err_ovl_no_viable_subscript) 15375 << Args[0]->getType() << Args[0]->getSourceRange() << Range); 15376 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 15377 OCD_AllCandidates, ArgExpr, "[]", LLoc); 15378 return ExprError(); 15379 } 15380 15381 case OR_Ambiguous: 15382 if (Args.size() == 2) { 15383 CandidateSet.NoteCandidates( 15384 PartialDiagnosticAt( 15385 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 15386 << "[]" << Args[0]->getType() << Args[1]->getType() 15387 << Args[0]->getSourceRange() << Range), 15388 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 15389 } else { 15390 CandidateSet.NoteCandidates( 15391 PartialDiagnosticAt(LLoc, 15392 PDiag(diag::err_ovl_ambiguous_subscript_call) 15393 << Args[0]->getType() 15394 << Args[0]->getSourceRange() << Range), 15395 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 15396 } 15397 return ExprError(); 15398 15399 case OR_Deleted: { 15400 StringLiteral *Msg = Best->Function->getDeletedMessage(); 15401 CandidateSet.NoteCandidates( 15402 PartialDiagnosticAt(LLoc, 15403 PDiag(diag::err_ovl_deleted_oper) 15404 << "[]" << (Msg != nullptr) 15405 << (Msg ? Msg->getString() : StringRef()) 15406 << Args[0]->getSourceRange() << Range), 15407 *this, OCD_AllCandidates, Args, "[]", LLoc); 15408 return ExprError(); 15409 } 15410 } 15411 15412 // We matched a built-in operator; build it. 15413 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 15414 } 15415 15416 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 15417 SourceLocation LParenLoc, 15418 MultiExprArg Args, 15419 SourceLocation RParenLoc, 15420 Expr *ExecConfig, bool IsExecConfig, 15421 bool AllowRecovery) { 15422 assert(MemExprE->getType() == Context.BoundMemberTy || 15423 MemExprE->getType() == Context.OverloadTy); 15424 15425 // Dig out the member expression. This holds both the object 15426 // argument and the member function we're referring to. 15427 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 15428 15429 // Determine whether this is a call to a pointer-to-member function. 15430 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 15431 assert(op->getType() == Context.BoundMemberTy); 15432 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 15433 15434 QualType fnType = 15435 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 15436 15437 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 15438 QualType resultType = proto->getCallResultType(Context); 15439 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 15440 15441 // Check that the object type isn't more qualified than the 15442 // member function we're calling. 15443 Qualifiers funcQuals = proto->getMethodQuals(); 15444 15445 QualType objectType = op->getLHS()->getType(); 15446 if (op->getOpcode() == BO_PtrMemI) 15447 objectType = objectType->castAs<PointerType>()->getPointeeType(); 15448 Qualifiers objectQuals = objectType.getQualifiers(); 15449 15450 Qualifiers difference = objectQuals - funcQuals; 15451 difference.removeObjCGCAttr(); 15452 difference.removeAddressSpace(); 15453 if (difference) { 15454 std::string qualsString = difference.getAsString(); 15455 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 15456 << fnType.getUnqualifiedType() 15457 << qualsString 15458 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 15459 } 15460 15461 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 15462 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 15463 CurFPFeatureOverrides(), proto->getNumParams()); 15464 15465 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 15466 call, nullptr)) 15467 return ExprError(); 15468 15469 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 15470 return ExprError(); 15471 15472 if (CheckOtherCall(call, proto)) 15473 return ExprError(); 15474 15475 return MaybeBindToTemporary(call); 15476 } 15477 15478 // We only try to build a recovery expr at this level if we can preserve 15479 // the return type, otherwise we return ExprError() and let the caller 15480 // recover. 15481 auto BuildRecoveryExpr = [&](QualType Type) { 15482 if (!AllowRecovery) 15483 return ExprError(); 15484 std::vector<Expr *> SubExprs = {MemExprE}; 15485 llvm::append_range(SubExprs, Args); 15486 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 15487 Type); 15488 }; 15489 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 15490 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 15491 RParenLoc, CurFPFeatureOverrides()); 15492 15493 UnbridgedCastsSet UnbridgedCasts; 15494 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 15495 return ExprError(); 15496 15497 MemberExpr *MemExpr; 15498 CXXMethodDecl *Method = nullptr; 15499 bool HadMultipleCandidates = false; 15500 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 15501 NestedNameSpecifier *Qualifier = nullptr; 15502 if (isa<MemberExpr>(NakedMemExpr)) { 15503 MemExpr = cast<MemberExpr>(NakedMemExpr); 15504 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 15505 FoundDecl = MemExpr->getFoundDecl(); 15506 Qualifier = MemExpr->getQualifier(); 15507 UnbridgedCasts.restore(); 15508 } else { 15509 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 15510 Qualifier = UnresExpr->getQualifier(); 15511 15512 QualType ObjectType = UnresExpr->getBaseType(); 15513 Expr::Classification ObjectClassification 15514 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 15515 : UnresExpr->getBase()->Classify(Context); 15516 15517 // Add overload candidates 15518 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 15519 OverloadCandidateSet::CSK_Normal); 15520 15521 // FIXME: avoid copy. 15522 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15523 if (UnresExpr->hasExplicitTemplateArgs()) { 15524 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15525 TemplateArgs = &TemplateArgsBuffer; 15526 } 15527 15528 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 15529 E = UnresExpr->decls_end(); I != E; ++I) { 15530 15531 QualType ExplicitObjectType = ObjectType; 15532 15533 NamedDecl *Func = *I; 15534 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 15535 if (isa<UsingShadowDecl>(Func)) 15536 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 15537 15538 bool HasExplicitParameter = false; 15539 if (const auto *M = dyn_cast<FunctionDecl>(Func); 15540 M && M->hasCXXExplicitFunctionObjectParameter()) 15541 HasExplicitParameter = true; 15542 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func); 15543 M && 15544 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter()) 15545 HasExplicitParameter = true; 15546 15547 if (HasExplicitParameter) 15548 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr); 15549 15550 // Microsoft supports direct constructor calls. 15551 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 15552 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 15553 CandidateSet, 15554 /*SuppressUserConversions*/ false); 15555 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 15556 // If explicit template arguments were provided, we can't call a 15557 // non-template member function. 15558 if (TemplateArgs) 15559 continue; 15560 15561 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType, 15562 ObjectClassification, Args, CandidateSet, 15563 /*SuppressUserConversions=*/false); 15564 } else { 15565 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 15566 I.getPair(), ActingDC, TemplateArgs, 15567 ExplicitObjectType, ObjectClassification, 15568 Args, CandidateSet, 15569 /*SuppressUserConversions=*/false); 15570 } 15571 } 15572 15573 HadMultipleCandidates = (CandidateSet.size() > 1); 15574 15575 DeclarationName DeclName = UnresExpr->getMemberName(); 15576 15577 UnbridgedCasts.restore(); 15578 15579 OverloadCandidateSet::iterator Best; 15580 bool Succeeded = false; 15581 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 15582 Best)) { 15583 case OR_Success: 15584 Method = cast<CXXMethodDecl>(Best->Function); 15585 FoundDecl = Best->FoundDecl; 15586 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 15587 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 15588 break; 15589 // If FoundDecl is different from Method (such as if one is a template 15590 // and the other a specialization), make sure DiagnoseUseOfDecl is 15591 // called on both. 15592 // FIXME: This would be more comprehensively addressed by modifying 15593 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 15594 // being used. 15595 if (Method != FoundDecl.getDecl() && 15596 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc())) 15597 break; 15598 Succeeded = true; 15599 break; 15600 15601 case OR_No_Viable_Function: 15602 CandidateSet.NoteCandidates( 15603 PartialDiagnosticAt( 15604 UnresExpr->getMemberLoc(), 15605 PDiag(diag::err_ovl_no_viable_member_function_in_call) 15606 << DeclName << MemExprE->getSourceRange()), 15607 *this, OCD_AllCandidates, Args); 15608 break; 15609 case OR_Ambiguous: 15610 CandidateSet.NoteCandidates( 15611 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 15612 PDiag(diag::err_ovl_ambiguous_member_call) 15613 << DeclName << MemExprE->getSourceRange()), 15614 *this, OCD_AmbiguousCandidates, Args); 15615 break; 15616 case OR_Deleted: 15617 DiagnoseUseOfDeletedFunction( 15618 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName, 15619 CandidateSet, Best->Function, Args, /*IsMember=*/true); 15620 break; 15621 } 15622 // Overload resolution fails, try to recover. 15623 if (!Succeeded) 15624 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 15625 15626 ExprResult Res = 15627 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 15628 if (Res.isInvalid()) 15629 return ExprError(); 15630 MemExprE = Res.get(); 15631 15632 // If overload resolution picked a static member 15633 // build a non-member call based on that function. 15634 if (Method->isStatic()) { 15635 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, 15636 ExecConfig, IsExecConfig); 15637 } 15638 15639 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 15640 } 15641 15642 QualType ResultType = Method->getReturnType(); 15643 ExprValueKind VK = Expr::getValueKindForType(ResultType); 15644 ResultType = ResultType.getNonLValueExprType(Context); 15645 15646 assert(Method && "Member call to something that isn't a method?"); 15647 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 15648 15649 CallExpr *TheCall = nullptr; 15650 llvm::SmallVector<Expr *, 8> NewArgs; 15651 if (Method->isExplicitObjectMemberFunction()) { 15652 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args, 15653 NewArgs)) 15654 return ExprError(); 15655 15656 // Build the actual expression node. 15657 ExprResult FnExpr = 15658 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr, 15659 HadMultipleCandidates, MemExpr->getExprLoc()); 15660 if (FnExpr.isInvalid()) 15661 return ExprError(); 15662 15663 TheCall = 15664 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc, 15665 CurFPFeatureOverrides(), Proto->getNumParams()); 15666 } else { 15667 // Convert the object argument (for a non-static member function call). 15668 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization( 15669 MemExpr->getBase(), Qualifier, FoundDecl, Method); 15670 if (ObjectArg.isInvalid()) 15671 return ExprError(); 15672 MemExpr->setBase(ObjectArg.get()); 15673 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 15674 RParenLoc, CurFPFeatureOverrides(), 15675 Proto->getNumParams()); 15676 } 15677 15678 // Check for a valid return type. 15679 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 15680 TheCall, Method)) 15681 return BuildRecoveryExpr(ResultType); 15682 15683 // Convert the rest of the arguments 15684 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 15685 RParenLoc)) 15686 return BuildRecoveryExpr(ResultType); 15687 15688 DiagnoseSentinelCalls(Method, LParenLoc, Args); 15689 15690 if (CheckFunctionCall(Method, TheCall, Proto)) 15691 return ExprError(); 15692 15693 // In the case the method to call was not selected by the overloading 15694 // resolution process, we still need to handle the enable_if attribute. Do 15695 // that here, so it will not hide previous -- and more relevant -- errors. 15696 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 15697 if (const EnableIfAttr *Attr = 15698 CheckEnableIf(Method, LParenLoc, Args, true)) { 15699 Diag(MemE->getMemberLoc(), 15700 diag::err_ovl_no_viable_member_function_in_call) 15701 << Method << Method->getSourceRange(); 15702 Diag(Method->getLocation(), 15703 diag::note_ovl_candidate_disabled_by_function_cond_attr) 15704 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 15705 return ExprError(); 15706 } 15707 } 15708 15709 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) && 15710 TheCall->getDirectCallee()->isPureVirtual()) { 15711 const FunctionDecl *MD = TheCall->getDirectCallee(); 15712 15713 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 15714 MemExpr->performsVirtualDispatch(getLangOpts())) { 15715 Diag(MemExpr->getBeginLoc(), 15716 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 15717 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 15718 << MD->getParent(); 15719 15720 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 15721 if (getLangOpts().AppleKext) 15722 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 15723 << MD->getParent() << MD->getDeclName(); 15724 } 15725 } 15726 15727 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) { 15728 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 15729 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 15730 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 15731 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 15732 MemExpr->getMemberLoc()); 15733 } 15734 15735 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 15736 TheCall->getDirectCallee()); 15737 } 15738 15739 ExprResult 15740 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 15741 SourceLocation LParenLoc, 15742 MultiExprArg Args, 15743 SourceLocation RParenLoc) { 15744 if (checkPlaceholderForOverload(*this, Obj)) 15745 return ExprError(); 15746 ExprResult Object = Obj; 15747 15748 UnbridgedCastsSet UnbridgedCasts; 15749 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 15750 return ExprError(); 15751 15752 assert(Object.get()->getType()->isRecordType() && 15753 "Requires object type argument"); 15754 15755 // C++ [over.call.object]p1: 15756 // If the primary-expression E in the function call syntax 15757 // evaluates to a class object of type "cv T", then the set of 15758 // candidate functions includes at least the function call 15759 // operators of T. The function call operators of T are obtained by 15760 // ordinary lookup of the name operator() in the context of 15761 // (E).operator(). 15762 OverloadCandidateSet CandidateSet(LParenLoc, 15763 OverloadCandidateSet::CSK_Operator); 15764 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 15765 15766 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 15767 diag::err_incomplete_object_call, Object.get())) 15768 return true; 15769 15770 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 15771 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 15772 LookupQualifiedName(R, Record->getDecl()); 15773 R.suppressAccessDiagnostics(); 15774 15775 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 15776 Oper != OperEnd; ++Oper) { 15777 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 15778 Object.get()->Classify(Context), Args, CandidateSet, 15779 /*SuppressUserConversion=*/false); 15780 } 15781 15782 // When calling a lambda, both the call operator, and 15783 // the conversion operator to function pointer 15784 // are considered. But when constraint checking 15785 // on the call operator fails, it will also fail on the 15786 // conversion operator as the constraints are always the same. 15787 // As the user probably does not intend to perform a surrogate call, 15788 // we filter them out to produce better error diagnostics, ie to avoid 15789 // showing 2 failed overloads instead of one. 15790 bool IgnoreSurrogateFunctions = false; 15791 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) { 15792 const OverloadCandidate &Candidate = *CandidateSet.begin(); 15793 if (!Candidate.Viable && 15794 Candidate.FailureKind == ovl_fail_constraints_not_satisfied) 15795 IgnoreSurrogateFunctions = true; 15796 } 15797 15798 // C++ [over.call.object]p2: 15799 // In addition, for each (non-explicit in C++0x) conversion function 15800 // declared in T of the form 15801 // 15802 // operator conversion-type-id () cv-qualifier; 15803 // 15804 // where cv-qualifier is the same cv-qualification as, or a 15805 // greater cv-qualification than, cv, and where conversion-type-id 15806 // denotes the type "pointer to function of (P1,...,Pn) returning 15807 // R", or the type "reference to pointer to function of 15808 // (P1,...,Pn) returning R", or the type "reference to function 15809 // of (P1,...,Pn) returning R", a surrogate call function [...] 15810 // is also considered as a candidate function. Similarly, 15811 // surrogate call functions are added to the set of candidate 15812 // functions for each conversion function declared in an 15813 // accessible base class provided the function is not hidden 15814 // within T by another intervening declaration. 15815 const auto &Conversions = 15816 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 15817 for (auto I = Conversions.begin(), E = Conversions.end(); 15818 !IgnoreSurrogateFunctions && I != E; ++I) { 15819 NamedDecl *D = *I; 15820 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 15821 if (isa<UsingShadowDecl>(D)) 15822 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 15823 15824 // Skip over templated conversion functions; they aren't 15825 // surrogates. 15826 if (isa<FunctionTemplateDecl>(D)) 15827 continue; 15828 15829 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 15830 if (!Conv->isExplicit()) { 15831 // Strip the reference type (if any) and then the pointer type (if 15832 // any) to get down to what might be a function type. 15833 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 15834 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 15835 ConvType = ConvPtrType->getPointeeType(); 15836 15837 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 15838 { 15839 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 15840 Object.get(), Args, CandidateSet); 15841 } 15842 } 15843 } 15844 15845 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15846 15847 // Perform overload resolution. 15848 OverloadCandidateSet::iterator Best; 15849 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 15850 Best)) { 15851 case OR_Success: 15852 // Overload resolution succeeded; we'll build the appropriate call 15853 // below. 15854 break; 15855 15856 case OR_No_Viable_Function: { 15857 PartialDiagnostic PD = 15858 CandidateSet.empty() 15859 ? (PDiag(diag::err_ovl_no_oper) 15860 << Object.get()->getType() << /*call*/ 1 15861 << Object.get()->getSourceRange()) 15862 : (PDiag(diag::err_ovl_no_viable_object_call) 15863 << Object.get()->getType() << Object.get()->getSourceRange()); 15864 CandidateSet.NoteCandidates( 15865 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 15866 OCD_AllCandidates, Args); 15867 break; 15868 } 15869 case OR_Ambiguous: 15870 if (!R.isAmbiguous()) 15871 CandidateSet.NoteCandidates( 15872 PartialDiagnosticAt(Object.get()->getBeginLoc(), 15873 PDiag(diag::err_ovl_ambiguous_object_call) 15874 << Object.get()->getType() 15875 << Object.get()->getSourceRange()), 15876 *this, OCD_AmbiguousCandidates, Args); 15877 break; 15878 15879 case OR_Deleted: { 15880 // FIXME: Is this diagnostic here really necessary? It seems that 15881 // 1. we don't have any tests for this diagnostic, and 15882 // 2. we already issue err_deleted_function_use for this later on anyway. 15883 StringLiteral *Msg = Best->Function->getDeletedMessage(); 15884 CandidateSet.NoteCandidates( 15885 PartialDiagnosticAt(Object.get()->getBeginLoc(), 15886 PDiag(diag::err_ovl_deleted_object_call) 15887 << Object.get()->getType() << (Msg != nullptr) 15888 << (Msg ? Msg->getString() : StringRef()) 15889 << Object.get()->getSourceRange()), 15890 *this, OCD_AllCandidates, Args); 15891 break; 15892 } 15893 } 15894 15895 if (Best == CandidateSet.end()) 15896 return true; 15897 15898 UnbridgedCasts.restore(); 15899 15900 if (Best->Function == nullptr) { 15901 // Since there is no function declaration, this is one of the 15902 // surrogate candidates. Dig out the conversion function. 15903 CXXConversionDecl *Conv 15904 = cast<CXXConversionDecl>( 15905 Best->Conversions[0].UserDefined.ConversionFunction); 15906 15907 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 15908 Best->FoundDecl); 15909 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 15910 return ExprError(); 15911 assert(Conv == Best->FoundDecl.getDecl() && 15912 "Found Decl & conversion-to-functionptr should be same, right?!"); 15913 // We selected one of the surrogate functions that converts the 15914 // object parameter to a function pointer. Perform the conversion 15915 // on the object argument, then let BuildCallExpr finish the job. 15916 15917 // Create an implicit member expr to refer to the conversion operator. 15918 // and then call it. 15919 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 15920 Conv, HadMultipleCandidates); 15921 if (Call.isInvalid()) 15922 return ExprError(); 15923 // Record usage of conversion in an implicit cast. 15924 Call = ImplicitCastExpr::Create( 15925 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 15926 nullptr, VK_PRValue, CurFPFeatureOverrides()); 15927 15928 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 15929 } 15930 15931 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 15932 15933 // We found an overloaded operator(). Build a CXXOperatorCallExpr 15934 // that calls this method, using Object for the implicit object 15935 // parameter and passing along the remaining arguments. 15936 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 15937 15938 // An error diagnostic has already been printed when parsing the declaration. 15939 if (Method->isInvalidDecl()) 15940 return ExprError(); 15941 15942 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 15943 unsigned NumParams = Proto->getNumParams(); 15944 15945 DeclarationNameInfo OpLocInfo( 15946 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 15947 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 15948 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 15949 Obj, HadMultipleCandidates, 15950 OpLocInfo.getLoc(), 15951 OpLocInfo.getInfo()); 15952 if (NewFn.isInvalid()) 15953 return true; 15954 15955 SmallVector<Expr *, 8> MethodArgs; 15956 MethodArgs.reserve(NumParams + 1); 15957 15958 bool IsError = false; 15959 15960 // Initialize the object parameter. 15961 llvm::SmallVector<Expr *, 8> NewArgs; 15962 if (Method->isExplicitObjectMemberFunction()) { 15963 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs); 15964 } else { 15965 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization( 15966 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method); 15967 if (ObjRes.isInvalid()) 15968 IsError = true; 15969 else 15970 Object = ObjRes; 15971 MethodArgs.push_back(Object.get()); 15972 } 15973 15974 IsError |= PrepareArgumentsForCallToObjectOfClassType( 15975 *this, MethodArgs, Method, Args, LParenLoc); 15976 15977 // If this is a variadic call, handle args passed through "...". 15978 if (Proto->isVariadic()) { 15979 // Promote the arguments (C99 6.5.2.2p7). 15980 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 15981 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 15982 nullptr); 15983 IsError |= Arg.isInvalid(); 15984 MethodArgs.push_back(Arg.get()); 15985 } 15986 } 15987 15988 if (IsError) 15989 return true; 15990 15991 DiagnoseSentinelCalls(Method, LParenLoc, Args); 15992 15993 // Once we've built TheCall, all of the expressions are properly owned. 15994 QualType ResultTy = Method->getReturnType(); 15995 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15996 ResultTy = ResultTy.getNonLValueExprType(Context); 15997 15998 CallExpr *TheCall = CXXOperatorCallExpr::Create( 15999 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 16000 CurFPFeatureOverrides()); 16001 16002 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 16003 return true; 16004 16005 if (CheckFunctionCall(Method, TheCall, Proto)) 16006 return true; 16007 16008 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 16009 } 16010 16011 ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, 16012 SourceLocation OpLoc, 16013 bool *NoArrowOperatorFound) { 16014 assert(Base->getType()->isRecordType() && 16015 "left-hand side must have class type"); 16016 16017 if (checkPlaceholderForOverload(*this, Base)) 16018 return ExprError(); 16019 16020 SourceLocation Loc = Base->getExprLoc(); 16021 16022 // C++ [over.ref]p1: 16023 // 16024 // [...] An expression x->m is interpreted as (x.operator->())->m 16025 // for a class object x of type T if T::operator->() exists and if 16026 // the operator is selected as the best match function by the 16027 // overload resolution mechanism (13.3). 16028 DeclarationName OpName = 16029 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 16030 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 16031 16032 if (RequireCompleteType(Loc, Base->getType(), 16033 diag::err_typecheck_incomplete_tag, Base)) 16034 return ExprError(); 16035 16036 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 16037 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 16038 R.suppressAccessDiagnostics(); 16039 16040 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 16041 Oper != OperEnd; ++Oper) { 16042 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 16043 {}, CandidateSet, 16044 /*SuppressUserConversion=*/false); 16045 } 16046 16047 bool HadMultipleCandidates = (CandidateSet.size() > 1); 16048 16049 // Perform overload resolution. 16050 OverloadCandidateSet::iterator Best; 16051 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 16052 case OR_Success: 16053 // Overload resolution succeeded; we'll build the call below. 16054 break; 16055 16056 case OR_No_Viable_Function: { 16057 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 16058 if (CandidateSet.empty()) { 16059 QualType BaseType = Base->getType(); 16060 if (NoArrowOperatorFound) { 16061 // Report this specific error to the caller instead of emitting a 16062 // diagnostic, as requested. 16063 *NoArrowOperatorFound = true; 16064 return ExprError(); 16065 } 16066 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 16067 << BaseType << Base->getSourceRange(); 16068 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 16069 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 16070 << FixItHint::CreateReplacement(OpLoc, "."); 16071 } 16072 } else 16073 Diag(OpLoc, diag::err_ovl_no_viable_oper) 16074 << "operator->" << Base->getSourceRange(); 16075 CandidateSet.NoteCandidates(*this, Base, Cands); 16076 return ExprError(); 16077 } 16078 case OR_Ambiguous: 16079 if (!R.isAmbiguous()) 16080 CandidateSet.NoteCandidates( 16081 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 16082 << "->" << Base->getType() 16083 << Base->getSourceRange()), 16084 *this, OCD_AmbiguousCandidates, Base); 16085 return ExprError(); 16086 16087 case OR_Deleted: { 16088 StringLiteral *Msg = Best->Function->getDeletedMessage(); 16089 CandidateSet.NoteCandidates( 16090 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 16091 << "->" << (Msg != nullptr) 16092 << (Msg ? Msg->getString() : StringRef()) 16093 << Base->getSourceRange()), 16094 *this, OCD_AllCandidates, Base); 16095 return ExprError(); 16096 } 16097 } 16098 16099 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 16100 16101 // Convert the object parameter. 16102 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 16103 16104 if (Method->isExplicitObjectMemberFunction()) { 16105 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method); 16106 if (R.isInvalid()) 16107 return ExprError(); 16108 Base = R.get(); 16109 } else { 16110 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization( 16111 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method); 16112 if (BaseResult.isInvalid()) 16113 return ExprError(); 16114 Base = BaseResult.get(); 16115 } 16116 16117 // Build the operator call. 16118 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 16119 Base, HadMultipleCandidates, OpLoc); 16120 if (FnExpr.isInvalid()) 16121 return ExprError(); 16122 16123 QualType ResultTy = Method->getReturnType(); 16124 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 16125 ResultTy = ResultTy.getNonLValueExprType(Context); 16126 16127 CallExpr *TheCall = 16128 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 16129 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 16130 16131 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 16132 return ExprError(); 16133 16134 if (CheckFunctionCall(Method, TheCall, 16135 Method->getType()->castAs<FunctionProtoType>())) 16136 return ExprError(); 16137 16138 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 16139 } 16140 16141 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 16142 DeclarationNameInfo &SuffixInfo, 16143 ArrayRef<Expr*> Args, 16144 SourceLocation LitEndLoc, 16145 TemplateArgumentListInfo *TemplateArgs) { 16146 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 16147 16148 OverloadCandidateSet CandidateSet(UDSuffixLoc, 16149 OverloadCandidateSet::CSK_Normal); 16150 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 16151 TemplateArgs); 16152 16153 bool HadMultipleCandidates = (CandidateSet.size() > 1); 16154 16155 // Perform overload resolution. This will usually be trivial, but might need 16156 // to perform substitutions for a literal operator template. 16157 OverloadCandidateSet::iterator Best; 16158 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 16159 case OR_Success: 16160 case OR_Deleted: 16161 break; 16162 16163 case OR_No_Viable_Function: 16164 CandidateSet.NoteCandidates( 16165 PartialDiagnosticAt(UDSuffixLoc, 16166 PDiag(diag::err_ovl_no_viable_function_in_call) 16167 << R.getLookupName()), 16168 *this, OCD_AllCandidates, Args); 16169 return ExprError(); 16170 16171 case OR_Ambiguous: 16172 CandidateSet.NoteCandidates( 16173 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 16174 << R.getLookupName()), 16175 *this, OCD_AmbiguousCandidates, Args); 16176 return ExprError(); 16177 } 16178 16179 FunctionDecl *FD = Best->Function; 16180 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 16181 nullptr, HadMultipleCandidates, 16182 SuffixInfo.getLoc(), 16183 SuffixInfo.getInfo()); 16184 if (Fn.isInvalid()) 16185 return true; 16186 16187 // Check the argument types. This should almost always be a no-op, except 16188 // that array-to-pointer decay is applied to string literals. 16189 Expr *ConvArgs[2]; 16190 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 16191 ExprResult InputInit = PerformCopyInitialization( 16192 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 16193 SourceLocation(), Args[ArgIdx]); 16194 if (InputInit.isInvalid()) 16195 return true; 16196 ConvArgs[ArgIdx] = InputInit.get(); 16197 } 16198 16199 QualType ResultTy = FD->getReturnType(); 16200 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 16201 ResultTy = ResultTy.getNonLValueExprType(Context); 16202 16203 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 16204 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK, 16205 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 16206 16207 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 16208 return ExprError(); 16209 16210 if (CheckFunctionCall(FD, UDL, nullptr)) 16211 return ExprError(); 16212 16213 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 16214 } 16215 16216 Sema::ForRangeStatus 16217 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 16218 SourceLocation RangeLoc, 16219 const DeclarationNameInfo &NameInfo, 16220 LookupResult &MemberLookup, 16221 OverloadCandidateSet *CandidateSet, 16222 Expr *Range, ExprResult *CallExpr) { 16223 Scope *S = nullptr; 16224 16225 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 16226 if (!MemberLookup.empty()) { 16227 ExprResult MemberRef = 16228 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 16229 /*IsPtr=*/false, CXXScopeSpec(), 16230 /*TemplateKWLoc=*/SourceLocation(), 16231 /*FirstQualifierInScope=*/nullptr, 16232 MemberLookup, 16233 /*TemplateArgs=*/nullptr, S); 16234 if (MemberRef.isInvalid()) { 16235 *CallExpr = ExprError(); 16236 return FRS_DiagnosticIssued; 16237 } 16238 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr); 16239 if (CallExpr->isInvalid()) { 16240 *CallExpr = ExprError(); 16241 return FRS_DiagnosticIssued; 16242 } 16243 } else { 16244 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 16245 NestedNameSpecifierLoc(), 16246 NameInfo, UnresolvedSet<0>()); 16247 if (FnR.isInvalid()) 16248 return FRS_DiagnosticIssued; 16249 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 16250 16251 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 16252 CandidateSet, CallExpr); 16253 if (CandidateSet->empty() || CandidateSetError) { 16254 *CallExpr = ExprError(); 16255 return FRS_NoViableFunction; 16256 } 16257 OverloadCandidateSet::iterator Best; 16258 OverloadingResult OverloadResult = 16259 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 16260 16261 if (OverloadResult == OR_No_Viable_Function) { 16262 *CallExpr = ExprError(); 16263 return FRS_NoViableFunction; 16264 } 16265 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 16266 Loc, nullptr, CandidateSet, &Best, 16267 OverloadResult, 16268 /*AllowTypoCorrection=*/false); 16269 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 16270 *CallExpr = ExprError(); 16271 return FRS_DiagnosticIssued; 16272 } 16273 } 16274 return FRS_Success; 16275 } 16276 16277 ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 16278 FunctionDecl *Fn) { 16279 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 16280 ExprResult SubExpr = 16281 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn); 16282 if (SubExpr.isInvalid()) 16283 return ExprError(); 16284 if (SubExpr.get() == PE->getSubExpr()) 16285 return PE; 16286 16287 return new (Context) 16288 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 16289 } 16290 16291 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 16292 ExprResult SubExpr = 16293 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn); 16294 if (SubExpr.isInvalid()) 16295 return ExprError(); 16296 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 16297 SubExpr.get()->getType()) && 16298 "Implicit cast type cannot be determined from overload"); 16299 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 16300 if (SubExpr.get() == ICE->getSubExpr()) 16301 return ICE; 16302 16303 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 16304 SubExpr.get(), nullptr, ICE->getValueKind(), 16305 CurFPFeatureOverrides()); 16306 } 16307 16308 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 16309 if (!GSE->isResultDependent()) { 16310 ExprResult SubExpr = 16311 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 16312 if (SubExpr.isInvalid()) 16313 return ExprError(); 16314 if (SubExpr.get() == GSE->getResultExpr()) 16315 return GSE; 16316 16317 // Replace the resulting type information before rebuilding the generic 16318 // selection expression. 16319 ArrayRef<Expr *> A = GSE->getAssocExprs(); 16320 SmallVector<Expr *, 4> AssocExprs(A); 16321 unsigned ResultIdx = GSE->getResultIndex(); 16322 AssocExprs[ResultIdx] = SubExpr.get(); 16323 16324 if (GSE->isExprPredicate()) 16325 return GenericSelectionExpr::Create( 16326 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 16327 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 16328 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 16329 ResultIdx); 16330 return GenericSelectionExpr::Create( 16331 Context, GSE->getGenericLoc(), GSE->getControllingType(), 16332 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 16333 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 16334 ResultIdx); 16335 } 16336 // Rather than fall through to the unreachable, return the original generic 16337 // selection expression. 16338 return GSE; 16339 } 16340 16341 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 16342 assert(UnOp->getOpcode() == UO_AddrOf && 16343 "Can only take the address of an overloaded function"); 16344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 16345 if (!Method->isImplicitObjectMemberFunction()) { 16346 // Do nothing: the address of static and 16347 // explicit object member functions is a (non-member) function pointer. 16348 } else { 16349 // Fix the subexpression, which really has to be an 16350 // UnresolvedLookupExpr holding an overloaded member function 16351 // or template. 16352 ExprResult SubExpr = 16353 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn); 16354 if (SubExpr.isInvalid()) 16355 return ExprError(); 16356 if (SubExpr.get() == UnOp->getSubExpr()) 16357 return UnOp; 16358 16359 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(), 16360 SubExpr.get(), Method)) 16361 return ExprError(); 16362 16363 assert(isa<DeclRefExpr>(SubExpr.get()) && 16364 "fixed to something other than a decl ref"); 16365 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() && 16366 "fixed to a member ref with no nested name qualifier"); 16367 16368 // We have taken the address of a pointer to member 16369 // function. Perform the computation here so that we get the 16370 // appropriate pointer to member type. 16371 QualType ClassType 16372 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 16373 QualType MemPtrType 16374 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 16375 // Under the MS ABI, lock down the inheritance model now. 16376 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 16377 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 16378 16379 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf, 16380 MemPtrType, VK_PRValue, OK_Ordinary, 16381 UnOp->getOperatorLoc(), false, 16382 CurFPFeatureOverrides()); 16383 } 16384 } 16385 ExprResult SubExpr = 16386 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn); 16387 if (SubExpr.isInvalid()) 16388 return ExprError(); 16389 if (SubExpr.get() == UnOp->getSubExpr()) 16390 return UnOp; 16391 16392 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, 16393 SubExpr.get()); 16394 } 16395 16396 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 16397 // FIXME: avoid copy. 16398 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 16399 if (ULE->hasExplicitTemplateArgs()) { 16400 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 16401 TemplateArgs = &TemplateArgsBuffer; 16402 } 16403 16404 QualType Type = Fn->getType(); 16405 ExprValueKind ValueKind = 16406 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter() 16407 ? VK_LValue 16408 : VK_PRValue; 16409 16410 // FIXME: Duplicated from BuildDeclarationNameExpr. 16411 if (unsigned BID = Fn->getBuiltinID()) { 16412 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 16413 Type = Context.BuiltinFnTy; 16414 ValueKind = VK_PRValue; 16415 } 16416 } 16417 16418 DeclRefExpr *DRE = BuildDeclRefExpr( 16419 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), 16420 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); 16421 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 16422 return DRE; 16423 } 16424 16425 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 16426 // FIXME: avoid copy. 16427 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 16428 if (MemExpr->hasExplicitTemplateArgs()) { 16429 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 16430 TemplateArgs = &TemplateArgsBuffer; 16431 } 16432 16433 Expr *Base; 16434 16435 // If we're filling in a static method where we used to have an 16436 // implicit member access, rewrite to a simple decl ref. 16437 if (MemExpr->isImplicitAccess()) { 16438 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 16439 DeclRefExpr *DRE = BuildDeclRefExpr( 16440 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 16441 MemExpr->getQualifierLoc(), Found.getDecl(), 16442 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 16443 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 16444 return DRE; 16445 } else { 16446 SourceLocation Loc = MemExpr->getMemberLoc(); 16447 if (MemExpr->getQualifier()) 16448 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 16449 Base = 16450 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 16451 } 16452 } else 16453 Base = MemExpr->getBase(); 16454 16455 ExprValueKind valueKind; 16456 QualType type; 16457 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 16458 valueKind = VK_LValue; 16459 type = Fn->getType(); 16460 } else { 16461 valueKind = VK_PRValue; 16462 type = Context.BoundMemberTy; 16463 } 16464 16465 return BuildMemberExpr( 16466 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 16467 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 16468 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 16469 type, valueKind, OK_Ordinary, TemplateArgs); 16470 } 16471 16472 llvm_unreachable("Invalid reference to overloaded function"); 16473 } 16474 16475 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 16476 DeclAccessPair Found, 16477 FunctionDecl *Fn) { 16478 return FixOverloadedFunctionReference(E.get(), Found, Fn); 16479 } 16480 16481 bool clang::shouldEnforceArgLimit(bool PartialOverloading, 16482 FunctionDecl *Function) { 16483 if (!PartialOverloading || !Function) 16484 return true; 16485 if (Function->isVariadic()) 16486 return false; 16487 if (const auto *Proto = 16488 dyn_cast<FunctionProtoType>(Function->getFunctionType())) 16489 if (Proto->isTemplateVariadic()) 16490 return false; 16491 if (auto *Pattern = Function->getTemplateInstantiationPattern()) 16492 if (const auto *Proto = 16493 dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) 16494 if (Proto->isTemplateVariadic()) 16495 return false; 16496 return true; 16497 } 16498 16499 void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, 16500 DeclarationName Name, 16501 OverloadCandidateSet &CandidateSet, 16502 FunctionDecl *Fn, MultiExprArg Args, 16503 bool IsMember) { 16504 StringLiteral *Msg = Fn->getDeletedMessage(); 16505 CandidateSet.NoteCandidates( 16506 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call) 16507 << IsMember << Name << (Msg != nullptr) 16508 << (Msg ? Msg->getString() : StringRef()) 16509 << Range), 16510 *this, OCD_AllCandidates, Args); 16511 } 16512