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 "clang/Sema/Overload.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 const Expr *Base, bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 DeclRefExpr *DRE = new (S.Context) 64 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 65 if (HadMultipleCandidates) 66 DRE->setHadMultipleCandidates(true); 67 68 S.MarkDeclRefReferenced(DRE, Base); 69 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 70 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 71 S.ResolveExceptionSpec(Loc, FPT); 72 DRE->setType(Fn->getType()); 73 } 74 } 75 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 76 CK_FunctionToPointerDecay); 77 } 78 79 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 80 bool InOverloadResolution, 81 StandardConversionSequence &SCS, 82 bool CStyle, 83 bool AllowObjCWritebackConversion); 84 85 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 86 QualType &ToType, 87 bool InOverloadResolution, 88 StandardConversionSequence &SCS, 89 bool CStyle); 90 static OverloadingResult 91 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 92 UserDefinedConversionSequence& User, 93 OverloadCandidateSet& Conversions, 94 bool AllowExplicit, 95 bool AllowObjCConversionOnExplicit); 96 97 98 static ImplicitConversionSequence::CompareKind 99 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 100 const StandardConversionSequence& SCS1, 101 const StandardConversionSequence& SCS2); 102 103 static ImplicitConversionSequence::CompareKind 104 CompareQualificationConversions(Sema &S, 105 const StandardConversionSequence& SCS1, 106 const StandardConversionSequence& SCS2); 107 108 static ImplicitConversionSequence::CompareKind 109 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 110 const StandardConversionSequence& SCS1, 111 const StandardConversionSequence& SCS2); 112 113 /// GetConversionRank - Retrieve the implicit conversion rank 114 /// corresponding to the given implicit conversion kind. 115 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 116 static const ImplicitConversionRank 117 Rank[(int)ICK_Num_Conversion_Kinds] = { 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Promotion, 125 ICR_Promotion, 126 ICR_Promotion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_OCL_Scalar_Widening, 138 ICR_Complex_Real_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Writeback_Conversion, 142 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 143 // it was omitted by the patch that added 144 // ICK_Zero_Event_Conversion 145 ICR_C_Conversion, 146 ICR_C_Conversion_Extension 147 }; 148 return Rank[(int)Kind]; 149 } 150 151 /// GetImplicitConversionName - Return the name of this kind of 152 /// implicit conversion. 153 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 155 "No conversion", 156 "Lvalue-to-rvalue", 157 "Array-to-pointer", 158 "Function-to-pointer", 159 "Function pointer conversion", 160 "Qualification", 161 "Integral promotion", 162 "Floating point promotion", 163 "Complex promotion", 164 "Integral conversion", 165 "Floating conversion", 166 "Complex conversion", 167 "Floating-integral conversion", 168 "Pointer conversion", 169 "Pointer-to-member conversion", 170 "Boolean conversion", 171 "Compatible-types conversion", 172 "Derived-to-base conversion", 173 "Vector conversion", 174 "Vector splat", 175 "Complex-real conversion", 176 "Block Pointer conversion", 177 "Transparent Union Conversion", 178 "Writeback conversion", 179 "OpenCL Zero Event Conversion", 180 "C specific type conversion", 181 "Incompatible pointer conversion" 182 }; 183 return Name[Kind]; 184 } 185 186 /// StandardConversionSequence - Set the standard conversion 187 /// sequence to the identity conversion. 188 void StandardConversionSequence::setAsIdentityConversion() { 189 First = ICK_Identity; 190 Second = ICK_Identity; 191 Third = ICK_Identity; 192 DeprecatedStringLiteralToCharPtr = false; 193 QualificationIncludesObjCLifetime = false; 194 ReferenceBinding = false; 195 DirectBinding = false; 196 IsLvalueReference = true; 197 BindsToFunctionLvalue = false; 198 BindsToRvalue = false; 199 BindsImplicitObjectArgumentWithoutRefQualifier = false; 200 ObjCLifetimeConversionBinding = false; 201 CopyConstructor = nullptr; 202 } 203 204 /// getRank - Retrieve the rank of this standard conversion sequence 205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 206 /// implicit conversions. 207 ImplicitConversionRank StandardConversionSequence::getRank() const { 208 ImplicitConversionRank Rank = ICR_Exact_Match; 209 if (GetConversionRank(First) > Rank) 210 Rank = GetConversionRank(First); 211 if (GetConversionRank(Second) > Rank) 212 Rank = GetConversionRank(Second); 213 if (GetConversionRank(Third) > Rank) 214 Rank = GetConversionRank(Third); 215 return Rank; 216 } 217 218 /// isPointerConversionToBool - Determines whether this conversion is 219 /// a conversion of a pointer or pointer-to-member to bool. This is 220 /// used as part of the ranking of standard conversion sequences 221 /// (C++ 13.3.3.2p4). 222 bool StandardConversionSequence::isPointerConversionToBool() const { 223 // Note that FromType has not necessarily been transformed by the 224 // array-to-pointer or function-to-pointer implicit conversions, so 225 // check for their presence as well as checking whether FromType is 226 // a pointer. 227 if (getToType(1)->isBooleanType() && 228 (getFromType()->isPointerType() || 229 getFromType()->isMemberPointerType() || 230 getFromType()->isObjCObjectPointerType() || 231 getFromType()->isBlockPointerType() || 232 getFromType()->isNullPtrType() || 233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234 return true; 235 236 return false; 237 } 238 239 /// isPointerConversionToVoidPointer - Determines whether this 240 /// conversion is a conversion of a pointer to a void pointer. This is 241 /// used as part of the ranking of standard conversion sequences (C++ 242 /// 13.3.3.2p4). 243 bool 244 StandardConversionSequence:: 245 isPointerConversionToVoidPointer(ASTContext& Context) const { 246 QualType FromType = getFromType(); 247 QualType ToType = getToType(1); 248 249 // Note that FromType has not necessarily been transformed by the 250 // array-to-pointer implicit conversion, so check for its presence 251 // and redo the conversion to get a pointer. 252 if (First == ICK_Array_To_Pointer) 253 FromType = Context.getArrayDecayedType(FromType); 254 255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 257 return ToPtrType->getPointeeType()->isVoidType(); 258 259 return false; 260 } 261 262 /// Skip any implicit casts which could be either part of a narrowing conversion 263 /// or after one in an implicit conversion. 264 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 265 const Expr *Converted) { 266 // We can have cleanups wrapping the converted expression; these need to be 267 // preserved so that destructors run if necessary. 268 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 269 Expr *Inner = 270 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 271 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 272 EWC->getObjects()); 273 } 274 275 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 276 switch (ICE->getCastKind()) { 277 case CK_NoOp: 278 case CK_IntegralCast: 279 case CK_IntegralToBoolean: 280 case CK_IntegralToFloating: 281 case CK_BooleanToSignedIntegral: 282 case CK_FloatingToIntegral: 283 case CK_FloatingToBoolean: 284 case CK_FloatingCast: 285 Converted = ICE->getSubExpr(); 286 continue; 287 288 default: 289 return Converted; 290 } 291 } 292 293 return Converted; 294 } 295 296 /// Check if this standard conversion sequence represents a narrowing 297 /// conversion, according to C++11 [dcl.init.list]p7. 298 /// 299 /// \param Ctx The AST context. 300 /// \param Converted The result of applying this standard conversion sequence. 301 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 302 /// value of the expression prior to the narrowing conversion. 303 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 304 /// type of the expression prior to the narrowing conversion. 305 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 306 /// from floating point types to integral types should be ignored. 307 NarrowingKind StandardConversionSequence::getNarrowingKind( 308 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 309 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 310 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 311 312 // C++11 [dcl.init.list]p7: 313 // A narrowing conversion is an implicit conversion ... 314 QualType FromType = getToType(0); 315 QualType ToType = getToType(1); 316 317 // A conversion to an enumeration type is narrowing if the conversion to 318 // the underlying type is narrowing. This only arises for expressions of 319 // the form 'Enum{init}'. 320 if (auto *ET = ToType->getAs<EnumType>()) 321 ToType = ET->getDecl()->getIntegerType(); 322 323 switch (Second) { 324 // 'bool' is an integral type; dispatch to the right place to handle it. 325 case ICK_Boolean_Conversion: 326 if (FromType->isRealFloatingType()) 327 goto FloatingIntegralConversion; 328 if (FromType->isIntegralOrUnscopedEnumerationType()) 329 goto IntegralConversion; 330 // Boolean conversions can be from pointers and pointers to members 331 // [conv.bool], and those aren't considered narrowing conversions. 332 return NK_Not_Narrowing; 333 334 // -- from a floating-point type to an integer type, or 335 // 336 // -- from an integer type or unscoped enumeration type to a floating-point 337 // type, except where the source is a constant expression and the actual 338 // value after conversion will fit into the target type and will produce 339 // the original value when converted back to the original type, or 340 case ICK_Floating_Integral: 341 FloatingIntegralConversion: 342 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 343 return NK_Type_Narrowing; 344 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 345 ToType->isRealFloatingType()) { 346 if (IgnoreFloatToIntegralConversion) 347 return NK_Not_Narrowing; 348 llvm::APSInt IntConstantValue; 349 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 350 assert(Initializer && "Unknown conversion expression"); 351 352 // If it's value-dependent, we can't tell whether it's narrowing. 353 if (Initializer->isValueDependent()) 354 return NK_Dependent_Narrowing; 355 356 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 357 // Convert the integer to the floating type. 358 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 359 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 360 llvm::APFloat::rmNearestTiesToEven); 361 // And back. 362 llvm::APSInt ConvertedValue = IntConstantValue; 363 bool ignored; 364 Result.convertToInteger(ConvertedValue, 365 llvm::APFloat::rmTowardZero, &ignored); 366 // If the resulting value is different, this was a narrowing conversion. 367 if (IntConstantValue != ConvertedValue) { 368 ConstantValue = APValue(IntConstantValue); 369 ConstantType = Initializer->getType(); 370 return NK_Constant_Narrowing; 371 } 372 } else { 373 // Variables are always narrowings. 374 return NK_Variable_Narrowing; 375 } 376 } 377 return NK_Not_Narrowing; 378 379 // -- from long double to double or float, or from double to float, except 380 // where the source is a constant expression and the actual value after 381 // conversion is within the range of values that can be represented (even 382 // if it cannot be represented exactly), or 383 case ICK_Floating_Conversion: 384 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 385 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 386 // FromType is larger than ToType. 387 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 388 389 // If it's value-dependent, we can't tell whether it's narrowing. 390 if (Initializer->isValueDependent()) 391 return NK_Dependent_Narrowing; 392 393 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 394 // Constant! 395 assert(ConstantValue.isFloat()); 396 llvm::APFloat FloatVal = ConstantValue.getFloat(); 397 // Convert the source value into the target type. 398 bool ignored; 399 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 400 Ctx.getFloatTypeSemantics(ToType), 401 llvm::APFloat::rmNearestTiesToEven, &ignored); 402 // If there was no overflow, the source value is within the range of 403 // values that can be represented. 404 if (ConvertStatus & llvm::APFloat::opOverflow) { 405 ConstantType = Initializer->getType(); 406 return NK_Constant_Narrowing; 407 } 408 } else { 409 return NK_Variable_Narrowing; 410 } 411 } 412 return NK_Not_Narrowing; 413 414 // -- from an integer type or unscoped enumeration type to an integer type 415 // that cannot represent all the values of the original type, except where 416 // the source is a constant expression and the actual value after 417 // conversion will fit into the target type and will produce the original 418 // value when converted back to the original type. 419 case ICK_Integral_Conversion: 420 IntegralConversion: { 421 assert(FromType->isIntegralOrUnscopedEnumerationType()); 422 assert(ToType->isIntegralOrUnscopedEnumerationType()); 423 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 424 const unsigned FromWidth = Ctx.getIntWidth(FromType); 425 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 426 const unsigned ToWidth = Ctx.getIntWidth(ToType); 427 428 if (FromWidth > ToWidth || 429 (FromWidth == ToWidth && FromSigned != ToSigned) || 430 (FromSigned && !ToSigned)) { 431 // Not all values of FromType can be represented in ToType. 432 llvm::APSInt InitializerValue; 433 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 434 435 // If it's value-dependent, we can't tell whether it's narrowing. 436 if (Initializer->isValueDependent()) 437 return NK_Dependent_Narrowing; 438 439 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 440 // Such conversions on variables are always narrowing. 441 return NK_Variable_Narrowing; 442 } 443 bool Narrowing = false; 444 if (FromWidth < ToWidth) { 445 // Negative -> unsigned is narrowing. Otherwise, more bits is never 446 // narrowing. 447 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 448 Narrowing = true; 449 } else { 450 // Add a bit to the InitializerValue so we don't have to worry about 451 // signed vs. unsigned comparisons. 452 InitializerValue = InitializerValue.extend( 453 InitializerValue.getBitWidth() + 1); 454 // Convert the initializer to and from the target width and signed-ness. 455 llvm::APSInt ConvertedValue = InitializerValue; 456 ConvertedValue = ConvertedValue.trunc(ToWidth); 457 ConvertedValue.setIsSigned(ToSigned); 458 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 459 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 460 // If the result is different, this was a narrowing conversion. 461 if (ConvertedValue != InitializerValue) 462 Narrowing = true; 463 } 464 if (Narrowing) { 465 ConstantType = Initializer->getType(); 466 ConstantValue = APValue(InitializerValue); 467 return NK_Constant_Narrowing; 468 } 469 } 470 return NK_Not_Narrowing; 471 } 472 473 default: 474 // Other kinds of conversions are not narrowings. 475 return NK_Not_Narrowing; 476 } 477 } 478 479 /// dump - Print this standard conversion sequence to standard 480 /// error. Useful for debugging overloading issues. 481 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 482 raw_ostream &OS = llvm::errs(); 483 bool PrintedSomething = false; 484 if (First != ICK_Identity) { 485 OS << GetImplicitConversionName(First); 486 PrintedSomething = true; 487 } 488 489 if (Second != ICK_Identity) { 490 if (PrintedSomething) { 491 OS << " -> "; 492 } 493 OS << GetImplicitConversionName(Second); 494 495 if (CopyConstructor) { 496 OS << " (by copy constructor)"; 497 } else if (DirectBinding) { 498 OS << " (direct reference binding)"; 499 } else if (ReferenceBinding) { 500 OS << " (reference binding)"; 501 } 502 PrintedSomething = true; 503 } 504 505 if (Third != ICK_Identity) { 506 if (PrintedSomething) { 507 OS << " -> "; 508 } 509 OS << GetImplicitConversionName(Third); 510 PrintedSomething = true; 511 } 512 513 if (!PrintedSomething) { 514 OS << "No conversions required"; 515 } 516 } 517 518 /// dump - Print this user-defined conversion sequence to standard 519 /// error. Useful for debugging overloading issues. 520 void UserDefinedConversionSequence::dump() const { 521 raw_ostream &OS = llvm::errs(); 522 if (Before.First || Before.Second || Before.Third) { 523 Before.dump(); 524 OS << " -> "; 525 } 526 if (ConversionFunction) 527 OS << '\'' << *ConversionFunction << '\''; 528 else 529 OS << "aggregate initialization"; 530 if (After.First || After.Second || After.Third) { 531 OS << " -> "; 532 After.dump(); 533 } 534 } 535 536 /// dump - Print this implicit conversion sequence to standard 537 /// error. Useful for debugging overloading issues. 538 void ImplicitConversionSequence::dump() const { 539 raw_ostream &OS = llvm::errs(); 540 if (isStdInitializerListElement()) 541 OS << "Worst std::initializer_list element conversion: "; 542 switch (ConversionKind) { 543 case StandardConversion: 544 OS << "Standard conversion: "; 545 Standard.dump(); 546 break; 547 case UserDefinedConversion: 548 OS << "User-defined conversion: "; 549 UserDefined.dump(); 550 break; 551 case EllipsisConversion: 552 OS << "Ellipsis conversion"; 553 break; 554 case AmbiguousConversion: 555 OS << "Ambiguous conversion"; 556 break; 557 case BadConversion: 558 OS << "Bad conversion"; 559 break; 560 } 561 562 OS << "\n"; 563 } 564 565 void AmbiguousConversionSequence::construct() { 566 new (&conversions()) ConversionSet(); 567 } 568 569 void AmbiguousConversionSequence::destruct() { 570 conversions().~ConversionSet(); 571 } 572 573 void 574 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 575 FromTypePtr = O.FromTypePtr; 576 ToTypePtr = O.ToTypePtr; 577 new (&conversions()) ConversionSet(O.conversions()); 578 } 579 580 namespace { 581 // Structure used by DeductionFailureInfo to store 582 // template argument information. 583 struct DFIArguments { 584 TemplateArgument FirstArg; 585 TemplateArgument SecondArg; 586 }; 587 // Structure used by DeductionFailureInfo to store 588 // template parameter and template argument information. 589 struct DFIParamWithArguments : DFIArguments { 590 TemplateParameter Param; 591 }; 592 // Structure used by DeductionFailureInfo to store template argument 593 // information and the index of the problematic call argument. 594 struct DFIDeducedMismatchArgs : DFIArguments { 595 TemplateArgumentList *TemplateArgs; 596 unsigned CallArgIndex; 597 }; 598 // Structure used by DeductionFailureInfo to store information about 599 // unsatisfied constraints. 600 struct CNSInfo { 601 TemplateArgumentList *TemplateArgs; 602 ConstraintSatisfaction Satisfaction; 603 }; 604 } 605 606 /// Convert from Sema's representation of template deduction information 607 /// to the form used in overload-candidate information. 608 DeductionFailureInfo 609 clang::MakeDeductionFailureInfo(ASTContext &Context, 610 Sema::TemplateDeductionResult TDK, 611 TemplateDeductionInfo &Info) { 612 DeductionFailureInfo Result; 613 Result.Result = static_cast<unsigned>(TDK); 614 Result.HasDiagnostic = false; 615 switch (TDK) { 616 case Sema::TDK_Invalid: 617 case Sema::TDK_InstantiationDepth: 618 case Sema::TDK_TooManyArguments: 619 case Sema::TDK_TooFewArguments: 620 case Sema::TDK_MiscellaneousDeductionFailure: 621 case Sema::TDK_CUDATargetMismatch: 622 Result.Data = nullptr; 623 break; 624 625 case Sema::TDK_Incomplete: 626 case Sema::TDK_InvalidExplicitArguments: 627 Result.Data = Info.Param.getOpaqueValue(); 628 break; 629 630 case Sema::TDK_DeducedMismatch: 631 case Sema::TDK_DeducedMismatchNested: { 632 // FIXME: Should allocate from normal heap so that we can free this later. 633 auto *Saved = new (Context) DFIDeducedMismatchArgs; 634 Saved->FirstArg = Info.FirstArg; 635 Saved->SecondArg = Info.SecondArg; 636 Saved->TemplateArgs = Info.take(); 637 Saved->CallArgIndex = Info.CallArgIndex; 638 Result.Data = Saved; 639 break; 640 } 641 642 case Sema::TDK_NonDeducedMismatch: { 643 // FIXME: Should allocate from normal heap so that we can free this later. 644 DFIArguments *Saved = new (Context) DFIArguments; 645 Saved->FirstArg = Info.FirstArg; 646 Saved->SecondArg = Info.SecondArg; 647 Result.Data = Saved; 648 break; 649 } 650 651 case Sema::TDK_IncompletePack: 652 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 653 case Sema::TDK_Inconsistent: 654 case Sema::TDK_Underqualified: { 655 // FIXME: Should allocate from normal heap so that we can free this later. 656 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 657 Saved->Param = Info.Param; 658 Saved->FirstArg = Info.FirstArg; 659 Saved->SecondArg = Info.SecondArg; 660 Result.Data = Saved; 661 break; 662 } 663 664 case Sema::TDK_SubstitutionFailure: 665 Result.Data = Info.take(); 666 if (Info.hasSFINAEDiagnostic()) { 667 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 668 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 669 Info.takeSFINAEDiagnostic(*Diag); 670 Result.HasDiagnostic = true; 671 } 672 break; 673 674 case Sema::TDK_ConstraintsNotSatisfied: { 675 CNSInfo *Saved = new (Context) CNSInfo; 676 Saved->TemplateArgs = Info.take(); 677 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 678 Result.Data = Saved; 679 break; 680 } 681 682 case Sema::TDK_Success: 683 case Sema::TDK_NonDependentConversionFailure: 684 llvm_unreachable("not a deduction failure"); 685 } 686 687 return Result; 688 } 689 690 void DeductionFailureInfo::Destroy() { 691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 692 case Sema::TDK_Success: 693 case Sema::TDK_Invalid: 694 case Sema::TDK_InstantiationDepth: 695 case Sema::TDK_Incomplete: 696 case Sema::TDK_TooManyArguments: 697 case Sema::TDK_TooFewArguments: 698 case Sema::TDK_InvalidExplicitArguments: 699 case Sema::TDK_CUDATargetMismatch: 700 case Sema::TDK_NonDependentConversionFailure: 701 break; 702 703 case Sema::TDK_IncompletePack: 704 case Sema::TDK_Inconsistent: 705 case Sema::TDK_Underqualified: 706 case Sema::TDK_DeducedMismatch: 707 case Sema::TDK_DeducedMismatchNested: 708 case Sema::TDK_NonDeducedMismatch: 709 // FIXME: Destroy the data? 710 Data = nullptr; 711 break; 712 713 case Sema::TDK_SubstitutionFailure: 714 // FIXME: Destroy the template argument list? 715 Data = nullptr; 716 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 717 Diag->~PartialDiagnosticAt(); 718 HasDiagnostic = false; 719 } 720 break; 721 722 case Sema::TDK_ConstraintsNotSatisfied: 723 // FIXME: Destroy the template argument list? 724 Data = nullptr; 725 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 726 Diag->~PartialDiagnosticAt(); 727 HasDiagnostic = false; 728 } 729 break; 730 731 // Unhandled 732 case Sema::TDK_MiscellaneousDeductionFailure: 733 break; 734 } 735 } 736 737 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 738 if (HasDiagnostic) 739 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 740 return nullptr; 741 } 742 743 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 745 case Sema::TDK_Success: 746 case Sema::TDK_Invalid: 747 case Sema::TDK_InstantiationDepth: 748 case Sema::TDK_TooManyArguments: 749 case Sema::TDK_TooFewArguments: 750 case Sema::TDK_SubstitutionFailure: 751 case Sema::TDK_DeducedMismatch: 752 case Sema::TDK_DeducedMismatchNested: 753 case Sema::TDK_NonDeducedMismatch: 754 case Sema::TDK_CUDATargetMismatch: 755 case Sema::TDK_NonDependentConversionFailure: 756 case Sema::TDK_ConstraintsNotSatisfied: 757 return TemplateParameter(); 758 759 case Sema::TDK_Incomplete: 760 case Sema::TDK_InvalidExplicitArguments: 761 return TemplateParameter::getFromOpaqueValue(Data); 762 763 case Sema::TDK_IncompletePack: 764 case Sema::TDK_Inconsistent: 765 case Sema::TDK_Underqualified: 766 return static_cast<DFIParamWithArguments*>(Data)->Param; 767 768 // Unhandled 769 case Sema::TDK_MiscellaneousDeductionFailure: 770 break; 771 } 772 773 return TemplateParameter(); 774 } 775 776 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 777 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 778 case Sema::TDK_Success: 779 case Sema::TDK_Invalid: 780 case Sema::TDK_InstantiationDepth: 781 case Sema::TDK_TooManyArguments: 782 case Sema::TDK_TooFewArguments: 783 case Sema::TDK_Incomplete: 784 case Sema::TDK_IncompletePack: 785 case Sema::TDK_InvalidExplicitArguments: 786 case Sema::TDK_Inconsistent: 787 case Sema::TDK_Underqualified: 788 case Sema::TDK_NonDeducedMismatch: 789 case Sema::TDK_CUDATargetMismatch: 790 case Sema::TDK_NonDependentConversionFailure: 791 return nullptr; 792 793 case Sema::TDK_DeducedMismatch: 794 case Sema::TDK_DeducedMismatchNested: 795 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 796 797 case Sema::TDK_SubstitutionFailure: 798 return static_cast<TemplateArgumentList*>(Data); 799 800 case Sema::TDK_ConstraintsNotSatisfied: 801 return static_cast<CNSInfo*>(Data)->TemplateArgs; 802 803 // Unhandled 804 case Sema::TDK_MiscellaneousDeductionFailure: 805 break; 806 } 807 808 return nullptr; 809 } 810 811 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 813 case Sema::TDK_Success: 814 case Sema::TDK_Invalid: 815 case Sema::TDK_InstantiationDepth: 816 case Sema::TDK_Incomplete: 817 case Sema::TDK_TooManyArguments: 818 case Sema::TDK_TooFewArguments: 819 case Sema::TDK_InvalidExplicitArguments: 820 case Sema::TDK_SubstitutionFailure: 821 case Sema::TDK_CUDATargetMismatch: 822 case Sema::TDK_NonDependentConversionFailure: 823 case Sema::TDK_ConstraintsNotSatisfied: 824 return nullptr; 825 826 case Sema::TDK_IncompletePack: 827 case Sema::TDK_Inconsistent: 828 case Sema::TDK_Underqualified: 829 case Sema::TDK_DeducedMismatch: 830 case Sema::TDK_DeducedMismatchNested: 831 case Sema::TDK_NonDeducedMismatch: 832 return &static_cast<DFIArguments*>(Data)->FirstArg; 833 834 // Unhandled 835 case Sema::TDK_MiscellaneousDeductionFailure: 836 break; 837 } 838 839 return nullptr; 840 } 841 842 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 843 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 844 case Sema::TDK_Success: 845 case Sema::TDK_Invalid: 846 case Sema::TDK_InstantiationDepth: 847 case Sema::TDK_Incomplete: 848 case Sema::TDK_IncompletePack: 849 case Sema::TDK_TooManyArguments: 850 case Sema::TDK_TooFewArguments: 851 case Sema::TDK_InvalidExplicitArguments: 852 case Sema::TDK_SubstitutionFailure: 853 case Sema::TDK_CUDATargetMismatch: 854 case Sema::TDK_NonDependentConversionFailure: 855 case Sema::TDK_ConstraintsNotSatisfied: 856 return nullptr; 857 858 case Sema::TDK_Inconsistent: 859 case Sema::TDK_Underqualified: 860 case Sema::TDK_DeducedMismatch: 861 case Sema::TDK_DeducedMismatchNested: 862 case Sema::TDK_NonDeducedMismatch: 863 return &static_cast<DFIArguments*>(Data)->SecondArg; 864 865 // Unhandled 866 case Sema::TDK_MiscellaneousDeductionFailure: 867 break; 868 } 869 870 return nullptr; 871 } 872 873 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 874 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 875 case Sema::TDK_DeducedMismatch: 876 case Sema::TDK_DeducedMismatchNested: 877 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 878 879 default: 880 return llvm::None; 881 } 882 } 883 884 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 885 OverloadedOperatorKind Op) { 886 if (!AllowRewrittenCandidates) 887 return false; 888 return Op == OO_EqualEqual || Op == OO_Spaceship; 889 } 890 891 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 892 ASTContext &Ctx, const FunctionDecl *FD) { 893 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 894 return false; 895 // Don't bother adding a reversed candidate that can never be a better 896 // match than the non-reversed version. 897 return FD->getNumParams() != 2 || 898 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 899 FD->getParamDecl(1)->getType()) || 900 FD->hasAttr<EnableIfAttr>(); 901 } 902 903 void OverloadCandidateSet::destroyCandidates() { 904 for (iterator i = begin(), e = end(); i != e; ++i) { 905 for (auto &C : i->Conversions) 906 C.~ImplicitConversionSequence(); 907 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 908 i->DeductionFailure.Destroy(); 909 } 910 } 911 912 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 913 destroyCandidates(); 914 SlabAllocator.Reset(); 915 NumInlineBytesUsed = 0; 916 Candidates.clear(); 917 Functions.clear(); 918 Kind = CSK; 919 } 920 921 namespace { 922 class UnbridgedCastsSet { 923 struct Entry { 924 Expr **Addr; 925 Expr *Saved; 926 }; 927 SmallVector<Entry, 2> Entries; 928 929 public: 930 void save(Sema &S, Expr *&E) { 931 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 932 Entry entry = { &E, E }; 933 Entries.push_back(entry); 934 E = S.stripARCUnbridgedCast(E); 935 } 936 937 void restore() { 938 for (SmallVectorImpl<Entry>::iterator 939 i = Entries.begin(), e = Entries.end(); i != e; ++i) 940 *i->Addr = i->Saved; 941 } 942 }; 943 } 944 945 /// checkPlaceholderForOverload - Do any interesting placeholder-like 946 /// preprocessing on the given expression. 947 /// 948 /// \param unbridgedCasts a collection to which to add unbridged casts; 949 /// without this, they will be immediately diagnosed as errors 950 /// 951 /// Return true on unrecoverable error. 952 static bool 953 checkPlaceholderForOverload(Sema &S, Expr *&E, 954 UnbridgedCastsSet *unbridgedCasts = nullptr) { 955 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 956 // We can't handle overloaded expressions here because overload 957 // resolution might reasonably tweak them. 958 if (placeholder->getKind() == BuiltinType::Overload) return false; 959 960 // If the context potentially accepts unbridged ARC casts, strip 961 // the unbridged cast and add it to the collection for later restoration. 962 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 963 unbridgedCasts) { 964 unbridgedCasts->save(S, E); 965 return false; 966 } 967 968 // Go ahead and check everything else. 969 ExprResult result = S.CheckPlaceholderExpr(E); 970 if (result.isInvalid()) 971 return true; 972 973 E = result.get(); 974 return false; 975 } 976 977 // Nothing to do. 978 return false; 979 } 980 981 /// checkArgPlaceholdersForOverload - Check a set of call operands for 982 /// placeholders. 983 static bool checkArgPlaceholdersForOverload(Sema &S, 984 MultiExprArg Args, 985 UnbridgedCastsSet &unbridged) { 986 for (unsigned i = 0, e = Args.size(); i != e; ++i) 987 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 988 return true; 989 990 return false; 991 } 992 993 /// Determine whether the given New declaration is an overload of the 994 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 995 /// New and Old cannot be overloaded, e.g., if New has the same signature as 996 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 997 /// functions (or function templates) at all. When it does return Ovl_Match or 998 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 999 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1000 /// declaration. 1001 /// 1002 /// Example: Given the following input: 1003 /// 1004 /// void f(int, float); // #1 1005 /// void f(int, int); // #2 1006 /// int f(int, int); // #3 1007 /// 1008 /// When we process #1, there is no previous declaration of "f", so IsOverload 1009 /// will not be used. 1010 /// 1011 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1012 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1013 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1014 /// unchanged. 1015 /// 1016 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1017 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1018 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1019 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1020 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1021 /// 1022 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1023 /// by a using declaration. The rules for whether to hide shadow declarations 1024 /// ignore some properties which otherwise figure into a function template's 1025 /// signature. 1026 Sema::OverloadKind 1027 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1028 NamedDecl *&Match, bool NewIsUsingDecl) { 1029 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1030 I != E; ++I) { 1031 NamedDecl *OldD = *I; 1032 1033 bool OldIsUsingDecl = false; 1034 if (isa<UsingShadowDecl>(OldD)) { 1035 OldIsUsingDecl = true; 1036 1037 // We can always introduce two using declarations into the same 1038 // context, even if they have identical signatures. 1039 if (NewIsUsingDecl) continue; 1040 1041 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1042 } 1043 1044 // A using-declaration does not conflict with another declaration 1045 // if one of them is hidden. 1046 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1047 continue; 1048 1049 // If either declaration was introduced by a using declaration, 1050 // we'll need to use slightly different rules for matching. 1051 // Essentially, these rules are the normal rules, except that 1052 // function templates hide function templates with different 1053 // return types or template parameter lists. 1054 bool UseMemberUsingDeclRules = 1055 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1056 !New->getFriendObjectKind(); 1057 1058 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1059 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1060 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1061 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1062 continue; 1063 } 1064 1065 if (!isa<FunctionTemplateDecl>(OldD) && 1066 !shouldLinkPossiblyHiddenDecl(*I, New)) 1067 continue; 1068 1069 Match = *I; 1070 return Ovl_Match; 1071 } 1072 1073 // Builtins that have custom typechecking or have a reference should 1074 // not be overloadable or redeclarable. 1075 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1076 Match = *I; 1077 return Ovl_NonFunction; 1078 } 1079 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1080 // We can overload with these, which can show up when doing 1081 // redeclaration checks for UsingDecls. 1082 assert(Old.getLookupKind() == LookupUsingDeclName); 1083 } else if (isa<TagDecl>(OldD)) { 1084 // We can always overload with tags by hiding them. 1085 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1086 // Optimistically assume that an unresolved using decl will 1087 // overload; if it doesn't, we'll have to diagnose during 1088 // template instantiation. 1089 // 1090 // Exception: if the scope is dependent and this is not a class 1091 // member, the using declaration can only introduce an enumerator. 1092 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1093 Match = *I; 1094 return Ovl_NonFunction; 1095 } 1096 } else { 1097 // (C++ 13p1): 1098 // Only function declarations can be overloaded; object and type 1099 // declarations cannot be overloaded. 1100 Match = *I; 1101 return Ovl_NonFunction; 1102 } 1103 } 1104 1105 // C++ [temp.friend]p1: 1106 // For a friend function declaration that is not a template declaration: 1107 // -- if the name of the friend is a qualified or unqualified template-id, 1108 // [...], otherwise 1109 // -- if the name of the friend is a qualified-id and a matching 1110 // non-template function is found in the specified class or namespace, 1111 // the friend declaration refers to that function, otherwise, 1112 // -- if the name of the friend is a qualified-id and a matching function 1113 // template is found in the specified class or namespace, the friend 1114 // declaration refers to the deduced specialization of that function 1115 // template, otherwise 1116 // -- the name shall be an unqualified-id [...] 1117 // If we get here for a qualified friend declaration, we've just reached the 1118 // third bullet. If the type of the friend is dependent, skip this lookup 1119 // until instantiation. 1120 if (New->getFriendObjectKind() && New->getQualifier() && 1121 !New->getDescribedFunctionTemplate() && 1122 !New->getDependentSpecializationInfo() && 1123 !New->getType()->isDependentType()) { 1124 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1125 TemplateSpecResult.addAllDecls(Old); 1126 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1127 /*QualifiedFriend*/true)) { 1128 New->setInvalidDecl(); 1129 return Ovl_Overload; 1130 } 1131 1132 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1133 return Ovl_Match; 1134 } 1135 1136 return Ovl_Overload; 1137 } 1138 1139 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1140 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1141 // C++ [basic.start.main]p2: This function shall not be overloaded. 1142 if (New->isMain()) 1143 return false; 1144 1145 // MSVCRT user defined entry points cannot be overloaded. 1146 if (New->isMSVCRTEntryPoint()) 1147 return false; 1148 1149 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1150 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1151 1152 // C++ [temp.fct]p2: 1153 // A function template can be overloaded with other function templates 1154 // and with normal (non-template) functions. 1155 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1156 return true; 1157 1158 // Is the function New an overload of the function Old? 1159 QualType OldQType = Context.getCanonicalType(Old->getType()); 1160 QualType NewQType = Context.getCanonicalType(New->getType()); 1161 1162 // Compare the signatures (C++ 1.3.10) of the two functions to 1163 // determine whether they are overloads. If we find any mismatch 1164 // in the signature, they are overloads. 1165 1166 // If either of these functions is a K&R-style function (no 1167 // prototype), then we consider them to have matching signatures. 1168 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1169 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1170 return false; 1171 1172 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1173 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1174 1175 // The signature of a function includes the types of its 1176 // parameters (C++ 1.3.10), which includes the presence or absence 1177 // of the ellipsis; see C++ DR 357). 1178 if (OldQType != NewQType && 1179 (OldType->getNumParams() != NewType->getNumParams() || 1180 OldType->isVariadic() != NewType->isVariadic() || 1181 !FunctionParamTypesAreEqual(OldType, NewType))) 1182 return true; 1183 1184 // C++ [temp.over.link]p4: 1185 // The signature of a function template consists of its function 1186 // signature, its return type and its template parameter list. The names 1187 // of the template parameters are significant only for establishing the 1188 // relationship between the template parameters and the rest of the 1189 // signature. 1190 // 1191 // We check the return type and template parameter lists for function 1192 // templates first; the remaining checks follow. 1193 // 1194 // However, we don't consider either of these when deciding whether 1195 // a member introduced by a shadow declaration is hidden. 1196 if (!UseMemberUsingDeclRules && NewTemplate && 1197 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1198 OldTemplate->getTemplateParameters(), 1199 false, TPL_TemplateMatch) || 1200 !Context.hasSameType(Old->getDeclaredReturnType(), 1201 New->getDeclaredReturnType()))) 1202 return true; 1203 1204 // If the function is a class member, its signature includes the 1205 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1206 // 1207 // As part of this, also check whether one of the member functions 1208 // is static, in which case they are not overloads (C++ 1209 // 13.1p2). While not part of the definition of the signature, 1210 // this check is important to determine whether these functions 1211 // can be overloaded. 1212 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1213 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1214 if (OldMethod && NewMethod && 1215 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1216 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1217 if (!UseMemberUsingDeclRules && 1218 (OldMethod->getRefQualifier() == RQ_None || 1219 NewMethod->getRefQualifier() == RQ_None)) { 1220 // C++0x [over.load]p2: 1221 // - Member function declarations with the same name and the same 1222 // parameter-type-list as well as member function template 1223 // declarations with the same name, the same parameter-type-list, and 1224 // the same template parameter lists cannot be overloaded if any of 1225 // them, but not all, have a ref-qualifier (8.3.5). 1226 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1227 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1228 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1229 } 1230 return true; 1231 } 1232 1233 // We may not have applied the implicit const for a constexpr member 1234 // function yet (because we haven't yet resolved whether this is a static 1235 // or non-static member function). Add it now, on the assumption that this 1236 // is a redeclaration of OldMethod. 1237 auto OldQuals = OldMethod->getMethodQualifiers(); 1238 auto NewQuals = NewMethod->getMethodQualifiers(); 1239 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1240 !isa<CXXConstructorDecl>(NewMethod)) 1241 NewQuals.addConst(); 1242 // We do not allow overloading based off of '__restrict'. 1243 OldQuals.removeRestrict(); 1244 NewQuals.removeRestrict(); 1245 if (OldQuals != NewQuals) 1246 return true; 1247 } 1248 1249 // Though pass_object_size is placed on parameters and takes an argument, we 1250 // consider it to be a function-level modifier for the sake of function 1251 // identity. Either the function has one or more parameters with 1252 // pass_object_size or it doesn't. 1253 if (functionHasPassObjectSizeParams(New) != 1254 functionHasPassObjectSizeParams(Old)) 1255 return true; 1256 1257 // enable_if attributes are an order-sensitive part of the signature. 1258 for (specific_attr_iterator<EnableIfAttr> 1259 NewI = New->specific_attr_begin<EnableIfAttr>(), 1260 NewE = New->specific_attr_end<EnableIfAttr>(), 1261 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1262 OldE = Old->specific_attr_end<EnableIfAttr>(); 1263 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1264 if (NewI == NewE || OldI == OldE) 1265 return true; 1266 llvm::FoldingSetNodeID NewID, OldID; 1267 NewI->getCond()->Profile(NewID, Context, true); 1268 OldI->getCond()->Profile(OldID, Context, true); 1269 if (NewID != OldID) 1270 return true; 1271 } 1272 1273 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1274 // Don't allow overloading of destructors. (In theory we could, but it 1275 // would be a giant change to clang.) 1276 if (isa<CXXDestructorDecl>(New)) 1277 return false; 1278 1279 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1280 OldTarget = IdentifyCUDATarget(Old); 1281 if (NewTarget == CFT_InvalidTarget) 1282 return false; 1283 1284 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1285 1286 // Allow overloading of functions with same signature and different CUDA 1287 // target attributes. 1288 return NewTarget != OldTarget; 1289 } 1290 1291 // TODO: Concepts: Check function trailing requires clauses here. 1292 1293 // The signatures match; this is not an overload. 1294 return false; 1295 } 1296 1297 /// Tries a user-defined conversion from From to ToType. 1298 /// 1299 /// Produces an implicit conversion sequence for when a standard conversion 1300 /// is not an option. See TryImplicitConversion for more information. 1301 static ImplicitConversionSequence 1302 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1303 bool SuppressUserConversions, 1304 bool AllowExplicit, 1305 bool InOverloadResolution, 1306 bool CStyle, 1307 bool AllowObjCWritebackConversion, 1308 bool AllowObjCConversionOnExplicit) { 1309 ImplicitConversionSequence ICS; 1310 1311 if (SuppressUserConversions) { 1312 // We're not in the case above, so there is no conversion that 1313 // we can perform. 1314 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1315 return ICS; 1316 } 1317 1318 // Attempt user-defined conversion. 1319 OverloadCandidateSet Conversions(From->getExprLoc(), 1320 OverloadCandidateSet::CSK_Normal); 1321 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1322 Conversions, AllowExplicit, 1323 AllowObjCConversionOnExplicit)) { 1324 case OR_Success: 1325 case OR_Deleted: 1326 ICS.setUserDefined(); 1327 // C++ [over.ics.user]p4: 1328 // A conversion of an expression of class type to the same class 1329 // type is given Exact Match rank, and a conversion of an 1330 // expression of class type to a base class of that type is 1331 // given Conversion rank, in spite of the fact that a copy 1332 // constructor (i.e., a user-defined conversion function) is 1333 // called for those cases. 1334 if (CXXConstructorDecl *Constructor 1335 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1336 QualType FromCanon 1337 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1338 QualType ToCanon 1339 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1340 if (Constructor->isCopyConstructor() && 1341 (FromCanon == ToCanon || 1342 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1343 // Turn this into a "standard" conversion sequence, so that it 1344 // gets ranked with standard conversion sequences. 1345 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1346 ICS.setStandard(); 1347 ICS.Standard.setAsIdentityConversion(); 1348 ICS.Standard.setFromType(From->getType()); 1349 ICS.Standard.setAllToTypes(ToType); 1350 ICS.Standard.CopyConstructor = Constructor; 1351 ICS.Standard.FoundCopyConstructor = Found; 1352 if (ToCanon != FromCanon) 1353 ICS.Standard.Second = ICK_Derived_To_Base; 1354 } 1355 } 1356 break; 1357 1358 case OR_Ambiguous: 1359 ICS.setAmbiguous(); 1360 ICS.Ambiguous.setFromType(From->getType()); 1361 ICS.Ambiguous.setToType(ToType); 1362 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1363 Cand != Conversions.end(); ++Cand) 1364 if (Cand->Best) 1365 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1366 break; 1367 1368 // Fall through. 1369 case OR_No_Viable_Function: 1370 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1371 break; 1372 } 1373 1374 return ICS; 1375 } 1376 1377 /// TryImplicitConversion - Attempt to perform an implicit conversion 1378 /// from the given expression (Expr) to the given type (ToType). This 1379 /// function returns an implicit conversion sequence that can be used 1380 /// to perform the initialization. Given 1381 /// 1382 /// void f(float f); 1383 /// void g(int i) { f(i); } 1384 /// 1385 /// this routine would produce an implicit conversion sequence to 1386 /// describe the initialization of f from i, which will be a standard 1387 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1388 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1389 // 1390 /// Note that this routine only determines how the conversion can be 1391 /// performed; it does not actually perform the conversion. As such, 1392 /// it will not produce any diagnostics if no conversion is available, 1393 /// but will instead return an implicit conversion sequence of kind 1394 /// "BadConversion". 1395 /// 1396 /// If @p SuppressUserConversions, then user-defined conversions are 1397 /// not permitted. 1398 /// If @p AllowExplicit, then explicit user-defined conversions are 1399 /// permitted. 1400 /// 1401 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1402 /// writeback conversion, which allows __autoreleasing id* parameters to 1403 /// be initialized with __strong id* or __weak id* arguments. 1404 static ImplicitConversionSequence 1405 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1406 bool SuppressUserConversions, 1407 bool AllowExplicit, 1408 bool InOverloadResolution, 1409 bool CStyle, 1410 bool AllowObjCWritebackConversion, 1411 bool AllowObjCConversionOnExplicit) { 1412 ImplicitConversionSequence ICS; 1413 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1414 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1415 ICS.setStandard(); 1416 return ICS; 1417 } 1418 1419 if (!S.getLangOpts().CPlusPlus) { 1420 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1421 return ICS; 1422 } 1423 1424 // C++ [over.ics.user]p4: 1425 // A conversion of an expression of class type to the same class 1426 // type is given Exact Match rank, and a conversion of an 1427 // expression of class type to a base class of that type is 1428 // given Conversion rank, in spite of the fact that a copy/move 1429 // constructor (i.e., a user-defined conversion function) is 1430 // called for those cases. 1431 QualType FromType = From->getType(); 1432 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1433 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1434 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1435 ICS.setStandard(); 1436 ICS.Standard.setAsIdentityConversion(); 1437 ICS.Standard.setFromType(FromType); 1438 ICS.Standard.setAllToTypes(ToType); 1439 1440 // We don't actually check at this point whether there is a valid 1441 // copy/move constructor, since overloading just assumes that it 1442 // exists. When we actually perform initialization, we'll find the 1443 // appropriate constructor to copy the returned object, if needed. 1444 ICS.Standard.CopyConstructor = nullptr; 1445 1446 // Determine whether this is considered a derived-to-base conversion. 1447 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1448 ICS.Standard.Second = ICK_Derived_To_Base; 1449 1450 return ICS; 1451 } 1452 1453 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1454 AllowExplicit, InOverloadResolution, CStyle, 1455 AllowObjCWritebackConversion, 1456 AllowObjCConversionOnExplicit); 1457 } 1458 1459 ImplicitConversionSequence 1460 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1461 bool SuppressUserConversions, 1462 bool AllowExplicit, 1463 bool InOverloadResolution, 1464 bool CStyle, 1465 bool AllowObjCWritebackConversion) { 1466 return ::TryImplicitConversion(*this, From, ToType, 1467 SuppressUserConversions, AllowExplicit, 1468 InOverloadResolution, CStyle, 1469 AllowObjCWritebackConversion, 1470 /*AllowObjCConversionOnExplicit=*/false); 1471 } 1472 1473 /// PerformImplicitConversion - Perform an implicit conversion of the 1474 /// expression From to the type ToType. Returns the 1475 /// converted expression. Flavor is the kind of conversion we're 1476 /// performing, used in the error message. If @p AllowExplicit, 1477 /// explicit user-defined conversions are permitted. 1478 ExprResult 1479 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1480 AssignmentAction Action, bool AllowExplicit) { 1481 ImplicitConversionSequence ICS; 1482 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1483 } 1484 1485 ExprResult 1486 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1487 AssignmentAction Action, bool AllowExplicit, 1488 ImplicitConversionSequence& ICS) { 1489 if (checkPlaceholderForOverload(*this, From)) 1490 return ExprError(); 1491 1492 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1493 bool AllowObjCWritebackConversion 1494 = getLangOpts().ObjCAutoRefCount && 1495 (Action == AA_Passing || Action == AA_Sending); 1496 if (getLangOpts().ObjC) 1497 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1498 From->getType(), From); 1499 ICS = ::TryImplicitConversion(*this, From, ToType, 1500 /*SuppressUserConversions=*/false, 1501 AllowExplicit, 1502 /*InOverloadResolution=*/false, 1503 /*CStyle=*/false, 1504 AllowObjCWritebackConversion, 1505 /*AllowObjCConversionOnExplicit=*/false); 1506 return PerformImplicitConversion(From, ToType, ICS, Action); 1507 } 1508 1509 /// Determine whether the conversion from FromType to ToType is a valid 1510 /// conversion that strips "noexcept" or "noreturn" off the nested function 1511 /// type. 1512 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1513 QualType &ResultTy) { 1514 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1515 return false; 1516 1517 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1518 // or F(t noexcept) -> F(t) 1519 // where F adds one of the following at most once: 1520 // - a pointer 1521 // - a member pointer 1522 // - a block pointer 1523 // Changes here need matching changes in FindCompositePointerType. 1524 CanQualType CanTo = Context.getCanonicalType(ToType); 1525 CanQualType CanFrom = Context.getCanonicalType(FromType); 1526 Type::TypeClass TyClass = CanTo->getTypeClass(); 1527 if (TyClass != CanFrom->getTypeClass()) return false; 1528 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1529 if (TyClass == Type::Pointer) { 1530 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1531 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1532 } else if (TyClass == Type::BlockPointer) { 1533 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1534 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1535 } else if (TyClass == Type::MemberPointer) { 1536 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1537 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1538 // A function pointer conversion cannot change the class of the function. 1539 if (ToMPT->getClass() != FromMPT->getClass()) 1540 return false; 1541 CanTo = ToMPT->getPointeeType(); 1542 CanFrom = FromMPT->getPointeeType(); 1543 } else { 1544 return false; 1545 } 1546 1547 TyClass = CanTo->getTypeClass(); 1548 if (TyClass != CanFrom->getTypeClass()) return false; 1549 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1550 return false; 1551 } 1552 1553 const auto *FromFn = cast<FunctionType>(CanFrom); 1554 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1555 1556 const auto *ToFn = cast<FunctionType>(CanTo); 1557 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1558 1559 bool Changed = false; 1560 1561 // Drop 'noreturn' if not present in target type. 1562 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1563 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1564 Changed = true; 1565 } 1566 1567 // Drop 'noexcept' if not present in target type. 1568 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1569 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1570 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1571 FromFn = cast<FunctionType>( 1572 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1573 EST_None) 1574 .getTypePtr()); 1575 Changed = true; 1576 } 1577 1578 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1579 // only if the ExtParameterInfo lists of the two function prototypes can be 1580 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1581 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1582 bool CanUseToFPT, CanUseFromFPT; 1583 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1584 CanUseFromFPT, NewParamInfos) && 1585 CanUseToFPT && !CanUseFromFPT) { 1586 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1587 ExtInfo.ExtParameterInfos = 1588 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1589 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1590 FromFPT->getParamTypes(), ExtInfo); 1591 FromFn = QT->getAs<FunctionType>(); 1592 Changed = true; 1593 } 1594 } 1595 1596 if (!Changed) 1597 return false; 1598 1599 assert(QualType(FromFn, 0).isCanonical()); 1600 if (QualType(FromFn, 0) != CanTo) return false; 1601 1602 ResultTy = ToType; 1603 return true; 1604 } 1605 1606 /// Determine whether the conversion from FromType to ToType is a valid 1607 /// vector conversion. 1608 /// 1609 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1610 /// conversion. 1611 static bool IsVectorConversion(Sema &S, QualType FromType, 1612 QualType ToType, ImplicitConversionKind &ICK) { 1613 // We need at least one of these types to be a vector type to have a vector 1614 // conversion. 1615 if (!ToType->isVectorType() && !FromType->isVectorType()) 1616 return false; 1617 1618 // Identical types require no conversions. 1619 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1620 return false; 1621 1622 // There are no conversions between extended vector types, only identity. 1623 if (ToType->isExtVectorType()) { 1624 // There are no conversions between extended vector types other than the 1625 // identity conversion. 1626 if (FromType->isExtVectorType()) 1627 return false; 1628 1629 // Vector splat from any arithmetic type to a vector. 1630 if (FromType->isArithmeticType()) { 1631 ICK = ICK_Vector_Splat; 1632 return true; 1633 } 1634 } 1635 1636 // We can perform the conversion between vector types in the following cases: 1637 // 1)vector types are equivalent AltiVec and GCC vector types 1638 // 2)lax vector conversions are permitted and the vector types are of the 1639 // same size 1640 if (ToType->isVectorType() && FromType->isVectorType()) { 1641 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1642 S.isLaxVectorConversion(FromType, ToType)) { 1643 ICK = ICK_Vector_Conversion; 1644 return true; 1645 } 1646 } 1647 1648 return false; 1649 } 1650 1651 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1652 bool InOverloadResolution, 1653 StandardConversionSequence &SCS, 1654 bool CStyle); 1655 1656 /// IsStandardConversion - Determines whether there is a standard 1657 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1658 /// expression From to the type ToType. Standard conversion sequences 1659 /// only consider non-class types; for conversions that involve class 1660 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1661 /// contain the standard conversion sequence required to perform this 1662 /// conversion and this routine will return true. Otherwise, this 1663 /// routine will return false and the value of SCS is unspecified. 1664 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1665 bool InOverloadResolution, 1666 StandardConversionSequence &SCS, 1667 bool CStyle, 1668 bool AllowObjCWritebackConversion) { 1669 QualType FromType = From->getType(); 1670 1671 // Standard conversions (C++ [conv]) 1672 SCS.setAsIdentityConversion(); 1673 SCS.IncompatibleObjC = false; 1674 SCS.setFromType(FromType); 1675 SCS.CopyConstructor = nullptr; 1676 1677 // There are no standard conversions for class types in C++, so 1678 // abort early. When overloading in C, however, we do permit them. 1679 if (S.getLangOpts().CPlusPlus && 1680 (FromType->isRecordType() || ToType->isRecordType())) 1681 return false; 1682 1683 // The first conversion can be an lvalue-to-rvalue conversion, 1684 // array-to-pointer conversion, or function-to-pointer conversion 1685 // (C++ 4p1). 1686 1687 if (FromType == S.Context.OverloadTy) { 1688 DeclAccessPair AccessPair; 1689 if (FunctionDecl *Fn 1690 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1691 AccessPair)) { 1692 // We were able to resolve the address of the overloaded function, 1693 // so we can convert to the type of that function. 1694 FromType = Fn->getType(); 1695 SCS.setFromType(FromType); 1696 1697 // we can sometimes resolve &foo<int> regardless of ToType, so check 1698 // if the type matches (identity) or we are converting to bool 1699 if (!S.Context.hasSameUnqualifiedType( 1700 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1701 QualType resultTy; 1702 // if the function type matches except for [[noreturn]], it's ok 1703 if (!S.IsFunctionConversion(FromType, 1704 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1705 // otherwise, only a boolean conversion is standard 1706 if (!ToType->isBooleanType()) 1707 return false; 1708 } 1709 1710 // Check if the "from" expression is taking the address of an overloaded 1711 // function and recompute the FromType accordingly. Take advantage of the 1712 // fact that non-static member functions *must* have such an address-of 1713 // expression. 1714 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1715 if (Method && !Method->isStatic()) { 1716 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1717 "Non-unary operator on non-static member address"); 1718 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1719 == UO_AddrOf && 1720 "Non-address-of operator on non-static member address"); 1721 const Type *ClassType 1722 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1723 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1724 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1725 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1726 UO_AddrOf && 1727 "Non-address-of operator for overloaded function expression"); 1728 FromType = S.Context.getPointerType(FromType); 1729 } 1730 1731 // Check that we've computed the proper type after overload resolution. 1732 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1733 // be calling it from within an NDEBUG block. 1734 assert(S.Context.hasSameType( 1735 FromType, 1736 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1737 } else { 1738 return false; 1739 } 1740 } 1741 // Lvalue-to-rvalue conversion (C++11 4.1): 1742 // A glvalue (3.10) of a non-function, non-array type T can 1743 // be converted to a prvalue. 1744 bool argIsLValue = From->isGLValue(); 1745 if (argIsLValue && 1746 !FromType->isFunctionType() && !FromType->isArrayType() && 1747 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1748 SCS.First = ICK_Lvalue_To_Rvalue; 1749 1750 // C11 6.3.2.1p2: 1751 // ... if the lvalue has atomic type, the value has the non-atomic version 1752 // of the type of the lvalue ... 1753 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1754 FromType = Atomic->getValueType(); 1755 1756 // If T is a non-class type, the type of the rvalue is the 1757 // cv-unqualified version of T. Otherwise, the type of the rvalue 1758 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1759 // just strip the qualifiers because they don't matter. 1760 FromType = FromType.getUnqualifiedType(); 1761 } else if (FromType->isArrayType()) { 1762 // Array-to-pointer conversion (C++ 4.2) 1763 SCS.First = ICK_Array_To_Pointer; 1764 1765 // An lvalue or rvalue of type "array of N T" or "array of unknown 1766 // bound of T" can be converted to an rvalue of type "pointer to 1767 // T" (C++ 4.2p1). 1768 FromType = S.Context.getArrayDecayedType(FromType); 1769 1770 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1771 // This conversion is deprecated in C++03 (D.4) 1772 SCS.DeprecatedStringLiteralToCharPtr = true; 1773 1774 // For the purpose of ranking in overload resolution 1775 // (13.3.3.1.1), this conversion is considered an 1776 // array-to-pointer conversion followed by a qualification 1777 // conversion (4.4). (C++ 4.2p2) 1778 SCS.Second = ICK_Identity; 1779 SCS.Third = ICK_Qualification; 1780 SCS.QualificationIncludesObjCLifetime = false; 1781 SCS.setAllToTypes(FromType); 1782 return true; 1783 } 1784 } else if (FromType->isFunctionType() && argIsLValue) { 1785 // Function-to-pointer conversion (C++ 4.3). 1786 SCS.First = ICK_Function_To_Pointer; 1787 1788 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1789 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1790 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1791 return false; 1792 1793 // An lvalue of function type T can be converted to an rvalue of 1794 // type "pointer to T." The result is a pointer to the 1795 // function. (C++ 4.3p1). 1796 FromType = S.Context.getPointerType(FromType); 1797 } else { 1798 // We don't require any conversions for the first step. 1799 SCS.First = ICK_Identity; 1800 } 1801 SCS.setToType(0, FromType); 1802 1803 // The second conversion can be an integral promotion, floating 1804 // point promotion, integral conversion, floating point conversion, 1805 // floating-integral conversion, pointer conversion, 1806 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1807 // For overloading in C, this can also be a "compatible-type" 1808 // conversion. 1809 bool IncompatibleObjC = false; 1810 ImplicitConversionKind SecondICK = ICK_Identity; 1811 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1812 // The unqualified versions of the types are the same: there's no 1813 // conversion to do. 1814 SCS.Second = ICK_Identity; 1815 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1816 // Integral promotion (C++ 4.5). 1817 SCS.Second = ICK_Integral_Promotion; 1818 FromType = ToType.getUnqualifiedType(); 1819 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1820 // Floating point promotion (C++ 4.6). 1821 SCS.Second = ICK_Floating_Promotion; 1822 FromType = ToType.getUnqualifiedType(); 1823 } else if (S.IsComplexPromotion(FromType, ToType)) { 1824 // Complex promotion (Clang extension) 1825 SCS.Second = ICK_Complex_Promotion; 1826 FromType = ToType.getUnqualifiedType(); 1827 } else if (ToType->isBooleanType() && 1828 (FromType->isArithmeticType() || 1829 FromType->isAnyPointerType() || 1830 FromType->isBlockPointerType() || 1831 FromType->isMemberPointerType() || 1832 FromType->isNullPtrType())) { 1833 // Boolean conversions (C++ 4.12). 1834 SCS.Second = ICK_Boolean_Conversion; 1835 FromType = S.Context.BoolTy; 1836 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1837 ToType->isIntegralType(S.Context)) { 1838 // Integral conversions (C++ 4.7). 1839 SCS.Second = ICK_Integral_Conversion; 1840 FromType = ToType.getUnqualifiedType(); 1841 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1842 // Complex conversions (C99 6.3.1.6) 1843 SCS.Second = ICK_Complex_Conversion; 1844 FromType = ToType.getUnqualifiedType(); 1845 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1846 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1847 // Complex-real conversions (C99 6.3.1.7) 1848 SCS.Second = ICK_Complex_Real; 1849 FromType = ToType.getUnqualifiedType(); 1850 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1851 // FIXME: disable conversions between long double and __float128 if 1852 // their representation is different until there is back end support 1853 // We of course allow this conversion if long double is really double. 1854 if (&S.Context.getFloatTypeSemantics(FromType) != 1855 &S.Context.getFloatTypeSemantics(ToType)) { 1856 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1857 ToType == S.Context.LongDoubleTy) || 1858 (FromType == S.Context.LongDoubleTy && 1859 ToType == S.Context.Float128Ty)); 1860 if (Float128AndLongDouble && 1861 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1862 &llvm::APFloat::PPCDoubleDouble())) 1863 return false; 1864 } 1865 // Floating point conversions (C++ 4.8). 1866 SCS.Second = ICK_Floating_Conversion; 1867 FromType = ToType.getUnqualifiedType(); 1868 } else if ((FromType->isRealFloatingType() && 1869 ToType->isIntegralType(S.Context)) || 1870 (FromType->isIntegralOrUnscopedEnumerationType() && 1871 ToType->isRealFloatingType())) { 1872 // Floating-integral conversions (C++ 4.9). 1873 SCS.Second = ICK_Floating_Integral; 1874 FromType = ToType.getUnqualifiedType(); 1875 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1876 SCS.Second = ICK_Block_Pointer_Conversion; 1877 } else if (AllowObjCWritebackConversion && 1878 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1879 SCS.Second = ICK_Writeback_Conversion; 1880 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1881 FromType, IncompatibleObjC)) { 1882 // Pointer conversions (C++ 4.10). 1883 SCS.Second = ICK_Pointer_Conversion; 1884 SCS.IncompatibleObjC = IncompatibleObjC; 1885 FromType = FromType.getUnqualifiedType(); 1886 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1887 InOverloadResolution, FromType)) { 1888 // Pointer to member conversions (4.11). 1889 SCS.Second = ICK_Pointer_Member; 1890 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1891 SCS.Second = SecondICK; 1892 FromType = ToType.getUnqualifiedType(); 1893 } else if (!S.getLangOpts().CPlusPlus && 1894 S.Context.typesAreCompatible(ToType, FromType)) { 1895 // Compatible conversions (Clang extension for C function overloading) 1896 SCS.Second = ICK_Compatible_Conversion; 1897 FromType = ToType.getUnqualifiedType(); 1898 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1899 InOverloadResolution, 1900 SCS, CStyle)) { 1901 SCS.Second = ICK_TransparentUnionConversion; 1902 FromType = ToType; 1903 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1904 CStyle)) { 1905 // tryAtomicConversion has updated the standard conversion sequence 1906 // appropriately. 1907 return true; 1908 } else if (ToType->isEventT() && 1909 From->isIntegerConstantExpr(S.getASTContext()) && 1910 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1911 SCS.Second = ICK_Zero_Event_Conversion; 1912 FromType = ToType; 1913 } else if (ToType->isQueueT() && 1914 From->isIntegerConstantExpr(S.getASTContext()) && 1915 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1916 SCS.Second = ICK_Zero_Queue_Conversion; 1917 FromType = ToType; 1918 } else if (ToType->isSamplerT() && 1919 From->isIntegerConstantExpr(S.getASTContext())) { 1920 SCS.Second = ICK_Compatible_Conversion; 1921 FromType = ToType; 1922 } else { 1923 // No second conversion required. 1924 SCS.Second = ICK_Identity; 1925 } 1926 SCS.setToType(1, FromType); 1927 1928 // The third conversion can be a function pointer conversion or a 1929 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1930 bool ObjCLifetimeConversion; 1931 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1932 // Function pointer conversions (removing 'noexcept') including removal of 1933 // 'noreturn' (Clang extension). 1934 SCS.Third = ICK_Function_Conversion; 1935 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1936 ObjCLifetimeConversion)) { 1937 SCS.Third = ICK_Qualification; 1938 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1939 FromType = ToType; 1940 } else { 1941 // No conversion required 1942 SCS.Third = ICK_Identity; 1943 } 1944 1945 // C++ [over.best.ics]p6: 1946 // [...] Any difference in top-level cv-qualification is 1947 // subsumed by the initialization itself and does not constitute 1948 // a conversion. [...] 1949 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1950 QualType CanonTo = S.Context.getCanonicalType(ToType); 1951 if (CanonFrom.getLocalUnqualifiedType() 1952 == CanonTo.getLocalUnqualifiedType() && 1953 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1954 FromType = ToType; 1955 CanonFrom = CanonTo; 1956 } 1957 1958 SCS.setToType(2, FromType); 1959 1960 if (CanonFrom == CanonTo) 1961 return true; 1962 1963 // If we have not converted the argument type to the parameter type, 1964 // this is a bad conversion sequence, unless we're resolving an overload in C. 1965 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1966 return false; 1967 1968 ExprResult ER = ExprResult{From}; 1969 Sema::AssignConvertType Conv = 1970 S.CheckSingleAssignmentConstraints(ToType, ER, 1971 /*Diagnose=*/false, 1972 /*DiagnoseCFAudited=*/false, 1973 /*ConvertRHS=*/false); 1974 ImplicitConversionKind SecondConv; 1975 switch (Conv) { 1976 case Sema::Compatible: 1977 SecondConv = ICK_C_Only_Conversion; 1978 break; 1979 // For our purposes, discarding qualifiers is just as bad as using an 1980 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1981 // qualifiers, as well. 1982 case Sema::CompatiblePointerDiscardsQualifiers: 1983 case Sema::IncompatiblePointer: 1984 case Sema::IncompatiblePointerSign: 1985 SecondConv = ICK_Incompatible_Pointer_Conversion; 1986 break; 1987 default: 1988 return false; 1989 } 1990 1991 // First can only be an lvalue conversion, so we pretend that this was the 1992 // second conversion. First should already be valid from earlier in the 1993 // function. 1994 SCS.Second = SecondConv; 1995 SCS.setToType(1, ToType); 1996 1997 // Third is Identity, because Second should rank us worse than any other 1998 // conversion. This could also be ICK_Qualification, but it's simpler to just 1999 // lump everything in with the second conversion, and we don't gain anything 2000 // from making this ICK_Qualification. 2001 SCS.Third = ICK_Identity; 2002 SCS.setToType(2, ToType); 2003 return true; 2004 } 2005 2006 static bool 2007 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2008 QualType &ToType, 2009 bool InOverloadResolution, 2010 StandardConversionSequence &SCS, 2011 bool CStyle) { 2012 2013 const RecordType *UT = ToType->getAsUnionType(); 2014 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2015 return false; 2016 // The field to initialize within the transparent union. 2017 RecordDecl *UD = UT->getDecl(); 2018 // It's compatible if the expression matches any of the fields. 2019 for (const auto *it : UD->fields()) { 2020 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2021 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2022 ToType = it->getType(); 2023 return true; 2024 } 2025 } 2026 return false; 2027 } 2028 2029 /// IsIntegralPromotion - Determines whether the conversion from the 2030 /// expression From (whose potentially-adjusted type is FromType) to 2031 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2032 /// sets PromotedType to the promoted type. 2033 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2034 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2035 // All integers are built-in. 2036 if (!To) { 2037 return false; 2038 } 2039 2040 // An rvalue of type char, signed char, unsigned char, short int, or 2041 // unsigned short int can be converted to an rvalue of type int if 2042 // int can represent all the values of the source type; otherwise, 2043 // the source rvalue can be converted to an rvalue of type unsigned 2044 // int (C++ 4.5p1). 2045 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2046 !FromType->isEnumeralType()) { 2047 if (// We can promote any signed, promotable integer type to an int 2048 (FromType->isSignedIntegerType() || 2049 // We can promote any unsigned integer type whose size is 2050 // less than int to an int. 2051 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2052 return To->getKind() == BuiltinType::Int; 2053 } 2054 2055 return To->getKind() == BuiltinType::UInt; 2056 } 2057 2058 // C++11 [conv.prom]p3: 2059 // A prvalue of an unscoped enumeration type whose underlying type is not 2060 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2061 // following types that can represent all the values of the enumeration 2062 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2063 // unsigned int, long int, unsigned long int, long long int, or unsigned 2064 // long long int. If none of the types in that list can represent all the 2065 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2066 // type can be converted to an rvalue a prvalue of the extended integer type 2067 // with lowest integer conversion rank (4.13) greater than the rank of long 2068 // long in which all the values of the enumeration can be represented. If 2069 // there are two such extended types, the signed one is chosen. 2070 // C++11 [conv.prom]p4: 2071 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2072 // can be converted to a prvalue of its underlying type. Moreover, if 2073 // integral promotion can be applied to its underlying type, a prvalue of an 2074 // unscoped enumeration type whose underlying type is fixed can also be 2075 // converted to a prvalue of the promoted underlying type. 2076 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2077 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2078 // provided for a scoped enumeration. 2079 if (FromEnumType->getDecl()->isScoped()) 2080 return false; 2081 2082 // We can perform an integral promotion to the underlying type of the enum, 2083 // even if that's not the promoted type. Note that the check for promoting 2084 // the underlying type is based on the type alone, and does not consider 2085 // the bitfield-ness of the actual source expression. 2086 if (FromEnumType->getDecl()->isFixed()) { 2087 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2088 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2089 IsIntegralPromotion(nullptr, Underlying, ToType); 2090 } 2091 2092 // We have already pre-calculated the promotion type, so this is trivial. 2093 if (ToType->isIntegerType() && 2094 isCompleteType(From->getBeginLoc(), FromType)) 2095 return Context.hasSameUnqualifiedType( 2096 ToType, FromEnumType->getDecl()->getPromotionType()); 2097 2098 // C++ [conv.prom]p5: 2099 // If the bit-field has an enumerated type, it is treated as any other 2100 // value of that type for promotion purposes. 2101 // 2102 // ... so do not fall through into the bit-field checks below in C++. 2103 if (getLangOpts().CPlusPlus) 2104 return false; 2105 } 2106 2107 // C++0x [conv.prom]p2: 2108 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2109 // to an rvalue a prvalue of the first of the following types that can 2110 // represent all the values of its underlying type: int, unsigned int, 2111 // long int, unsigned long int, long long int, or unsigned long long int. 2112 // If none of the types in that list can represent all the values of its 2113 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2114 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2115 // type. 2116 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2117 ToType->isIntegerType()) { 2118 // Determine whether the type we're converting from is signed or 2119 // unsigned. 2120 bool FromIsSigned = FromType->isSignedIntegerType(); 2121 uint64_t FromSize = Context.getTypeSize(FromType); 2122 2123 // The types we'll try to promote to, in the appropriate 2124 // order. Try each of these types. 2125 QualType PromoteTypes[6] = { 2126 Context.IntTy, Context.UnsignedIntTy, 2127 Context.LongTy, Context.UnsignedLongTy , 2128 Context.LongLongTy, Context.UnsignedLongLongTy 2129 }; 2130 for (int Idx = 0; Idx < 6; ++Idx) { 2131 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2132 if (FromSize < ToSize || 2133 (FromSize == ToSize && 2134 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2135 // We found the type that we can promote to. If this is the 2136 // type we wanted, we have a promotion. Otherwise, no 2137 // promotion. 2138 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2139 } 2140 } 2141 } 2142 2143 // An rvalue for an integral bit-field (9.6) can be converted to an 2144 // rvalue of type int if int can represent all the values of the 2145 // bit-field; otherwise, it can be converted to unsigned int if 2146 // unsigned int can represent all the values of the bit-field. If 2147 // the bit-field is larger yet, no integral promotion applies to 2148 // it. If the bit-field has an enumerated type, it is treated as any 2149 // other value of that type for promotion purposes (C++ 4.5p3). 2150 // FIXME: We should delay checking of bit-fields until we actually perform the 2151 // conversion. 2152 // 2153 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2154 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2155 // bit-fields and those whose underlying type is larger than int) for GCC 2156 // compatibility. 2157 if (From) { 2158 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2159 llvm::APSInt BitWidth; 2160 if (FromType->isIntegralType(Context) && 2161 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2162 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2163 ToSize = Context.getTypeSize(ToType); 2164 2165 // Are we promoting to an int from a bitfield that fits in an int? 2166 if (BitWidth < ToSize || 2167 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2168 return To->getKind() == BuiltinType::Int; 2169 } 2170 2171 // Are we promoting to an unsigned int from an unsigned bitfield 2172 // that fits into an unsigned int? 2173 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2174 return To->getKind() == BuiltinType::UInt; 2175 } 2176 2177 return false; 2178 } 2179 } 2180 } 2181 2182 // An rvalue of type bool can be converted to an rvalue of type int, 2183 // with false becoming zero and true becoming one (C++ 4.5p4). 2184 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2185 return true; 2186 } 2187 2188 return false; 2189 } 2190 2191 /// IsFloatingPointPromotion - Determines whether the conversion from 2192 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2193 /// returns true and sets PromotedType to the promoted type. 2194 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2195 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2196 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2197 /// An rvalue of type float can be converted to an rvalue of type 2198 /// double. (C++ 4.6p1). 2199 if (FromBuiltin->getKind() == BuiltinType::Float && 2200 ToBuiltin->getKind() == BuiltinType::Double) 2201 return true; 2202 2203 // C99 6.3.1.5p1: 2204 // When a float is promoted to double or long double, or a 2205 // double is promoted to long double [...]. 2206 if (!getLangOpts().CPlusPlus && 2207 (FromBuiltin->getKind() == BuiltinType::Float || 2208 FromBuiltin->getKind() == BuiltinType::Double) && 2209 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2210 ToBuiltin->getKind() == BuiltinType::Float128)) 2211 return true; 2212 2213 // Half can be promoted to float. 2214 if (!getLangOpts().NativeHalfType && 2215 FromBuiltin->getKind() == BuiltinType::Half && 2216 ToBuiltin->getKind() == BuiltinType::Float) 2217 return true; 2218 } 2219 2220 return false; 2221 } 2222 2223 /// Determine if a conversion is a complex promotion. 2224 /// 2225 /// A complex promotion is defined as a complex -> complex conversion 2226 /// where the conversion between the underlying real types is a 2227 /// floating-point or integral promotion. 2228 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2229 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2230 if (!FromComplex) 2231 return false; 2232 2233 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2234 if (!ToComplex) 2235 return false; 2236 2237 return IsFloatingPointPromotion(FromComplex->getElementType(), 2238 ToComplex->getElementType()) || 2239 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2240 ToComplex->getElementType()); 2241 } 2242 2243 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2244 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2245 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2246 /// if non-empty, will be a pointer to ToType that may or may not have 2247 /// the right set of qualifiers on its pointee. 2248 /// 2249 static QualType 2250 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2251 QualType ToPointee, QualType ToType, 2252 ASTContext &Context, 2253 bool StripObjCLifetime = false) { 2254 assert((FromPtr->getTypeClass() == Type::Pointer || 2255 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2256 "Invalid similarly-qualified pointer type"); 2257 2258 /// Conversions to 'id' subsume cv-qualifier conversions. 2259 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2260 return ToType.getUnqualifiedType(); 2261 2262 QualType CanonFromPointee 2263 = Context.getCanonicalType(FromPtr->getPointeeType()); 2264 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2265 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2266 2267 if (StripObjCLifetime) 2268 Quals.removeObjCLifetime(); 2269 2270 // Exact qualifier match -> return the pointer type we're converting to. 2271 if (CanonToPointee.getLocalQualifiers() == Quals) { 2272 // ToType is exactly what we need. Return it. 2273 if (!ToType.isNull()) 2274 return ToType.getUnqualifiedType(); 2275 2276 // Build a pointer to ToPointee. It has the right qualifiers 2277 // already. 2278 if (isa<ObjCObjectPointerType>(ToType)) 2279 return Context.getObjCObjectPointerType(ToPointee); 2280 return Context.getPointerType(ToPointee); 2281 } 2282 2283 // Just build a canonical type that has the right qualifiers. 2284 QualType QualifiedCanonToPointee 2285 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2286 2287 if (isa<ObjCObjectPointerType>(ToType)) 2288 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2289 return Context.getPointerType(QualifiedCanonToPointee); 2290 } 2291 2292 static bool isNullPointerConstantForConversion(Expr *Expr, 2293 bool InOverloadResolution, 2294 ASTContext &Context) { 2295 // Handle value-dependent integral null pointer constants correctly. 2296 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2297 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2298 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2299 return !InOverloadResolution; 2300 2301 return Expr->isNullPointerConstant(Context, 2302 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2303 : Expr::NPC_ValueDependentIsNull); 2304 } 2305 2306 /// IsPointerConversion - Determines whether the conversion of the 2307 /// expression From, which has the (possibly adjusted) type FromType, 2308 /// can be converted to the type ToType via a pointer conversion (C++ 2309 /// 4.10). If so, returns true and places the converted type (that 2310 /// might differ from ToType in its cv-qualifiers at some level) into 2311 /// ConvertedType. 2312 /// 2313 /// This routine also supports conversions to and from block pointers 2314 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2315 /// pointers to interfaces. FIXME: Once we've determined the 2316 /// appropriate overloading rules for Objective-C, we may want to 2317 /// split the Objective-C checks into a different routine; however, 2318 /// GCC seems to consider all of these conversions to be pointer 2319 /// conversions, so for now they live here. IncompatibleObjC will be 2320 /// set if the conversion is an allowed Objective-C conversion that 2321 /// should result in a warning. 2322 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2323 bool InOverloadResolution, 2324 QualType& ConvertedType, 2325 bool &IncompatibleObjC) { 2326 IncompatibleObjC = false; 2327 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2328 IncompatibleObjC)) 2329 return true; 2330 2331 // Conversion from a null pointer constant to any Objective-C pointer type. 2332 if (ToType->isObjCObjectPointerType() && 2333 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2334 ConvertedType = ToType; 2335 return true; 2336 } 2337 2338 // Blocks: Block pointers can be converted to void*. 2339 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2340 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2341 ConvertedType = ToType; 2342 return true; 2343 } 2344 // Blocks: A null pointer constant can be converted to a block 2345 // pointer type. 2346 if (ToType->isBlockPointerType() && 2347 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2348 ConvertedType = ToType; 2349 return true; 2350 } 2351 2352 // If the left-hand-side is nullptr_t, the right side can be a null 2353 // pointer constant. 2354 if (ToType->isNullPtrType() && 2355 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2356 ConvertedType = ToType; 2357 return true; 2358 } 2359 2360 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2361 if (!ToTypePtr) 2362 return false; 2363 2364 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2365 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2366 ConvertedType = ToType; 2367 return true; 2368 } 2369 2370 // Beyond this point, both types need to be pointers 2371 // , including objective-c pointers. 2372 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2373 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2374 !getLangOpts().ObjCAutoRefCount) { 2375 ConvertedType = BuildSimilarlyQualifiedPointerType( 2376 FromType->getAs<ObjCObjectPointerType>(), 2377 ToPointeeType, 2378 ToType, Context); 2379 return true; 2380 } 2381 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2382 if (!FromTypePtr) 2383 return false; 2384 2385 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2386 2387 // If the unqualified pointee types are the same, this can't be a 2388 // pointer conversion, so don't do all of the work below. 2389 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2390 return false; 2391 2392 // An rvalue of type "pointer to cv T," where T is an object type, 2393 // can be converted to an rvalue of type "pointer to cv void" (C++ 2394 // 4.10p2). 2395 if (FromPointeeType->isIncompleteOrObjectType() && 2396 ToPointeeType->isVoidType()) { 2397 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2398 ToPointeeType, 2399 ToType, Context, 2400 /*StripObjCLifetime=*/true); 2401 return true; 2402 } 2403 2404 // MSVC allows implicit function to void* type conversion. 2405 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2406 ToPointeeType->isVoidType()) { 2407 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2408 ToPointeeType, 2409 ToType, Context); 2410 return true; 2411 } 2412 2413 // When we're overloading in C, we allow a special kind of pointer 2414 // conversion for compatible-but-not-identical pointee types. 2415 if (!getLangOpts().CPlusPlus && 2416 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2417 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2418 ToPointeeType, 2419 ToType, Context); 2420 return true; 2421 } 2422 2423 // C++ [conv.ptr]p3: 2424 // 2425 // An rvalue of type "pointer to cv D," where D is a class type, 2426 // can be converted to an rvalue of type "pointer to cv B," where 2427 // B is a base class (clause 10) of D. If B is an inaccessible 2428 // (clause 11) or ambiguous (10.2) base class of D, a program that 2429 // necessitates this conversion is ill-formed. The result of the 2430 // conversion is a pointer to the base class sub-object of the 2431 // derived class object. The null pointer value is converted to 2432 // the null pointer value of the destination type. 2433 // 2434 // Note that we do not check for ambiguity or inaccessibility 2435 // here. That is handled by CheckPointerConversion. 2436 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2437 ToPointeeType->isRecordType() && 2438 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2439 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2440 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2441 ToPointeeType, 2442 ToType, Context); 2443 return true; 2444 } 2445 2446 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2447 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2448 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2449 ToPointeeType, 2450 ToType, Context); 2451 return true; 2452 } 2453 2454 return false; 2455 } 2456 2457 /// Adopt the given qualifiers for the given type. 2458 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2459 Qualifiers TQs = T.getQualifiers(); 2460 2461 // Check whether qualifiers already match. 2462 if (TQs == Qs) 2463 return T; 2464 2465 if (Qs.compatiblyIncludes(TQs)) 2466 return Context.getQualifiedType(T, Qs); 2467 2468 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2469 } 2470 2471 /// isObjCPointerConversion - Determines whether this is an 2472 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2473 /// with the same arguments and return values. 2474 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2475 QualType& ConvertedType, 2476 bool &IncompatibleObjC) { 2477 if (!getLangOpts().ObjC) 2478 return false; 2479 2480 // The set of qualifiers on the type we're converting from. 2481 Qualifiers FromQualifiers = FromType.getQualifiers(); 2482 2483 // First, we handle all conversions on ObjC object pointer types. 2484 const ObjCObjectPointerType* ToObjCPtr = 2485 ToType->getAs<ObjCObjectPointerType>(); 2486 const ObjCObjectPointerType *FromObjCPtr = 2487 FromType->getAs<ObjCObjectPointerType>(); 2488 2489 if (ToObjCPtr && FromObjCPtr) { 2490 // If the pointee types are the same (ignoring qualifications), 2491 // then this is not a pointer conversion. 2492 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2493 FromObjCPtr->getPointeeType())) 2494 return false; 2495 2496 // Conversion between Objective-C pointers. 2497 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2498 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2499 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2500 if (getLangOpts().CPlusPlus && LHS && RHS && 2501 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2502 FromObjCPtr->getPointeeType())) 2503 return false; 2504 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2505 ToObjCPtr->getPointeeType(), 2506 ToType, Context); 2507 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2508 return true; 2509 } 2510 2511 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2512 // Okay: this is some kind of implicit downcast of Objective-C 2513 // interfaces, which is permitted. However, we're going to 2514 // complain about it. 2515 IncompatibleObjC = true; 2516 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2517 ToObjCPtr->getPointeeType(), 2518 ToType, Context); 2519 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2520 return true; 2521 } 2522 } 2523 // Beyond this point, both types need to be C pointers or block pointers. 2524 QualType ToPointeeType; 2525 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2526 ToPointeeType = ToCPtr->getPointeeType(); 2527 else if (const BlockPointerType *ToBlockPtr = 2528 ToType->getAs<BlockPointerType>()) { 2529 // Objective C++: We're able to convert from a pointer to any object 2530 // to a block pointer type. 2531 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2532 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2533 return true; 2534 } 2535 ToPointeeType = ToBlockPtr->getPointeeType(); 2536 } 2537 else if (FromType->getAs<BlockPointerType>() && 2538 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2539 // Objective C++: We're able to convert from a block pointer type to a 2540 // pointer to any object. 2541 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2542 return true; 2543 } 2544 else 2545 return false; 2546 2547 QualType FromPointeeType; 2548 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2549 FromPointeeType = FromCPtr->getPointeeType(); 2550 else if (const BlockPointerType *FromBlockPtr = 2551 FromType->getAs<BlockPointerType>()) 2552 FromPointeeType = FromBlockPtr->getPointeeType(); 2553 else 2554 return false; 2555 2556 // If we have pointers to pointers, recursively check whether this 2557 // is an Objective-C conversion. 2558 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2559 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2560 IncompatibleObjC)) { 2561 // We always complain about this conversion. 2562 IncompatibleObjC = true; 2563 ConvertedType = Context.getPointerType(ConvertedType); 2564 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2565 return true; 2566 } 2567 // Allow conversion of pointee being objective-c pointer to another one; 2568 // as in I* to id. 2569 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2570 ToPointeeType->getAs<ObjCObjectPointerType>() && 2571 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2572 IncompatibleObjC)) { 2573 2574 ConvertedType = Context.getPointerType(ConvertedType); 2575 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2576 return true; 2577 } 2578 2579 // If we have pointers to functions or blocks, check whether the only 2580 // differences in the argument and result types are in Objective-C 2581 // pointer conversions. If so, we permit the conversion (but 2582 // complain about it). 2583 const FunctionProtoType *FromFunctionType 2584 = FromPointeeType->getAs<FunctionProtoType>(); 2585 const FunctionProtoType *ToFunctionType 2586 = ToPointeeType->getAs<FunctionProtoType>(); 2587 if (FromFunctionType && ToFunctionType) { 2588 // If the function types are exactly the same, this isn't an 2589 // Objective-C pointer conversion. 2590 if (Context.getCanonicalType(FromPointeeType) 2591 == Context.getCanonicalType(ToPointeeType)) 2592 return false; 2593 2594 // Perform the quick checks that will tell us whether these 2595 // function types are obviously different. 2596 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2597 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2598 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2599 return false; 2600 2601 bool HasObjCConversion = false; 2602 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2603 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2604 // Okay, the types match exactly. Nothing to do. 2605 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2606 ToFunctionType->getReturnType(), 2607 ConvertedType, IncompatibleObjC)) { 2608 // Okay, we have an Objective-C pointer conversion. 2609 HasObjCConversion = true; 2610 } else { 2611 // Function types are too different. Abort. 2612 return false; 2613 } 2614 2615 // Check argument types. 2616 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2617 ArgIdx != NumArgs; ++ArgIdx) { 2618 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2619 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2620 if (Context.getCanonicalType(FromArgType) 2621 == Context.getCanonicalType(ToArgType)) { 2622 // Okay, the types match exactly. Nothing to do. 2623 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2624 ConvertedType, IncompatibleObjC)) { 2625 // Okay, we have an Objective-C pointer conversion. 2626 HasObjCConversion = true; 2627 } else { 2628 // Argument types are too different. Abort. 2629 return false; 2630 } 2631 } 2632 2633 if (HasObjCConversion) { 2634 // We had an Objective-C conversion. Allow this pointer 2635 // conversion, but complain about it. 2636 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2637 IncompatibleObjC = true; 2638 return true; 2639 } 2640 } 2641 2642 return false; 2643 } 2644 2645 /// Determine whether this is an Objective-C writeback conversion, 2646 /// used for parameter passing when performing automatic reference counting. 2647 /// 2648 /// \param FromType The type we're converting form. 2649 /// 2650 /// \param ToType The type we're converting to. 2651 /// 2652 /// \param ConvertedType The type that will be produced after applying 2653 /// this conversion. 2654 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2655 QualType &ConvertedType) { 2656 if (!getLangOpts().ObjCAutoRefCount || 2657 Context.hasSameUnqualifiedType(FromType, ToType)) 2658 return false; 2659 2660 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2661 QualType ToPointee; 2662 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2663 ToPointee = ToPointer->getPointeeType(); 2664 else 2665 return false; 2666 2667 Qualifiers ToQuals = ToPointee.getQualifiers(); 2668 if (!ToPointee->isObjCLifetimeType() || 2669 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2670 !ToQuals.withoutObjCLifetime().empty()) 2671 return false; 2672 2673 // Argument must be a pointer to __strong to __weak. 2674 QualType FromPointee; 2675 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2676 FromPointee = FromPointer->getPointeeType(); 2677 else 2678 return false; 2679 2680 Qualifiers FromQuals = FromPointee.getQualifiers(); 2681 if (!FromPointee->isObjCLifetimeType() || 2682 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2683 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2684 return false; 2685 2686 // Make sure that we have compatible qualifiers. 2687 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2688 if (!ToQuals.compatiblyIncludes(FromQuals)) 2689 return false; 2690 2691 // Remove qualifiers from the pointee type we're converting from; they 2692 // aren't used in the compatibility check belong, and we'll be adding back 2693 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2694 FromPointee = FromPointee.getUnqualifiedType(); 2695 2696 // The unqualified form of the pointee types must be compatible. 2697 ToPointee = ToPointee.getUnqualifiedType(); 2698 bool IncompatibleObjC; 2699 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2700 FromPointee = ToPointee; 2701 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2702 IncompatibleObjC)) 2703 return false; 2704 2705 /// Construct the type we're converting to, which is a pointer to 2706 /// __autoreleasing pointee. 2707 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2708 ConvertedType = Context.getPointerType(FromPointee); 2709 return true; 2710 } 2711 2712 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2713 QualType& ConvertedType) { 2714 QualType ToPointeeType; 2715 if (const BlockPointerType *ToBlockPtr = 2716 ToType->getAs<BlockPointerType>()) 2717 ToPointeeType = ToBlockPtr->getPointeeType(); 2718 else 2719 return false; 2720 2721 QualType FromPointeeType; 2722 if (const BlockPointerType *FromBlockPtr = 2723 FromType->getAs<BlockPointerType>()) 2724 FromPointeeType = FromBlockPtr->getPointeeType(); 2725 else 2726 return false; 2727 // We have pointer to blocks, check whether the only 2728 // differences in the argument and result types are in Objective-C 2729 // pointer conversions. If so, we permit the conversion. 2730 2731 const FunctionProtoType *FromFunctionType 2732 = FromPointeeType->getAs<FunctionProtoType>(); 2733 const FunctionProtoType *ToFunctionType 2734 = ToPointeeType->getAs<FunctionProtoType>(); 2735 2736 if (!FromFunctionType || !ToFunctionType) 2737 return false; 2738 2739 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2740 return true; 2741 2742 // Perform the quick checks that will tell us whether these 2743 // function types are obviously different. 2744 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2745 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2746 return false; 2747 2748 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2749 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2750 if (FromEInfo != ToEInfo) 2751 return false; 2752 2753 bool IncompatibleObjC = false; 2754 if (Context.hasSameType(FromFunctionType->getReturnType(), 2755 ToFunctionType->getReturnType())) { 2756 // Okay, the types match exactly. Nothing to do. 2757 } else { 2758 QualType RHS = FromFunctionType->getReturnType(); 2759 QualType LHS = ToFunctionType->getReturnType(); 2760 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2761 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2762 LHS = LHS.getUnqualifiedType(); 2763 2764 if (Context.hasSameType(RHS,LHS)) { 2765 // OK exact match. 2766 } else if (isObjCPointerConversion(RHS, LHS, 2767 ConvertedType, IncompatibleObjC)) { 2768 if (IncompatibleObjC) 2769 return false; 2770 // Okay, we have an Objective-C pointer conversion. 2771 } 2772 else 2773 return false; 2774 } 2775 2776 // Check argument types. 2777 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2778 ArgIdx != NumArgs; ++ArgIdx) { 2779 IncompatibleObjC = false; 2780 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2781 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2782 if (Context.hasSameType(FromArgType, ToArgType)) { 2783 // Okay, the types match exactly. Nothing to do. 2784 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2785 ConvertedType, IncompatibleObjC)) { 2786 if (IncompatibleObjC) 2787 return false; 2788 // Okay, we have an Objective-C pointer conversion. 2789 } else 2790 // Argument types are too different. Abort. 2791 return false; 2792 } 2793 2794 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2795 bool CanUseToFPT, CanUseFromFPT; 2796 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2797 CanUseToFPT, CanUseFromFPT, 2798 NewParamInfos)) 2799 return false; 2800 2801 ConvertedType = ToType; 2802 return true; 2803 } 2804 2805 enum { 2806 ft_default, 2807 ft_different_class, 2808 ft_parameter_arity, 2809 ft_parameter_mismatch, 2810 ft_return_type, 2811 ft_qualifer_mismatch, 2812 ft_noexcept 2813 }; 2814 2815 /// Attempts to get the FunctionProtoType from a Type. Handles 2816 /// MemberFunctionPointers properly. 2817 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2818 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2819 return FPT; 2820 2821 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2822 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2823 2824 return nullptr; 2825 } 2826 2827 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2828 /// function types. Catches different number of parameter, mismatch in 2829 /// parameter types, and different return types. 2830 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2831 QualType FromType, QualType ToType) { 2832 // If either type is not valid, include no extra info. 2833 if (FromType.isNull() || ToType.isNull()) { 2834 PDiag << ft_default; 2835 return; 2836 } 2837 2838 // Get the function type from the pointers. 2839 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2840 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2841 *ToMember = ToType->getAs<MemberPointerType>(); 2842 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2843 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2844 << QualType(FromMember->getClass(), 0); 2845 return; 2846 } 2847 FromType = FromMember->getPointeeType(); 2848 ToType = ToMember->getPointeeType(); 2849 } 2850 2851 if (FromType->isPointerType()) 2852 FromType = FromType->getPointeeType(); 2853 if (ToType->isPointerType()) 2854 ToType = ToType->getPointeeType(); 2855 2856 // Remove references. 2857 FromType = FromType.getNonReferenceType(); 2858 ToType = ToType.getNonReferenceType(); 2859 2860 // Don't print extra info for non-specialized template functions. 2861 if (FromType->isInstantiationDependentType() && 2862 !FromType->getAs<TemplateSpecializationType>()) { 2863 PDiag << ft_default; 2864 return; 2865 } 2866 2867 // No extra info for same types. 2868 if (Context.hasSameType(FromType, ToType)) { 2869 PDiag << ft_default; 2870 return; 2871 } 2872 2873 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2874 *ToFunction = tryGetFunctionProtoType(ToType); 2875 2876 // Both types need to be function types. 2877 if (!FromFunction || !ToFunction) { 2878 PDiag << ft_default; 2879 return; 2880 } 2881 2882 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2883 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2884 << FromFunction->getNumParams(); 2885 return; 2886 } 2887 2888 // Handle different parameter types. 2889 unsigned ArgPos; 2890 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2891 PDiag << ft_parameter_mismatch << ArgPos + 1 2892 << ToFunction->getParamType(ArgPos) 2893 << FromFunction->getParamType(ArgPos); 2894 return; 2895 } 2896 2897 // Handle different return type. 2898 if (!Context.hasSameType(FromFunction->getReturnType(), 2899 ToFunction->getReturnType())) { 2900 PDiag << ft_return_type << ToFunction->getReturnType() 2901 << FromFunction->getReturnType(); 2902 return; 2903 } 2904 2905 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2906 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2907 << FromFunction->getMethodQuals(); 2908 return; 2909 } 2910 2911 // Handle exception specification differences on canonical type (in C++17 2912 // onwards). 2913 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2914 ->isNothrow() != 2915 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2916 ->isNothrow()) { 2917 PDiag << ft_noexcept; 2918 return; 2919 } 2920 2921 // Unable to find a difference, so add no extra info. 2922 PDiag << ft_default; 2923 } 2924 2925 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2926 /// for equality of their argument types. Caller has already checked that 2927 /// they have same number of arguments. If the parameters are different, 2928 /// ArgPos will have the parameter index of the first different parameter. 2929 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2930 const FunctionProtoType *NewType, 2931 unsigned *ArgPos) { 2932 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2933 N = NewType->param_type_begin(), 2934 E = OldType->param_type_end(); 2935 O && (O != E); ++O, ++N) { 2936 // Ignore address spaces in pointee type. This is to disallow overloading 2937 // on __ptr32/__ptr64 address spaces. 2938 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2939 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2940 2941 if (!Context.hasSameType(Old, New)) { 2942 if (ArgPos) 2943 *ArgPos = O - OldType->param_type_begin(); 2944 return false; 2945 } 2946 } 2947 return true; 2948 } 2949 2950 /// CheckPointerConversion - Check the pointer conversion from the 2951 /// expression From to the type ToType. This routine checks for 2952 /// ambiguous or inaccessible derived-to-base pointer 2953 /// conversions for which IsPointerConversion has already returned 2954 /// true. It returns true and produces a diagnostic if there was an 2955 /// error, or returns false otherwise. 2956 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2957 CastKind &Kind, 2958 CXXCastPath& BasePath, 2959 bool IgnoreBaseAccess, 2960 bool Diagnose) { 2961 QualType FromType = From->getType(); 2962 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2963 2964 Kind = CK_BitCast; 2965 2966 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2967 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2968 Expr::NPCK_ZeroExpression) { 2969 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2970 DiagRuntimeBehavior(From->getExprLoc(), From, 2971 PDiag(diag::warn_impcast_bool_to_null_pointer) 2972 << ToType << From->getSourceRange()); 2973 else if (!isUnevaluatedContext()) 2974 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2975 << ToType << From->getSourceRange(); 2976 } 2977 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2978 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2979 QualType FromPointeeType = FromPtrType->getPointeeType(), 2980 ToPointeeType = ToPtrType->getPointeeType(); 2981 2982 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2983 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2984 // We must have a derived-to-base conversion. Check an 2985 // ambiguous or inaccessible conversion. 2986 unsigned InaccessibleID = 0; 2987 unsigned AmbigiousID = 0; 2988 if (Diagnose) { 2989 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2990 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2991 } 2992 if (CheckDerivedToBaseConversion( 2993 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2994 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2995 &BasePath, IgnoreBaseAccess)) 2996 return true; 2997 2998 // The conversion was successful. 2999 Kind = CK_DerivedToBase; 3000 } 3001 3002 if (Diagnose && !IsCStyleOrFunctionalCast && 3003 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3004 assert(getLangOpts().MSVCCompat && 3005 "this should only be possible with MSVCCompat!"); 3006 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3007 << From->getSourceRange(); 3008 } 3009 } 3010 } else if (const ObjCObjectPointerType *ToPtrType = 3011 ToType->getAs<ObjCObjectPointerType>()) { 3012 if (const ObjCObjectPointerType *FromPtrType = 3013 FromType->getAs<ObjCObjectPointerType>()) { 3014 // Objective-C++ conversions are always okay. 3015 // FIXME: We should have a different class of conversions for the 3016 // Objective-C++ implicit conversions. 3017 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3018 return false; 3019 } else if (FromType->isBlockPointerType()) { 3020 Kind = CK_BlockPointerToObjCPointerCast; 3021 } else { 3022 Kind = CK_CPointerToObjCPointerCast; 3023 } 3024 } else if (ToType->isBlockPointerType()) { 3025 if (!FromType->isBlockPointerType()) 3026 Kind = CK_AnyPointerToBlockPointerCast; 3027 } 3028 3029 // We shouldn't fall into this case unless it's valid for other 3030 // reasons. 3031 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3032 Kind = CK_NullToPointer; 3033 3034 return false; 3035 } 3036 3037 /// IsMemberPointerConversion - Determines whether the conversion of the 3038 /// expression From, which has the (possibly adjusted) type FromType, can be 3039 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3040 /// If so, returns true and places the converted type (that might differ from 3041 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3042 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3043 QualType ToType, 3044 bool InOverloadResolution, 3045 QualType &ConvertedType) { 3046 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3047 if (!ToTypePtr) 3048 return false; 3049 3050 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3051 if (From->isNullPointerConstant(Context, 3052 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3053 : Expr::NPC_ValueDependentIsNull)) { 3054 ConvertedType = ToType; 3055 return true; 3056 } 3057 3058 // Otherwise, both types have to be member pointers. 3059 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3060 if (!FromTypePtr) 3061 return false; 3062 3063 // A pointer to member of B can be converted to a pointer to member of D, 3064 // where D is derived from B (C++ 4.11p2). 3065 QualType FromClass(FromTypePtr->getClass(), 0); 3066 QualType ToClass(ToTypePtr->getClass(), 0); 3067 3068 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3069 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3070 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3071 ToClass.getTypePtr()); 3072 return true; 3073 } 3074 3075 return false; 3076 } 3077 3078 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3079 /// expression From to the type ToType. This routine checks for ambiguous or 3080 /// virtual or inaccessible base-to-derived member pointer conversions 3081 /// for which IsMemberPointerConversion has already returned true. It returns 3082 /// true and produces a diagnostic if there was an error, or returns false 3083 /// otherwise. 3084 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3085 CastKind &Kind, 3086 CXXCastPath &BasePath, 3087 bool IgnoreBaseAccess) { 3088 QualType FromType = From->getType(); 3089 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3090 if (!FromPtrType) { 3091 // This must be a null pointer to member pointer conversion 3092 assert(From->isNullPointerConstant(Context, 3093 Expr::NPC_ValueDependentIsNull) && 3094 "Expr must be null pointer constant!"); 3095 Kind = CK_NullToMemberPointer; 3096 return false; 3097 } 3098 3099 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3100 assert(ToPtrType && "No member pointer cast has a target type " 3101 "that is not a member pointer."); 3102 3103 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3104 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3105 3106 // FIXME: What about dependent types? 3107 assert(FromClass->isRecordType() && "Pointer into non-class."); 3108 assert(ToClass->isRecordType() && "Pointer into non-class."); 3109 3110 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3111 /*DetectVirtual=*/true); 3112 bool DerivationOkay = 3113 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3114 assert(DerivationOkay && 3115 "Should not have been called if derivation isn't OK."); 3116 (void)DerivationOkay; 3117 3118 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3119 getUnqualifiedType())) { 3120 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3121 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3122 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3123 return true; 3124 } 3125 3126 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3127 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3128 << FromClass << ToClass << QualType(VBase, 0) 3129 << From->getSourceRange(); 3130 return true; 3131 } 3132 3133 if (!IgnoreBaseAccess) 3134 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3135 Paths.front(), 3136 diag::err_downcast_from_inaccessible_base); 3137 3138 // Must be a base to derived member conversion. 3139 BuildBasePathArray(Paths, BasePath); 3140 Kind = CK_BaseToDerivedMemberPointer; 3141 return false; 3142 } 3143 3144 /// Determine whether the lifetime conversion between the two given 3145 /// qualifiers sets is nontrivial. 3146 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3147 Qualifiers ToQuals) { 3148 // Converting anything to const __unsafe_unretained is trivial. 3149 if (ToQuals.hasConst() && 3150 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3151 return false; 3152 3153 return true; 3154 } 3155 3156 /// Perform a single iteration of the loop for checking if a qualification 3157 /// conversion is valid. 3158 /// 3159 /// Specifically, check whether any change between the qualifiers of \p 3160 /// FromType and \p ToType is permissible, given knowledge about whether every 3161 /// outer layer is const-qualified. 3162 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3163 bool CStyle, 3164 bool &PreviousToQualsIncludeConst, 3165 bool &ObjCLifetimeConversion) { 3166 Qualifiers FromQuals = FromType.getQualifiers(); 3167 Qualifiers ToQuals = ToType.getQualifiers(); 3168 3169 // Ignore __unaligned qualifier if this type is void. 3170 if (ToType.getUnqualifiedType()->isVoidType()) 3171 FromQuals.removeUnaligned(); 3172 3173 // Objective-C ARC: 3174 // Check Objective-C lifetime conversions. 3175 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3176 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3177 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3178 ObjCLifetimeConversion = true; 3179 FromQuals.removeObjCLifetime(); 3180 ToQuals.removeObjCLifetime(); 3181 } else { 3182 // Qualification conversions cannot cast between different 3183 // Objective-C lifetime qualifiers. 3184 return false; 3185 } 3186 } 3187 3188 // Allow addition/removal of GC attributes but not changing GC attributes. 3189 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3190 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3191 FromQuals.removeObjCGCAttr(); 3192 ToQuals.removeObjCGCAttr(); 3193 } 3194 3195 // -- for every j > 0, if const is in cv 1,j then const is in cv 3196 // 2,j, and similarly for volatile. 3197 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3198 return false; 3199 3200 // For a C-style cast, just require the address spaces to overlap. 3201 // FIXME: Does "superset" also imply the representation of a pointer is the 3202 // same? We're assuming that it does here and in compatiblyIncludes. 3203 if (CStyle && !ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3204 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) 3205 return false; 3206 3207 // -- if the cv 1,j and cv 2,j are different, then const is in 3208 // every cv for 0 < k < j. 3209 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3210 !PreviousToQualsIncludeConst) 3211 return false; 3212 3213 // Keep track of whether all prior cv-qualifiers in the "to" type 3214 // include const. 3215 PreviousToQualsIncludeConst = 3216 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3217 return true; 3218 } 3219 3220 /// IsQualificationConversion - Determines whether the conversion from 3221 /// an rvalue of type FromType to ToType is a qualification conversion 3222 /// (C++ 4.4). 3223 /// 3224 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3225 /// when the qualification conversion involves a change in the Objective-C 3226 /// object lifetime. 3227 bool 3228 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3229 bool CStyle, bool &ObjCLifetimeConversion) { 3230 FromType = Context.getCanonicalType(FromType); 3231 ToType = Context.getCanonicalType(ToType); 3232 ObjCLifetimeConversion = false; 3233 3234 // If FromType and ToType are the same type, this is not a 3235 // qualification conversion. 3236 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3237 return false; 3238 3239 // (C++ 4.4p4): 3240 // A conversion can add cv-qualifiers at levels other than the first 3241 // in multi-level pointers, subject to the following rules: [...] 3242 bool PreviousToQualsIncludeConst = true; 3243 bool UnwrappedAnyPointer = false; 3244 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3245 if (!isQualificationConversionStep(FromType, ToType, CStyle, 3246 PreviousToQualsIncludeConst, 3247 ObjCLifetimeConversion)) 3248 return false; 3249 UnwrappedAnyPointer = true; 3250 } 3251 3252 // We are left with FromType and ToType being the pointee types 3253 // after unwrapping the original FromType and ToType the same number 3254 // of times. If we unwrapped any pointers, and if FromType and 3255 // ToType have the same unqualified type (since we checked 3256 // qualifiers above), then this is a qualification conversion. 3257 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3258 } 3259 3260 /// - Determine whether this is a conversion from a scalar type to an 3261 /// atomic type. 3262 /// 3263 /// If successful, updates \c SCS's second and third steps in the conversion 3264 /// sequence to finish the conversion. 3265 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3266 bool InOverloadResolution, 3267 StandardConversionSequence &SCS, 3268 bool CStyle) { 3269 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3270 if (!ToAtomic) 3271 return false; 3272 3273 StandardConversionSequence InnerSCS; 3274 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3275 InOverloadResolution, InnerSCS, 3276 CStyle, /*AllowObjCWritebackConversion=*/false)) 3277 return false; 3278 3279 SCS.Second = InnerSCS.Second; 3280 SCS.setToType(1, InnerSCS.getToType(1)); 3281 SCS.Third = InnerSCS.Third; 3282 SCS.QualificationIncludesObjCLifetime 3283 = InnerSCS.QualificationIncludesObjCLifetime; 3284 SCS.setToType(2, InnerSCS.getToType(2)); 3285 return true; 3286 } 3287 3288 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3289 CXXConstructorDecl *Constructor, 3290 QualType Type) { 3291 const FunctionProtoType *CtorType = 3292 Constructor->getType()->getAs<FunctionProtoType>(); 3293 if (CtorType->getNumParams() > 0) { 3294 QualType FirstArg = CtorType->getParamType(0); 3295 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3296 return true; 3297 } 3298 return false; 3299 } 3300 3301 static OverloadingResult 3302 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3303 CXXRecordDecl *To, 3304 UserDefinedConversionSequence &User, 3305 OverloadCandidateSet &CandidateSet, 3306 bool AllowExplicit) { 3307 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3308 for (auto *D : S.LookupConstructors(To)) { 3309 auto Info = getConstructorInfo(D); 3310 if (!Info) 3311 continue; 3312 3313 bool Usable = !Info.Constructor->isInvalidDecl() && 3314 S.isInitListConstructor(Info.Constructor) && 3315 (AllowExplicit || !Info.Constructor->isExplicit()); 3316 if (Usable) { 3317 // If the first argument is (a reference to) the target type, 3318 // suppress conversions. 3319 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3320 S.Context, Info.Constructor, ToType); 3321 if (Info.ConstructorTmpl) 3322 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3323 /*ExplicitArgs*/ nullptr, From, 3324 CandidateSet, SuppressUserConversions, 3325 /*PartialOverloading*/ false, 3326 AllowExplicit); 3327 else 3328 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3329 CandidateSet, SuppressUserConversions, 3330 /*PartialOverloading*/ false, AllowExplicit); 3331 } 3332 } 3333 3334 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3335 3336 OverloadCandidateSet::iterator Best; 3337 switch (auto Result = 3338 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3339 case OR_Deleted: 3340 case OR_Success: { 3341 // Record the standard conversion we used and the conversion function. 3342 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3343 QualType ThisType = Constructor->getThisType(); 3344 // Initializer lists don't have conversions as such. 3345 User.Before.setAsIdentityConversion(); 3346 User.HadMultipleCandidates = HadMultipleCandidates; 3347 User.ConversionFunction = Constructor; 3348 User.FoundConversionFunction = Best->FoundDecl; 3349 User.After.setAsIdentityConversion(); 3350 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3351 User.After.setAllToTypes(ToType); 3352 return Result; 3353 } 3354 3355 case OR_No_Viable_Function: 3356 return OR_No_Viable_Function; 3357 case OR_Ambiguous: 3358 return OR_Ambiguous; 3359 } 3360 3361 llvm_unreachable("Invalid OverloadResult!"); 3362 } 3363 3364 /// Determines whether there is a user-defined conversion sequence 3365 /// (C++ [over.ics.user]) that converts expression From to the type 3366 /// ToType. If such a conversion exists, User will contain the 3367 /// user-defined conversion sequence that performs such a conversion 3368 /// and this routine will return true. Otherwise, this routine returns 3369 /// false and User is unspecified. 3370 /// 3371 /// \param AllowExplicit true if the conversion should consider C++0x 3372 /// "explicit" conversion functions as well as non-explicit conversion 3373 /// functions (C++0x [class.conv.fct]p2). 3374 /// 3375 /// \param AllowObjCConversionOnExplicit true if the conversion should 3376 /// allow an extra Objective-C pointer conversion on uses of explicit 3377 /// constructors. Requires \c AllowExplicit to also be set. 3378 static OverloadingResult 3379 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3380 UserDefinedConversionSequence &User, 3381 OverloadCandidateSet &CandidateSet, 3382 bool AllowExplicit, 3383 bool AllowObjCConversionOnExplicit) { 3384 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3385 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3386 3387 // Whether we will only visit constructors. 3388 bool ConstructorsOnly = false; 3389 3390 // If the type we are conversion to is a class type, enumerate its 3391 // constructors. 3392 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3393 // C++ [over.match.ctor]p1: 3394 // When objects of class type are direct-initialized (8.5), or 3395 // copy-initialized from an expression of the same or a 3396 // derived class type (8.5), overload resolution selects the 3397 // constructor. [...] For copy-initialization, the candidate 3398 // functions are all the converting constructors (12.3.1) of 3399 // that class. The argument list is the expression-list within 3400 // the parentheses of the initializer. 3401 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3402 (From->getType()->getAs<RecordType>() && 3403 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3404 ConstructorsOnly = true; 3405 3406 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3407 // We're not going to find any constructors. 3408 } else if (CXXRecordDecl *ToRecordDecl 3409 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3410 3411 Expr **Args = &From; 3412 unsigned NumArgs = 1; 3413 bool ListInitializing = false; 3414 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3415 // But first, see if there is an init-list-constructor that will work. 3416 OverloadingResult Result = IsInitializerListConstructorConversion( 3417 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3418 if (Result != OR_No_Viable_Function) 3419 return Result; 3420 // Never mind. 3421 CandidateSet.clear( 3422 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3423 3424 // If we're list-initializing, we pass the individual elements as 3425 // arguments, not the entire list. 3426 Args = InitList->getInits(); 3427 NumArgs = InitList->getNumInits(); 3428 ListInitializing = true; 3429 } 3430 3431 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3432 auto Info = getConstructorInfo(D); 3433 if (!Info) 3434 continue; 3435 3436 bool Usable = !Info.Constructor->isInvalidDecl(); 3437 if (ListInitializing) 3438 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3439 else 3440 Usable = Usable && 3441 Info.Constructor->isConvertingConstructor(AllowExplicit); 3442 if (Usable) { 3443 bool SuppressUserConversions = !ConstructorsOnly; 3444 if (SuppressUserConversions && ListInitializing) { 3445 SuppressUserConversions = false; 3446 if (NumArgs == 1) { 3447 // If the first argument is (a reference to) the target type, 3448 // suppress conversions. 3449 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3450 S.Context, Info.Constructor, ToType); 3451 } 3452 } 3453 if (Info.ConstructorTmpl) 3454 S.AddTemplateOverloadCandidate( 3455 Info.ConstructorTmpl, Info.FoundDecl, 3456 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3457 CandidateSet, SuppressUserConversions, 3458 /*PartialOverloading*/ false, AllowExplicit); 3459 else 3460 // Allow one user-defined conversion when user specifies a 3461 // From->ToType conversion via an static cast (c-style, etc). 3462 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3463 llvm::makeArrayRef(Args, NumArgs), 3464 CandidateSet, SuppressUserConversions, 3465 /*PartialOverloading*/ false, AllowExplicit); 3466 } 3467 } 3468 } 3469 } 3470 3471 // Enumerate conversion functions, if we're allowed to. 3472 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3473 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3474 // No conversion functions from incomplete types. 3475 } else if (const RecordType *FromRecordType = 3476 From->getType()->getAs<RecordType>()) { 3477 if (CXXRecordDecl *FromRecordDecl 3478 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3479 // Add all of the conversion functions as candidates. 3480 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3481 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3482 DeclAccessPair FoundDecl = I.getPair(); 3483 NamedDecl *D = FoundDecl.getDecl(); 3484 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3485 if (isa<UsingShadowDecl>(D)) 3486 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3487 3488 CXXConversionDecl *Conv; 3489 FunctionTemplateDecl *ConvTemplate; 3490 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3491 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3492 else 3493 Conv = cast<CXXConversionDecl>(D); 3494 3495 if (AllowExplicit || !Conv->isExplicit()) { 3496 if (ConvTemplate) 3497 S.AddTemplateConversionCandidate( 3498 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3499 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3500 else 3501 S.AddConversionCandidate( 3502 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3503 AllowObjCConversionOnExplicit, AllowExplicit); 3504 } 3505 } 3506 } 3507 } 3508 3509 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3510 3511 OverloadCandidateSet::iterator Best; 3512 switch (auto Result = 3513 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3514 case OR_Success: 3515 case OR_Deleted: 3516 // Record the standard conversion we used and the conversion function. 3517 if (CXXConstructorDecl *Constructor 3518 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3519 // C++ [over.ics.user]p1: 3520 // If the user-defined conversion is specified by a 3521 // constructor (12.3.1), the initial standard conversion 3522 // sequence converts the source type to the type required by 3523 // the argument of the constructor. 3524 // 3525 QualType ThisType = Constructor->getThisType(); 3526 if (isa<InitListExpr>(From)) { 3527 // Initializer lists don't have conversions as such. 3528 User.Before.setAsIdentityConversion(); 3529 } else { 3530 if (Best->Conversions[0].isEllipsis()) 3531 User.EllipsisConversion = true; 3532 else { 3533 User.Before = Best->Conversions[0].Standard; 3534 User.EllipsisConversion = false; 3535 } 3536 } 3537 User.HadMultipleCandidates = HadMultipleCandidates; 3538 User.ConversionFunction = Constructor; 3539 User.FoundConversionFunction = Best->FoundDecl; 3540 User.After.setAsIdentityConversion(); 3541 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3542 User.After.setAllToTypes(ToType); 3543 return Result; 3544 } 3545 if (CXXConversionDecl *Conversion 3546 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3547 // C++ [over.ics.user]p1: 3548 // 3549 // [...] If the user-defined conversion is specified by a 3550 // conversion function (12.3.2), the initial standard 3551 // conversion sequence converts the source type to the 3552 // implicit object parameter of the conversion function. 3553 User.Before = Best->Conversions[0].Standard; 3554 User.HadMultipleCandidates = HadMultipleCandidates; 3555 User.ConversionFunction = Conversion; 3556 User.FoundConversionFunction = Best->FoundDecl; 3557 User.EllipsisConversion = false; 3558 3559 // C++ [over.ics.user]p2: 3560 // The second standard conversion sequence converts the 3561 // result of the user-defined conversion to the target type 3562 // for the sequence. Since an implicit conversion sequence 3563 // is an initialization, the special rules for 3564 // initialization by user-defined conversion apply when 3565 // selecting the best user-defined conversion for a 3566 // user-defined conversion sequence (see 13.3.3 and 3567 // 13.3.3.1). 3568 User.After = Best->FinalConversion; 3569 return Result; 3570 } 3571 llvm_unreachable("Not a constructor or conversion function?"); 3572 3573 case OR_No_Viable_Function: 3574 return OR_No_Viable_Function; 3575 3576 case OR_Ambiguous: 3577 return OR_Ambiguous; 3578 } 3579 3580 llvm_unreachable("Invalid OverloadResult!"); 3581 } 3582 3583 bool 3584 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3585 ImplicitConversionSequence ICS; 3586 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3587 OverloadCandidateSet::CSK_Normal); 3588 OverloadingResult OvResult = 3589 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3590 CandidateSet, false, false); 3591 3592 if (!(OvResult == OR_Ambiguous || 3593 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3594 return false; 3595 3596 auto Cands = CandidateSet.CompleteCandidates( 3597 *this, 3598 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3599 From); 3600 if (OvResult == OR_Ambiguous) 3601 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3602 << From->getType() << ToType << From->getSourceRange(); 3603 else { // OR_No_Viable_Function && !CandidateSet.empty() 3604 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3605 diag::err_typecheck_nonviable_condition_incomplete, 3606 From->getType(), From->getSourceRange())) 3607 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3608 << false << From->getType() << From->getSourceRange() << ToType; 3609 } 3610 3611 CandidateSet.NoteCandidates( 3612 *this, From, Cands); 3613 return true; 3614 } 3615 3616 /// Compare the user-defined conversion functions or constructors 3617 /// of two user-defined conversion sequences to determine whether any ordering 3618 /// is possible. 3619 static ImplicitConversionSequence::CompareKind 3620 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3621 FunctionDecl *Function2) { 3622 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3623 return ImplicitConversionSequence::Indistinguishable; 3624 3625 // Objective-C++: 3626 // If both conversion functions are implicitly-declared conversions from 3627 // a lambda closure type to a function pointer and a block pointer, 3628 // respectively, always prefer the conversion to a function pointer, 3629 // because the function pointer is more lightweight and is more likely 3630 // to keep code working. 3631 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3632 if (!Conv1) 3633 return ImplicitConversionSequence::Indistinguishable; 3634 3635 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3636 if (!Conv2) 3637 return ImplicitConversionSequence::Indistinguishable; 3638 3639 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3640 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3641 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3642 if (Block1 != Block2) 3643 return Block1 ? ImplicitConversionSequence::Worse 3644 : ImplicitConversionSequence::Better; 3645 } 3646 3647 return ImplicitConversionSequence::Indistinguishable; 3648 } 3649 3650 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3651 const ImplicitConversionSequence &ICS) { 3652 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3653 (ICS.isUserDefined() && 3654 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3655 } 3656 3657 /// CompareImplicitConversionSequences - Compare two implicit 3658 /// conversion sequences to determine whether one is better than the 3659 /// other or if they are indistinguishable (C++ 13.3.3.2). 3660 static ImplicitConversionSequence::CompareKind 3661 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3662 const ImplicitConversionSequence& ICS1, 3663 const ImplicitConversionSequence& ICS2) 3664 { 3665 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3666 // conversion sequences (as defined in 13.3.3.1) 3667 // -- a standard conversion sequence (13.3.3.1.1) is a better 3668 // conversion sequence than a user-defined conversion sequence or 3669 // an ellipsis conversion sequence, and 3670 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3671 // conversion sequence than an ellipsis conversion sequence 3672 // (13.3.3.1.3). 3673 // 3674 // C++0x [over.best.ics]p10: 3675 // For the purpose of ranking implicit conversion sequences as 3676 // described in 13.3.3.2, the ambiguous conversion sequence is 3677 // treated as a user-defined sequence that is indistinguishable 3678 // from any other user-defined conversion sequence. 3679 3680 // String literal to 'char *' conversion has been deprecated in C++03. It has 3681 // been removed from C++11. We still accept this conversion, if it happens at 3682 // the best viable function. Otherwise, this conversion is considered worse 3683 // than ellipsis conversion. Consider this as an extension; this is not in the 3684 // standard. For example: 3685 // 3686 // int &f(...); // #1 3687 // void f(char*); // #2 3688 // void g() { int &r = f("foo"); } 3689 // 3690 // In C++03, we pick #2 as the best viable function. 3691 // In C++11, we pick #1 as the best viable function, because ellipsis 3692 // conversion is better than string-literal to char* conversion (since there 3693 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3694 // convert arguments, #2 would be the best viable function in C++11. 3695 // If the best viable function has this conversion, a warning will be issued 3696 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3697 3698 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3699 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3700 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3701 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3702 ? ImplicitConversionSequence::Worse 3703 : ImplicitConversionSequence::Better; 3704 3705 if (ICS1.getKindRank() < ICS2.getKindRank()) 3706 return ImplicitConversionSequence::Better; 3707 if (ICS2.getKindRank() < ICS1.getKindRank()) 3708 return ImplicitConversionSequence::Worse; 3709 3710 // The following checks require both conversion sequences to be of 3711 // the same kind. 3712 if (ICS1.getKind() != ICS2.getKind()) 3713 return ImplicitConversionSequence::Indistinguishable; 3714 3715 ImplicitConversionSequence::CompareKind Result = 3716 ImplicitConversionSequence::Indistinguishable; 3717 3718 // Two implicit conversion sequences of the same form are 3719 // indistinguishable conversion sequences unless one of the 3720 // following rules apply: (C++ 13.3.3.2p3): 3721 3722 // List-initialization sequence L1 is a better conversion sequence than 3723 // list-initialization sequence L2 if: 3724 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3725 // if not that, 3726 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3727 // and N1 is smaller than N2., 3728 // even if one of the other rules in this paragraph would otherwise apply. 3729 if (!ICS1.isBad()) { 3730 if (ICS1.isStdInitializerListElement() && 3731 !ICS2.isStdInitializerListElement()) 3732 return ImplicitConversionSequence::Better; 3733 if (!ICS1.isStdInitializerListElement() && 3734 ICS2.isStdInitializerListElement()) 3735 return ImplicitConversionSequence::Worse; 3736 } 3737 3738 if (ICS1.isStandard()) 3739 // Standard conversion sequence S1 is a better conversion sequence than 3740 // standard conversion sequence S2 if [...] 3741 Result = CompareStandardConversionSequences(S, Loc, 3742 ICS1.Standard, ICS2.Standard); 3743 else if (ICS1.isUserDefined()) { 3744 // User-defined conversion sequence U1 is a better conversion 3745 // sequence than another user-defined conversion sequence U2 if 3746 // they contain the same user-defined conversion function or 3747 // constructor and if the second standard conversion sequence of 3748 // U1 is better than the second standard conversion sequence of 3749 // U2 (C++ 13.3.3.2p3). 3750 if (ICS1.UserDefined.ConversionFunction == 3751 ICS2.UserDefined.ConversionFunction) 3752 Result = CompareStandardConversionSequences(S, Loc, 3753 ICS1.UserDefined.After, 3754 ICS2.UserDefined.After); 3755 else 3756 Result = compareConversionFunctions(S, 3757 ICS1.UserDefined.ConversionFunction, 3758 ICS2.UserDefined.ConversionFunction); 3759 } 3760 3761 return Result; 3762 } 3763 3764 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3765 // determine if one is a proper subset of the other. 3766 static ImplicitConversionSequence::CompareKind 3767 compareStandardConversionSubsets(ASTContext &Context, 3768 const StandardConversionSequence& SCS1, 3769 const StandardConversionSequence& SCS2) { 3770 ImplicitConversionSequence::CompareKind Result 3771 = ImplicitConversionSequence::Indistinguishable; 3772 3773 // the identity conversion sequence is considered to be a subsequence of 3774 // any non-identity conversion sequence 3775 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3776 return ImplicitConversionSequence::Better; 3777 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3778 return ImplicitConversionSequence::Worse; 3779 3780 if (SCS1.Second != SCS2.Second) { 3781 if (SCS1.Second == ICK_Identity) 3782 Result = ImplicitConversionSequence::Better; 3783 else if (SCS2.Second == ICK_Identity) 3784 Result = ImplicitConversionSequence::Worse; 3785 else 3786 return ImplicitConversionSequence::Indistinguishable; 3787 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3788 return ImplicitConversionSequence::Indistinguishable; 3789 3790 if (SCS1.Third == SCS2.Third) { 3791 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3792 : ImplicitConversionSequence::Indistinguishable; 3793 } 3794 3795 if (SCS1.Third == ICK_Identity) 3796 return Result == ImplicitConversionSequence::Worse 3797 ? ImplicitConversionSequence::Indistinguishable 3798 : ImplicitConversionSequence::Better; 3799 3800 if (SCS2.Third == ICK_Identity) 3801 return Result == ImplicitConversionSequence::Better 3802 ? ImplicitConversionSequence::Indistinguishable 3803 : ImplicitConversionSequence::Worse; 3804 3805 return ImplicitConversionSequence::Indistinguishable; 3806 } 3807 3808 /// Determine whether one of the given reference bindings is better 3809 /// than the other based on what kind of bindings they are. 3810 static bool 3811 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3812 const StandardConversionSequence &SCS2) { 3813 // C++0x [over.ics.rank]p3b4: 3814 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3815 // implicit object parameter of a non-static member function declared 3816 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3817 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3818 // lvalue reference to a function lvalue and S2 binds an rvalue 3819 // reference*. 3820 // 3821 // FIXME: Rvalue references. We're going rogue with the above edits, 3822 // because the semantics in the current C++0x working paper (N3225 at the 3823 // time of this writing) break the standard definition of std::forward 3824 // and std::reference_wrapper when dealing with references to functions. 3825 // Proposed wording changes submitted to CWG for consideration. 3826 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3827 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3828 return false; 3829 3830 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3831 SCS2.IsLvalueReference) || 3832 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3833 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3834 } 3835 3836 enum class FixedEnumPromotion { 3837 None, 3838 ToUnderlyingType, 3839 ToPromotedUnderlyingType 3840 }; 3841 3842 /// Returns kind of fixed enum promotion the \a SCS uses. 3843 static FixedEnumPromotion 3844 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3845 3846 if (SCS.Second != ICK_Integral_Promotion) 3847 return FixedEnumPromotion::None; 3848 3849 QualType FromType = SCS.getFromType(); 3850 if (!FromType->isEnumeralType()) 3851 return FixedEnumPromotion::None; 3852 3853 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3854 if (!Enum->isFixed()) 3855 return FixedEnumPromotion::None; 3856 3857 QualType UnderlyingType = Enum->getIntegerType(); 3858 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3859 return FixedEnumPromotion::ToUnderlyingType; 3860 3861 return FixedEnumPromotion::ToPromotedUnderlyingType; 3862 } 3863 3864 /// CompareStandardConversionSequences - Compare two standard 3865 /// conversion sequences to determine whether one is better than the 3866 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3867 static ImplicitConversionSequence::CompareKind 3868 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3869 const StandardConversionSequence& SCS1, 3870 const StandardConversionSequence& SCS2) 3871 { 3872 // Standard conversion sequence S1 is a better conversion sequence 3873 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3874 3875 // -- S1 is a proper subsequence of S2 (comparing the conversion 3876 // sequences in the canonical form defined by 13.3.3.1.1, 3877 // excluding any Lvalue Transformation; the identity conversion 3878 // sequence is considered to be a subsequence of any 3879 // non-identity conversion sequence) or, if not that, 3880 if (ImplicitConversionSequence::CompareKind CK 3881 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3882 return CK; 3883 3884 // -- the rank of S1 is better than the rank of S2 (by the rules 3885 // defined below), or, if not that, 3886 ImplicitConversionRank Rank1 = SCS1.getRank(); 3887 ImplicitConversionRank Rank2 = SCS2.getRank(); 3888 if (Rank1 < Rank2) 3889 return ImplicitConversionSequence::Better; 3890 else if (Rank2 < Rank1) 3891 return ImplicitConversionSequence::Worse; 3892 3893 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3894 // are indistinguishable unless one of the following rules 3895 // applies: 3896 3897 // A conversion that is not a conversion of a pointer, or 3898 // pointer to member, to bool is better than another conversion 3899 // that is such a conversion. 3900 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3901 return SCS2.isPointerConversionToBool() 3902 ? ImplicitConversionSequence::Better 3903 : ImplicitConversionSequence::Worse; 3904 3905 // C++14 [over.ics.rank]p4b2: 3906 // This is retroactively applied to C++11 by CWG 1601. 3907 // 3908 // A conversion that promotes an enumeration whose underlying type is fixed 3909 // to its underlying type is better than one that promotes to the promoted 3910 // underlying type, if the two are different. 3911 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3912 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3913 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3914 FEP1 != FEP2) 3915 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3916 ? ImplicitConversionSequence::Better 3917 : ImplicitConversionSequence::Worse; 3918 3919 // C++ [over.ics.rank]p4b2: 3920 // 3921 // If class B is derived directly or indirectly from class A, 3922 // conversion of B* to A* is better than conversion of B* to 3923 // void*, and conversion of A* to void* is better than conversion 3924 // of B* to void*. 3925 bool SCS1ConvertsToVoid 3926 = SCS1.isPointerConversionToVoidPointer(S.Context); 3927 bool SCS2ConvertsToVoid 3928 = SCS2.isPointerConversionToVoidPointer(S.Context); 3929 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3930 // Exactly one of the conversion sequences is a conversion to 3931 // a void pointer; it's the worse conversion. 3932 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3933 : ImplicitConversionSequence::Worse; 3934 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3935 // Neither conversion sequence converts to a void pointer; compare 3936 // their derived-to-base conversions. 3937 if (ImplicitConversionSequence::CompareKind DerivedCK 3938 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3939 return DerivedCK; 3940 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3941 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3942 // Both conversion sequences are conversions to void 3943 // pointers. Compare the source types to determine if there's an 3944 // inheritance relationship in their sources. 3945 QualType FromType1 = SCS1.getFromType(); 3946 QualType FromType2 = SCS2.getFromType(); 3947 3948 // Adjust the types we're converting from via the array-to-pointer 3949 // conversion, if we need to. 3950 if (SCS1.First == ICK_Array_To_Pointer) 3951 FromType1 = S.Context.getArrayDecayedType(FromType1); 3952 if (SCS2.First == ICK_Array_To_Pointer) 3953 FromType2 = S.Context.getArrayDecayedType(FromType2); 3954 3955 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3956 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3957 3958 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3959 return ImplicitConversionSequence::Better; 3960 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3961 return ImplicitConversionSequence::Worse; 3962 3963 // Objective-C++: If one interface is more specific than the 3964 // other, it is the better one. 3965 const ObjCObjectPointerType* FromObjCPtr1 3966 = FromType1->getAs<ObjCObjectPointerType>(); 3967 const ObjCObjectPointerType* FromObjCPtr2 3968 = FromType2->getAs<ObjCObjectPointerType>(); 3969 if (FromObjCPtr1 && FromObjCPtr2) { 3970 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3971 FromObjCPtr2); 3972 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3973 FromObjCPtr1); 3974 if (AssignLeft != AssignRight) { 3975 return AssignLeft? ImplicitConversionSequence::Better 3976 : ImplicitConversionSequence::Worse; 3977 } 3978 } 3979 } 3980 3981 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3982 // bullet 3). 3983 if (ImplicitConversionSequence::CompareKind QualCK 3984 = CompareQualificationConversions(S, SCS1, SCS2)) 3985 return QualCK; 3986 3987 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3988 // Check for a better reference binding based on the kind of bindings. 3989 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3990 return ImplicitConversionSequence::Better; 3991 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3992 return ImplicitConversionSequence::Worse; 3993 3994 // C++ [over.ics.rank]p3b4: 3995 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3996 // which the references refer are the same type except for 3997 // top-level cv-qualifiers, and the type to which the reference 3998 // initialized by S2 refers is more cv-qualified than the type 3999 // to which the reference initialized by S1 refers. 4000 // FIXME: This should have been updated by DR2352, but was overlooked. The 4001 // corrected rule is: 4002 // -- S1 and S2 include reference bindings, and references refer to types 4003 // T1 and T2, respectively, where T2 is reference-compatible with T1. 4004 QualType T1 = SCS1.getToType(2); 4005 QualType T2 = SCS2.getToType(2); 4006 4007 // Objective-C++ ARC: If the references refer to objects with different 4008 // lifetimes, prefer bindings that don't change lifetime. 4009 // 4010 // FIXME: Should this really override ordering based on qualification 4011 // conversions? In the correspnding check for pointers, we treat a case 4012 // where one candidate has worse qualifications and the other has a 4013 // lifetime conversion as ambiguous. 4014 if (SCS1.ObjCLifetimeConversionBinding != 4015 SCS2.ObjCLifetimeConversionBinding && 4016 S.Context.hasSameUnqualifiedType(T1, T2)) { 4017 return SCS1.ObjCLifetimeConversionBinding 4018 ? ImplicitConversionSequence::Worse 4019 : ImplicitConversionSequence::Better; 4020 } 4021 4022 if (!S.Context.hasSameType(T1, T2)) { 4023 // FIXME: Unfortunately, there are pairs of types that admit reference 4024 // bindings in both directions, so we can't shortcut the second check 4025 // here. 4026 bool Better = 4027 S.CompareReferenceRelationship(Loc, T2, T1) == Sema::Ref_Compatible; 4028 bool Worse = 4029 S.CompareReferenceRelationship(Loc, T1, T2) == Sema::Ref_Compatible; 4030 if (Better && Worse) 4031 return ImplicitConversionSequence::Indistinguishable; 4032 if (Better) 4033 return ImplicitConversionSequence::Better; 4034 if (Worse) 4035 return ImplicitConversionSequence::Worse; 4036 } 4037 } 4038 4039 // In Microsoft mode, prefer an integral conversion to a 4040 // floating-to-integral conversion if the integral conversion 4041 // is between types of the same size. 4042 // For example: 4043 // void f(float); 4044 // void f(int); 4045 // int main { 4046 // long a; 4047 // f(a); 4048 // } 4049 // Here, MSVC will call f(int) instead of generating a compile error 4050 // as clang will do in standard mode. 4051 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4052 SCS2.Second == ICK_Floating_Integral && 4053 S.Context.getTypeSize(SCS1.getFromType()) == 4054 S.Context.getTypeSize(SCS1.getToType(2))) 4055 return ImplicitConversionSequence::Better; 4056 4057 // Prefer a compatible vector conversion over a lax vector conversion 4058 // For example: 4059 // 4060 // typedef float __v4sf __attribute__((__vector_size__(16))); 4061 // void f(vector float); 4062 // void f(vector signed int); 4063 // int main() { 4064 // __v4sf a; 4065 // f(a); 4066 // } 4067 // Here, we'd like to choose f(vector float) and not 4068 // report an ambiguous call error 4069 if (SCS1.Second == ICK_Vector_Conversion && 4070 SCS2.Second == ICK_Vector_Conversion) { 4071 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4072 SCS1.getFromType(), SCS1.getToType(2)); 4073 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4074 SCS2.getFromType(), SCS2.getToType(2)); 4075 4076 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4077 return SCS1IsCompatibleVectorConversion 4078 ? ImplicitConversionSequence::Better 4079 : ImplicitConversionSequence::Worse; 4080 } 4081 4082 return ImplicitConversionSequence::Indistinguishable; 4083 } 4084 4085 /// CompareQualificationConversions - Compares two standard conversion 4086 /// sequences to determine whether they can be ranked based on their 4087 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4088 static ImplicitConversionSequence::CompareKind 4089 CompareQualificationConversions(Sema &S, 4090 const StandardConversionSequence& SCS1, 4091 const StandardConversionSequence& SCS2) { 4092 // C++ 13.3.3.2p3: 4093 // -- S1 and S2 differ only in their qualification conversion and 4094 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4095 // cv-qualification signature of type T1 is a proper subset of 4096 // the cv-qualification signature of type T2, and S1 is not the 4097 // deprecated string literal array-to-pointer conversion (4.2). 4098 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4099 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4100 return ImplicitConversionSequence::Indistinguishable; 4101 4102 // FIXME: the example in the standard doesn't use a qualification 4103 // conversion (!) 4104 QualType T1 = SCS1.getToType(2); 4105 QualType T2 = SCS2.getToType(2); 4106 T1 = S.Context.getCanonicalType(T1); 4107 T2 = S.Context.getCanonicalType(T2); 4108 Qualifiers T1Quals, T2Quals; 4109 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4110 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4111 4112 // If the types are the same, we won't learn anything by unwrapped 4113 // them. 4114 if (UnqualT1 == UnqualT2) 4115 return ImplicitConversionSequence::Indistinguishable; 4116 4117 // If the type is an array type, promote the element qualifiers to the type 4118 // for comparison. 4119 if (isa<ArrayType>(T1) && T1Quals) 4120 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4121 if (isa<ArrayType>(T2) && T2Quals) 4122 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4123 4124 ImplicitConversionSequence::CompareKind Result 4125 = ImplicitConversionSequence::Indistinguishable; 4126 4127 // Objective-C++ ARC: 4128 // Prefer qualification conversions not involving a change in lifetime 4129 // to qualification conversions that do not change lifetime. 4130 if (SCS1.QualificationIncludesObjCLifetime != 4131 SCS2.QualificationIncludesObjCLifetime) { 4132 Result = SCS1.QualificationIncludesObjCLifetime 4133 ? ImplicitConversionSequence::Worse 4134 : ImplicitConversionSequence::Better; 4135 } 4136 4137 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4138 // Within each iteration of the loop, we check the qualifiers to 4139 // determine if this still looks like a qualification 4140 // conversion. Then, if all is well, we unwrap one more level of 4141 // pointers or pointers-to-members and do it all again 4142 // until there are no more pointers or pointers-to-members left 4143 // to unwrap. This essentially mimics what 4144 // IsQualificationConversion does, but here we're checking for a 4145 // strict subset of qualifiers. 4146 if (T1.getQualifiers().withoutObjCLifetime() == 4147 T2.getQualifiers().withoutObjCLifetime()) 4148 // The qualifiers are the same, so this doesn't tell us anything 4149 // about how the sequences rank. 4150 // ObjC ownership quals are omitted above as they interfere with 4151 // the ARC overload rule. 4152 ; 4153 else if (T2.isMoreQualifiedThan(T1)) { 4154 // T1 has fewer qualifiers, so it could be the better sequence. 4155 if (Result == ImplicitConversionSequence::Worse) 4156 // Neither has qualifiers that are a subset of the other's 4157 // qualifiers. 4158 return ImplicitConversionSequence::Indistinguishable; 4159 4160 Result = ImplicitConversionSequence::Better; 4161 } else if (T1.isMoreQualifiedThan(T2)) { 4162 // T2 has fewer qualifiers, so it could be the better sequence. 4163 if (Result == ImplicitConversionSequence::Better) 4164 // Neither has qualifiers that are a subset of the other's 4165 // qualifiers. 4166 return ImplicitConversionSequence::Indistinguishable; 4167 4168 Result = ImplicitConversionSequence::Worse; 4169 } else { 4170 // Qualifiers are disjoint. 4171 return ImplicitConversionSequence::Indistinguishable; 4172 } 4173 4174 // If the types after this point are equivalent, we're done. 4175 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4176 break; 4177 } 4178 4179 // Check that the winning standard conversion sequence isn't using 4180 // the deprecated string literal array to pointer conversion. 4181 switch (Result) { 4182 case ImplicitConversionSequence::Better: 4183 if (SCS1.DeprecatedStringLiteralToCharPtr) 4184 Result = ImplicitConversionSequence::Indistinguishable; 4185 break; 4186 4187 case ImplicitConversionSequence::Indistinguishable: 4188 break; 4189 4190 case ImplicitConversionSequence::Worse: 4191 if (SCS2.DeprecatedStringLiteralToCharPtr) 4192 Result = ImplicitConversionSequence::Indistinguishable; 4193 break; 4194 } 4195 4196 return Result; 4197 } 4198 4199 /// CompareDerivedToBaseConversions - Compares two standard conversion 4200 /// sequences to determine whether they can be ranked based on their 4201 /// various kinds of derived-to-base conversions (C++ 4202 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4203 /// conversions between Objective-C interface types. 4204 static ImplicitConversionSequence::CompareKind 4205 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4206 const StandardConversionSequence& SCS1, 4207 const StandardConversionSequence& SCS2) { 4208 QualType FromType1 = SCS1.getFromType(); 4209 QualType ToType1 = SCS1.getToType(1); 4210 QualType FromType2 = SCS2.getFromType(); 4211 QualType ToType2 = SCS2.getToType(1); 4212 4213 // Adjust the types we're converting from via the array-to-pointer 4214 // conversion, if we need to. 4215 if (SCS1.First == ICK_Array_To_Pointer) 4216 FromType1 = S.Context.getArrayDecayedType(FromType1); 4217 if (SCS2.First == ICK_Array_To_Pointer) 4218 FromType2 = S.Context.getArrayDecayedType(FromType2); 4219 4220 // Canonicalize all of the types. 4221 FromType1 = S.Context.getCanonicalType(FromType1); 4222 ToType1 = S.Context.getCanonicalType(ToType1); 4223 FromType2 = S.Context.getCanonicalType(FromType2); 4224 ToType2 = S.Context.getCanonicalType(ToType2); 4225 4226 // C++ [over.ics.rank]p4b3: 4227 // 4228 // If class B is derived directly or indirectly from class A and 4229 // class C is derived directly or indirectly from B, 4230 // 4231 // Compare based on pointer conversions. 4232 if (SCS1.Second == ICK_Pointer_Conversion && 4233 SCS2.Second == ICK_Pointer_Conversion && 4234 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4235 FromType1->isPointerType() && FromType2->isPointerType() && 4236 ToType1->isPointerType() && ToType2->isPointerType()) { 4237 QualType FromPointee1 = 4238 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4239 QualType ToPointee1 = 4240 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4241 QualType FromPointee2 = 4242 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4243 QualType ToPointee2 = 4244 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4245 4246 // -- conversion of C* to B* is better than conversion of C* to A*, 4247 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4248 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4249 return ImplicitConversionSequence::Better; 4250 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4251 return ImplicitConversionSequence::Worse; 4252 } 4253 4254 // -- conversion of B* to A* is better than conversion of C* to A*, 4255 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4256 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4257 return ImplicitConversionSequence::Better; 4258 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4259 return ImplicitConversionSequence::Worse; 4260 } 4261 } else if (SCS1.Second == ICK_Pointer_Conversion && 4262 SCS2.Second == ICK_Pointer_Conversion) { 4263 const ObjCObjectPointerType *FromPtr1 4264 = FromType1->getAs<ObjCObjectPointerType>(); 4265 const ObjCObjectPointerType *FromPtr2 4266 = FromType2->getAs<ObjCObjectPointerType>(); 4267 const ObjCObjectPointerType *ToPtr1 4268 = ToType1->getAs<ObjCObjectPointerType>(); 4269 const ObjCObjectPointerType *ToPtr2 4270 = ToType2->getAs<ObjCObjectPointerType>(); 4271 4272 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4273 // Apply the same conversion ranking rules for Objective-C pointer types 4274 // that we do for C++ pointers to class types. However, we employ the 4275 // Objective-C pseudo-subtyping relationship used for assignment of 4276 // Objective-C pointer types. 4277 bool FromAssignLeft 4278 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4279 bool FromAssignRight 4280 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4281 bool ToAssignLeft 4282 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4283 bool ToAssignRight 4284 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4285 4286 // A conversion to an a non-id object pointer type or qualified 'id' 4287 // type is better than a conversion to 'id'. 4288 if (ToPtr1->isObjCIdType() && 4289 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4290 return ImplicitConversionSequence::Worse; 4291 if (ToPtr2->isObjCIdType() && 4292 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4293 return ImplicitConversionSequence::Better; 4294 4295 // A conversion to a non-id object pointer type is better than a 4296 // conversion to a qualified 'id' type 4297 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4298 return ImplicitConversionSequence::Worse; 4299 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4300 return ImplicitConversionSequence::Better; 4301 4302 // A conversion to an a non-Class object pointer type or qualified 'Class' 4303 // type is better than a conversion to 'Class'. 4304 if (ToPtr1->isObjCClassType() && 4305 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4306 return ImplicitConversionSequence::Worse; 4307 if (ToPtr2->isObjCClassType() && 4308 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4309 return ImplicitConversionSequence::Better; 4310 4311 // A conversion to a non-Class object pointer type is better than a 4312 // conversion to a qualified 'Class' type. 4313 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4314 return ImplicitConversionSequence::Worse; 4315 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4316 return ImplicitConversionSequence::Better; 4317 4318 // -- "conversion of C* to B* is better than conversion of C* to A*," 4319 if (S.Context.hasSameType(FromType1, FromType2) && 4320 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4321 (ToAssignLeft != ToAssignRight)) { 4322 if (FromPtr1->isSpecialized()) { 4323 // "conversion of B<A> * to B * is better than conversion of B * to 4324 // C *. 4325 bool IsFirstSame = 4326 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4327 bool IsSecondSame = 4328 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4329 if (IsFirstSame) { 4330 if (!IsSecondSame) 4331 return ImplicitConversionSequence::Better; 4332 } else if (IsSecondSame) 4333 return ImplicitConversionSequence::Worse; 4334 } 4335 return ToAssignLeft? ImplicitConversionSequence::Worse 4336 : ImplicitConversionSequence::Better; 4337 } 4338 4339 // -- "conversion of B* to A* is better than conversion of C* to A*," 4340 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4341 (FromAssignLeft != FromAssignRight)) 4342 return FromAssignLeft? ImplicitConversionSequence::Better 4343 : ImplicitConversionSequence::Worse; 4344 } 4345 } 4346 4347 // Ranking of member-pointer types. 4348 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4349 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4350 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4351 const MemberPointerType * FromMemPointer1 = 4352 FromType1->getAs<MemberPointerType>(); 4353 const MemberPointerType * ToMemPointer1 = 4354 ToType1->getAs<MemberPointerType>(); 4355 const MemberPointerType * FromMemPointer2 = 4356 FromType2->getAs<MemberPointerType>(); 4357 const MemberPointerType * ToMemPointer2 = 4358 ToType2->getAs<MemberPointerType>(); 4359 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4360 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4361 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4362 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4363 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4364 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4365 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4366 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4367 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4368 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4369 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4370 return ImplicitConversionSequence::Worse; 4371 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4372 return ImplicitConversionSequence::Better; 4373 } 4374 // conversion of B::* to C::* is better than conversion of A::* to C::* 4375 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4376 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4377 return ImplicitConversionSequence::Better; 4378 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4379 return ImplicitConversionSequence::Worse; 4380 } 4381 } 4382 4383 if (SCS1.Second == ICK_Derived_To_Base) { 4384 // -- conversion of C to B is better than conversion of C to A, 4385 // -- binding of an expression of type C to a reference of type 4386 // B& is better than binding an expression of type C to a 4387 // reference of type A&, 4388 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4389 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4390 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4391 return ImplicitConversionSequence::Better; 4392 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4393 return ImplicitConversionSequence::Worse; 4394 } 4395 4396 // -- conversion of B to A is better than conversion of C to A. 4397 // -- binding of an expression of type B to a reference of type 4398 // A& is better than binding an expression of type C to a 4399 // reference of type A&, 4400 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4401 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4402 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4403 return ImplicitConversionSequence::Better; 4404 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4405 return ImplicitConversionSequence::Worse; 4406 } 4407 } 4408 4409 return ImplicitConversionSequence::Indistinguishable; 4410 } 4411 4412 /// Determine whether the given type is valid, e.g., it is not an invalid 4413 /// C++ class. 4414 static bool isTypeValid(QualType T) { 4415 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4416 return !Record->isInvalidDecl(); 4417 4418 return true; 4419 } 4420 4421 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4422 if (!T.getQualifiers().hasUnaligned()) 4423 return T; 4424 4425 Qualifiers Q; 4426 T = Ctx.getUnqualifiedArrayType(T, Q); 4427 Q.removeUnaligned(); 4428 return Ctx.getQualifiedType(T, Q); 4429 } 4430 4431 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4432 /// determine whether they are reference-compatible, 4433 /// reference-related, or incompatible, for use in C++ initialization by 4434 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4435 /// type, and the first type (T1) is the pointee type of the reference 4436 /// type being initialized. 4437 Sema::ReferenceCompareResult 4438 Sema::CompareReferenceRelationship(SourceLocation Loc, 4439 QualType OrigT1, QualType OrigT2, 4440 ReferenceConversions *ConvOut) { 4441 assert(!OrigT1->isReferenceType() && 4442 "T1 must be the pointee type of the reference type"); 4443 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4444 4445 QualType T1 = Context.getCanonicalType(OrigT1); 4446 QualType T2 = Context.getCanonicalType(OrigT2); 4447 Qualifiers T1Quals, T2Quals; 4448 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4449 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4450 4451 ReferenceConversions ConvTmp; 4452 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4453 Conv = ReferenceConversions(); 4454 4455 // C++2a [dcl.init.ref]p4: 4456 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4457 // reference-related to "cv2 T2" if T1 is similar to T2, or 4458 // T1 is a base class of T2. 4459 // "cv1 T1" is reference-compatible with "cv2 T2" if 4460 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4461 // "pointer to cv1 T1" via a standard conversion sequence. 4462 4463 // Check for standard conversions we can apply to pointers: derived-to-base 4464 // conversions, ObjC pointer conversions, and function pointer conversions. 4465 // (Qualification conversions are checked last.) 4466 QualType ConvertedT2; 4467 if (UnqualT1 == UnqualT2) { 4468 // Nothing to do. 4469 } else if (isCompleteType(Loc, OrigT2) && 4470 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4471 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4472 Conv |= ReferenceConversions::DerivedToBase; 4473 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4474 UnqualT2->isObjCObjectOrInterfaceType() && 4475 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4476 Conv |= ReferenceConversions::ObjC; 4477 else if (UnqualT2->isFunctionType() && 4478 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4479 Conv |= ReferenceConversions::Function; 4480 // No need to check qualifiers; function types don't have them. 4481 return Ref_Compatible; 4482 } 4483 bool ConvertedReferent = Conv != 0; 4484 4485 // We can have a qualification conversion. Compute whether the types are 4486 // similar at the same time. 4487 bool PreviousToQualsIncludeConst = true; 4488 do { 4489 if (T1 == T2) 4490 break; 4491 4492 // We will need a qualification conversion. 4493 Conv |= ReferenceConversions::Qualification; 4494 4495 // MS compiler ignores __unaligned qualifier for references; do the same. 4496 T1 = withoutUnaligned(Context, T1); 4497 T2 = withoutUnaligned(Context, T2); 4498 4499 // If we find a qualifier mismatch, the types are not reference-compatible, 4500 // but are still be reference-related if they're similar. 4501 bool ObjCLifetimeConversion = false; 4502 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, 4503 PreviousToQualsIncludeConst, 4504 ObjCLifetimeConversion)) 4505 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4506 ? Ref_Related 4507 : Ref_Incompatible; 4508 4509 // FIXME: Should we track this for any level other than the first? 4510 if (ObjCLifetimeConversion) 4511 Conv |= ReferenceConversions::ObjCLifetime; 4512 } while (Context.UnwrapSimilarTypes(T1, T2)); 4513 4514 // At this point, if the types are reference-related, we must either have the 4515 // same inner type (ignoring qualifiers), or must have already worked out how 4516 // to convert the referent. 4517 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4518 ? Ref_Compatible 4519 : Ref_Incompatible; 4520 } 4521 4522 /// Look for a user-defined conversion to a value reference-compatible 4523 /// with DeclType. Return true if something definite is found. 4524 static bool 4525 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4526 QualType DeclType, SourceLocation DeclLoc, 4527 Expr *Init, QualType T2, bool AllowRvalues, 4528 bool AllowExplicit) { 4529 assert(T2->isRecordType() && "Can only find conversions of record types."); 4530 CXXRecordDecl *T2RecordDecl 4531 = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4532 4533 OverloadCandidateSet CandidateSet( 4534 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4535 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4536 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4537 NamedDecl *D = *I; 4538 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4539 if (isa<UsingShadowDecl>(D)) 4540 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4541 4542 FunctionTemplateDecl *ConvTemplate 4543 = dyn_cast<FunctionTemplateDecl>(D); 4544 CXXConversionDecl *Conv; 4545 if (ConvTemplate) 4546 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4547 else 4548 Conv = cast<CXXConversionDecl>(D); 4549 4550 // If this is an explicit conversion, and we're not allowed to consider 4551 // explicit conversions, skip it. 4552 if (!AllowExplicit && Conv->isExplicit()) 4553 continue; 4554 4555 if (AllowRvalues) { 4556 // If we are initializing an rvalue reference, don't permit conversion 4557 // functions that return lvalues. 4558 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4559 const ReferenceType *RefType 4560 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4561 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4562 continue; 4563 } 4564 4565 if (!ConvTemplate && 4566 S.CompareReferenceRelationship( 4567 DeclLoc, 4568 Conv->getConversionType() 4569 .getNonReferenceType() 4570 .getUnqualifiedType(), 4571 DeclType.getNonReferenceType().getUnqualifiedType()) == 4572 Sema::Ref_Incompatible) 4573 continue; 4574 } else { 4575 // If the conversion function doesn't return a reference type, 4576 // it can't be considered for this conversion. An rvalue reference 4577 // is only acceptable if its referencee is a function type. 4578 4579 const ReferenceType *RefType = 4580 Conv->getConversionType()->getAs<ReferenceType>(); 4581 if (!RefType || 4582 (!RefType->isLValueReferenceType() && 4583 !RefType->getPointeeType()->isFunctionType())) 4584 continue; 4585 } 4586 4587 if (ConvTemplate) 4588 S.AddTemplateConversionCandidate( 4589 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4590 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4591 else 4592 S.AddConversionCandidate( 4593 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4594 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4595 } 4596 4597 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4598 4599 OverloadCandidateSet::iterator Best; 4600 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4601 case OR_Success: 4602 // C++ [over.ics.ref]p1: 4603 // 4604 // [...] If the parameter binds directly to the result of 4605 // applying a conversion function to the argument 4606 // expression, the implicit conversion sequence is a 4607 // user-defined conversion sequence (13.3.3.1.2), with the 4608 // second standard conversion sequence either an identity 4609 // conversion or, if the conversion function returns an 4610 // entity of a type that is a derived class of the parameter 4611 // type, a derived-to-base Conversion. 4612 if (!Best->FinalConversion.DirectBinding) 4613 return false; 4614 4615 ICS.setUserDefined(); 4616 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4617 ICS.UserDefined.After = Best->FinalConversion; 4618 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4619 ICS.UserDefined.ConversionFunction = Best->Function; 4620 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4621 ICS.UserDefined.EllipsisConversion = false; 4622 assert(ICS.UserDefined.After.ReferenceBinding && 4623 ICS.UserDefined.After.DirectBinding && 4624 "Expected a direct reference binding!"); 4625 return true; 4626 4627 case OR_Ambiguous: 4628 ICS.setAmbiguous(); 4629 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4630 Cand != CandidateSet.end(); ++Cand) 4631 if (Cand->Best) 4632 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4633 return true; 4634 4635 case OR_No_Viable_Function: 4636 case OR_Deleted: 4637 // There was no suitable conversion, or we found a deleted 4638 // conversion; continue with other checks. 4639 return false; 4640 } 4641 4642 llvm_unreachable("Invalid OverloadResult!"); 4643 } 4644 4645 /// Compute an implicit conversion sequence for reference 4646 /// initialization. 4647 static ImplicitConversionSequence 4648 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4649 SourceLocation DeclLoc, 4650 bool SuppressUserConversions, 4651 bool AllowExplicit) { 4652 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4653 4654 // Most paths end in a failed conversion. 4655 ImplicitConversionSequence ICS; 4656 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4657 4658 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4659 QualType T2 = Init->getType(); 4660 4661 // If the initializer is the address of an overloaded function, try 4662 // to resolve the overloaded function. If all goes well, T2 is the 4663 // type of the resulting function. 4664 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4665 DeclAccessPair Found; 4666 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4667 false, Found)) 4668 T2 = Fn->getType(); 4669 } 4670 4671 // Compute some basic properties of the types and the initializer. 4672 bool isRValRef = DeclType->isRValueReferenceType(); 4673 Expr::Classification InitCategory = Init->Classify(S.Context); 4674 4675 Sema::ReferenceConversions RefConv; 4676 Sema::ReferenceCompareResult RefRelationship = 4677 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4678 4679 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4680 ICS.setStandard(); 4681 ICS.Standard.First = ICK_Identity; 4682 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4683 ? ICK_Derived_To_Base 4684 : (RefConv & Sema::ReferenceConversions::ObjC) 4685 ? ICK_Compatible_Conversion 4686 : ICK_Identity; 4687 ICS.Standard.Third = ICK_Identity; 4688 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4689 ICS.Standard.setToType(0, T2); 4690 ICS.Standard.setToType(1, T1); 4691 ICS.Standard.setToType(2, T1); 4692 ICS.Standard.ReferenceBinding = true; 4693 ICS.Standard.DirectBinding = BindsDirectly; 4694 ICS.Standard.IsLvalueReference = !isRValRef; 4695 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4696 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4697 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4698 ICS.Standard.ObjCLifetimeConversionBinding = 4699 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4700 ICS.Standard.CopyConstructor = nullptr; 4701 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4702 }; 4703 4704 // C++0x [dcl.init.ref]p5: 4705 // A reference to type "cv1 T1" is initialized by an expression 4706 // of type "cv2 T2" as follows: 4707 4708 // -- If reference is an lvalue reference and the initializer expression 4709 if (!isRValRef) { 4710 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4711 // reference-compatible with "cv2 T2," or 4712 // 4713 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4714 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4715 // C++ [over.ics.ref]p1: 4716 // When a parameter of reference type binds directly (8.5.3) 4717 // to an argument expression, the implicit conversion sequence 4718 // is the identity conversion, unless the argument expression 4719 // has a type that is a derived class of the parameter type, 4720 // in which case the implicit conversion sequence is a 4721 // derived-to-base Conversion (13.3.3.1). 4722 SetAsReferenceBinding(/*BindsDirectly=*/true); 4723 4724 // Nothing more to do: the inaccessibility/ambiguity check for 4725 // derived-to-base conversions is suppressed when we're 4726 // computing the implicit conversion sequence (C++ 4727 // [over.best.ics]p2). 4728 return ICS; 4729 } 4730 4731 // -- has a class type (i.e., T2 is a class type), where T1 is 4732 // not reference-related to T2, and can be implicitly 4733 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4734 // is reference-compatible with "cv3 T3" 92) (this 4735 // conversion is selected by enumerating the applicable 4736 // conversion functions (13.3.1.6) and choosing the best 4737 // one through overload resolution (13.3)), 4738 if (!SuppressUserConversions && T2->isRecordType() && 4739 S.isCompleteType(DeclLoc, T2) && 4740 RefRelationship == Sema::Ref_Incompatible) { 4741 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4742 Init, T2, /*AllowRvalues=*/false, 4743 AllowExplicit)) 4744 return ICS; 4745 } 4746 } 4747 4748 // -- Otherwise, the reference shall be an lvalue reference to a 4749 // non-volatile const type (i.e., cv1 shall be const), or the reference 4750 // shall be an rvalue reference. 4751 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4752 return ICS; 4753 4754 // -- If the initializer expression 4755 // 4756 // -- is an xvalue, class prvalue, array prvalue or function 4757 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4758 if (RefRelationship == Sema::Ref_Compatible && 4759 (InitCategory.isXValue() || 4760 (InitCategory.isPRValue() && 4761 (T2->isRecordType() || T2->isArrayType())) || 4762 (InitCategory.isLValue() && T2->isFunctionType()))) { 4763 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4764 // binding unless we're binding to a class prvalue. 4765 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4766 // allow the use of rvalue references in C++98/03 for the benefit of 4767 // standard library implementors; therefore, we need the xvalue check here. 4768 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4769 !(InitCategory.isPRValue() || T2->isRecordType())); 4770 return ICS; 4771 } 4772 4773 // -- has a class type (i.e., T2 is a class type), where T1 is not 4774 // reference-related to T2, and can be implicitly converted to 4775 // an xvalue, class prvalue, or function lvalue of type 4776 // "cv3 T3", where "cv1 T1" is reference-compatible with 4777 // "cv3 T3", 4778 // 4779 // then the reference is bound to the value of the initializer 4780 // expression in the first case and to the result of the conversion 4781 // in the second case (or, in either case, to an appropriate base 4782 // class subobject). 4783 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4784 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4785 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4786 Init, T2, /*AllowRvalues=*/true, 4787 AllowExplicit)) { 4788 // In the second case, if the reference is an rvalue reference 4789 // and the second standard conversion sequence of the 4790 // user-defined conversion sequence includes an lvalue-to-rvalue 4791 // conversion, the program is ill-formed. 4792 if (ICS.isUserDefined() && isRValRef && 4793 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4794 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4795 4796 return ICS; 4797 } 4798 4799 // A temporary of function type cannot be created; don't even try. 4800 if (T1->isFunctionType()) 4801 return ICS; 4802 4803 // -- Otherwise, a temporary of type "cv1 T1" is created and 4804 // initialized from the initializer expression using the 4805 // rules for a non-reference copy initialization (8.5). The 4806 // reference is then bound to the temporary. If T1 is 4807 // reference-related to T2, cv1 must be the same 4808 // cv-qualification as, or greater cv-qualification than, 4809 // cv2; otherwise, the program is ill-formed. 4810 if (RefRelationship == Sema::Ref_Related) { 4811 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4812 // we would be reference-compatible or reference-compatible with 4813 // added qualification. But that wasn't the case, so the reference 4814 // initialization fails. 4815 // 4816 // Note that we only want to check address spaces and cvr-qualifiers here. 4817 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4818 Qualifiers T1Quals = T1.getQualifiers(); 4819 Qualifiers T2Quals = T2.getQualifiers(); 4820 T1Quals.removeObjCGCAttr(); 4821 T1Quals.removeObjCLifetime(); 4822 T2Quals.removeObjCGCAttr(); 4823 T2Quals.removeObjCLifetime(); 4824 // MS compiler ignores __unaligned qualifier for references; do the same. 4825 T1Quals.removeUnaligned(); 4826 T2Quals.removeUnaligned(); 4827 if (!T1Quals.compatiblyIncludes(T2Quals)) 4828 return ICS; 4829 } 4830 4831 // If at least one of the types is a class type, the types are not 4832 // related, and we aren't allowed any user conversions, the 4833 // reference binding fails. This case is important for breaking 4834 // recursion, since TryImplicitConversion below will attempt to 4835 // create a temporary through the use of a copy constructor. 4836 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4837 (T1->isRecordType() || T2->isRecordType())) 4838 return ICS; 4839 4840 // If T1 is reference-related to T2 and the reference is an rvalue 4841 // reference, the initializer expression shall not be an lvalue. 4842 if (RefRelationship >= Sema::Ref_Related && 4843 isRValRef && Init->Classify(S.Context).isLValue()) 4844 return ICS; 4845 4846 // C++ [over.ics.ref]p2: 4847 // When a parameter of reference type is not bound directly to 4848 // an argument expression, the conversion sequence is the one 4849 // required to convert the argument expression to the 4850 // underlying type of the reference according to 4851 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4852 // to copy-initializing a temporary of the underlying type with 4853 // the argument expression. Any difference in top-level 4854 // cv-qualification is subsumed by the initialization itself 4855 // and does not constitute a conversion. 4856 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4857 /*AllowExplicit=*/false, 4858 /*InOverloadResolution=*/false, 4859 /*CStyle=*/false, 4860 /*AllowObjCWritebackConversion=*/false, 4861 /*AllowObjCConversionOnExplicit=*/false); 4862 4863 // Of course, that's still a reference binding. 4864 if (ICS.isStandard()) { 4865 ICS.Standard.ReferenceBinding = true; 4866 ICS.Standard.IsLvalueReference = !isRValRef; 4867 ICS.Standard.BindsToFunctionLvalue = false; 4868 ICS.Standard.BindsToRvalue = true; 4869 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4870 ICS.Standard.ObjCLifetimeConversionBinding = false; 4871 } else if (ICS.isUserDefined()) { 4872 const ReferenceType *LValRefType = 4873 ICS.UserDefined.ConversionFunction->getReturnType() 4874 ->getAs<LValueReferenceType>(); 4875 4876 // C++ [over.ics.ref]p3: 4877 // Except for an implicit object parameter, for which see 13.3.1, a 4878 // standard conversion sequence cannot be formed if it requires [...] 4879 // binding an rvalue reference to an lvalue other than a function 4880 // lvalue. 4881 // Note that the function case is not possible here. 4882 if (DeclType->isRValueReferenceType() && LValRefType) { 4883 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4884 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4885 // reference to an rvalue! 4886 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4887 return ICS; 4888 } 4889 4890 ICS.UserDefined.After.ReferenceBinding = true; 4891 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4892 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4893 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4894 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4895 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4896 } 4897 4898 return ICS; 4899 } 4900 4901 static ImplicitConversionSequence 4902 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4903 bool SuppressUserConversions, 4904 bool InOverloadResolution, 4905 bool AllowObjCWritebackConversion, 4906 bool AllowExplicit = false); 4907 4908 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4909 /// initializer list From. 4910 static ImplicitConversionSequence 4911 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4912 bool SuppressUserConversions, 4913 bool InOverloadResolution, 4914 bool AllowObjCWritebackConversion) { 4915 // C++11 [over.ics.list]p1: 4916 // When an argument is an initializer list, it is not an expression and 4917 // special rules apply for converting it to a parameter type. 4918 4919 ImplicitConversionSequence Result; 4920 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4921 4922 // We need a complete type for what follows. Incomplete types can never be 4923 // initialized from init lists. 4924 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4925 return Result; 4926 4927 // Per DR1467: 4928 // If the parameter type is a class X and the initializer list has a single 4929 // element of type cv U, where U is X or a class derived from X, the 4930 // implicit conversion sequence is the one required to convert the element 4931 // to the parameter type. 4932 // 4933 // Otherwise, if the parameter type is a character array [... ] 4934 // and the initializer list has a single element that is an 4935 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4936 // implicit conversion sequence is the identity conversion. 4937 if (From->getNumInits() == 1) { 4938 if (ToType->isRecordType()) { 4939 QualType InitType = From->getInit(0)->getType(); 4940 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4941 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4942 return TryCopyInitialization(S, From->getInit(0), ToType, 4943 SuppressUserConversions, 4944 InOverloadResolution, 4945 AllowObjCWritebackConversion); 4946 } 4947 // FIXME: Check the other conditions here: array of character type, 4948 // initializer is a string literal. 4949 if (ToType->isArrayType()) { 4950 InitializedEntity Entity = 4951 InitializedEntity::InitializeParameter(S.Context, ToType, 4952 /*Consumed=*/false); 4953 if (S.CanPerformCopyInitialization(Entity, From)) { 4954 Result.setStandard(); 4955 Result.Standard.setAsIdentityConversion(); 4956 Result.Standard.setFromType(ToType); 4957 Result.Standard.setAllToTypes(ToType); 4958 return Result; 4959 } 4960 } 4961 } 4962 4963 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4964 // C++11 [over.ics.list]p2: 4965 // If the parameter type is std::initializer_list<X> or "array of X" and 4966 // all the elements can be implicitly converted to X, the implicit 4967 // conversion sequence is the worst conversion necessary to convert an 4968 // element of the list to X. 4969 // 4970 // C++14 [over.ics.list]p3: 4971 // Otherwise, if the parameter type is "array of N X", if the initializer 4972 // list has exactly N elements or if it has fewer than N elements and X is 4973 // default-constructible, and if all the elements of the initializer list 4974 // can be implicitly converted to X, the implicit conversion sequence is 4975 // the worst conversion necessary to convert an element of the list to X. 4976 // 4977 // FIXME: We're missing a lot of these checks. 4978 bool toStdInitializerList = false; 4979 QualType X; 4980 if (ToType->isArrayType()) 4981 X = S.Context.getAsArrayType(ToType)->getElementType(); 4982 else 4983 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4984 if (!X.isNull()) { 4985 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4986 Expr *Init = From->getInit(i); 4987 ImplicitConversionSequence ICS = 4988 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4989 InOverloadResolution, 4990 AllowObjCWritebackConversion); 4991 // If a single element isn't convertible, fail. 4992 if (ICS.isBad()) { 4993 Result = ICS; 4994 break; 4995 } 4996 // Otherwise, look for the worst conversion. 4997 if (Result.isBad() || CompareImplicitConversionSequences( 4998 S, From->getBeginLoc(), ICS, Result) == 4999 ImplicitConversionSequence::Worse) 5000 Result = ICS; 5001 } 5002 5003 // For an empty list, we won't have computed any conversion sequence. 5004 // Introduce the identity conversion sequence. 5005 if (From->getNumInits() == 0) { 5006 Result.setStandard(); 5007 Result.Standard.setAsIdentityConversion(); 5008 Result.Standard.setFromType(ToType); 5009 Result.Standard.setAllToTypes(ToType); 5010 } 5011 5012 Result.setStdInitializerListElement(toStdInitializerList); 5013 return Result; 5014 } 5015 5016 // C++14 [over.ics.list]p4: 5017 // C++11 [over.ics.list]p3: 5018 // Otherwise, if the parameter is a non-aggregate class X and overload 5019 // resolution chooses a single best constructor [...] the implicit 5020 // conversion sequence is a user-defined conversion sequence. If multiple 5021 // constructors are viable but none is better than the others, the 5022 // implicit conversion sequence is a user-defined conversion sequence. 5023 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5024 // This function can deal with initializer lists. 5025 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5026 /*AllowExplicit=*/false, 5027 InOverloadResolution, /*CStyle=*/false, 5028 AllowObjCWritebackConversion, 5029 /*AllowObjCConversionOnExplicit=*/false); 5030 } 5031 5032 // C++14 [over.ics.list]p5: 5033 // C++11 [over.ics.list]p4: 5034 // Otherwise, if the parameter has an aggregate type which can be 5035 // initialized from the initializer list [...] the implicit conversion 5036 // sequence is a user-defined conversion sequence. 5037 if (ToType->isAggregateType()) { 5038 // Type is an aggregate, argument is an init list. At this point it comes 5039 // down to checking whether the initialization works. 5040 // FIXME: Find out whether this parameter is consumed or not. 5041 InitializedEntity Entity = 5042 InitializedEntity::InitializeParameter(S.Context, ToType, 5043 /*Consumed=*/false); 5044 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5045 From)) { 5046 Result.setUserDefined(); 5047 Result.UserDefined.Before.setAsIdentityConversion(); 5048 // Initializer lists don't have a type. 5049 Result.UserDefined.Before.setFromType(QualType()); 5050 Result.UserDefined.Before.setAllToTypes(QualType()); 5051 5052 Result.UserDefined.After.setAsIdentityConversion(); 5053 Result.UserDefined.After.setFromType(ToType); 5054 Result.UserDefined.After.setAllToTypes(ToType); 5055 Result.UserDefined.ConversionFunction = nullptr; 5056 } 5057 return Result; 5058 } 5059 5060 // C++14 [over.ics.list]p6: 5061 // C++11 [over.ics.list]p5: 5062 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5063 if (ToType->isReferenceType()) { 5064 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5065 // mention initializer lists in any way. So we go by what list- 5066 // initialization would do and try to extrapolate from that. 5067 5068 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5069 5070 // If the initializer list has a single element that is reference-related 5071 // to the parameter type, we initialize the reference from that. 5072 if (From->getNumInits() == 1) { 5073 Expr *Init = From->getInit(0); 5074 5075 QualType T2 = Init->getType(); 5076 5077 // If the initializer is the address of an overloaded function, try 5078 // to resolve the overloaded function. If all goes well, T2 is the 5079 // type of the resulting function. 5080 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5081 DeclAccessPair Found; 5082 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5083 Init, ToType, false, Found)) 5084 T2 = Fn->getType(); 5085 } 5086 5087 // Compute some basic properties of the types and the initializer. 5088 Sema::ReferenceCompareResult RefRelationship = 5089 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5090 5091 if (RefRelationship >= Sema::Ref_Related) { 5092 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5093 SuppressUserConversions, 5094 /*AllowExplicit=*/false); 5095 } 5096 } 5097 5098 // Otherwise, we bind the reference to a temporary created from the 5099 // initializer list. 5100 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5101 InOverloadResolution, 5102 AllowObjCWritebackConversion); 5103 if (Result.isFailure()) 5104 return Result; 5105 assert(!Result.isEllipsis() && 5106 "Sub-initialization cannot result in ellipsis conversion."); 5107 5108 // Can we even bind to a temporary? 5109 if (ToType->isRValueReferenceType() || 5110 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5111 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5112 Result.UserDefined.After; 5113 SCS.ReferenceBinding = true; 5114 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5115 SCS.BindsToRvalue = true; 5116 SCS.BindsToFunctionLvalue = false; 5117 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5118 SCS.ObjCLifetimeConversionBinding = false; 5119 } else 5120 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5121 From, ToType); 5122 return Result; 5123 } 5124 5125 // C++14 [over.ics.list]p7: 5126 // C++11 [over.ics.list]p6: 5127 // Otherwise, if the parameter type is not a class: 5128 if (!ToType->isRecordType()) { 5129 // - if the initializer list has one element that is not itself an 5130 // initializer list, the implicit conversion sequence is the one 5131 // required to convert the element to the parameter type. 5132 unsigned NumInits = From->getNumInits(); 5133 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5134 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5135 SuppressUserConversions, 5136 InOverloadResolution, 5137 AllowObjCWritebackConversion); 5138 // - if the initializer list has no elements, the implicit conversion 5139 // sequence is the identity conversion. 5140 else if (NumInits == 0) { 5141 Result.setStandard(); 5142 Result.Standard.setAsIdentityConversion(); 5143 Result.Standard.setFromType(ToType); 5144 Result.Standard.setAllToTypes(ToType); 5145 } 5146 return Result; 5147 } 5148 5149 // C++14 [over.ics.list]p8: 5150 // C++11 [over.ics.list]p7: 5151 // In all cases other than those enumerated above, no conversion is possible 5152 return Result; 5153 } 5154 5155 /// TryCopyInitialization - Try to copy-initialize a value of type 5156 /// ToType from the expression From. Return the implicit conversion 5157 /// sequence required to pass this argument, which may be a bad 5158 /// conversion sequence (meaning that the argument cannot be passed to 5159 /// a parameter of this type). If @p SuppressUserConversions, then we 5160 /// do not permit any user-defined conversion sequences. 5161 static ImplicitConversionSequence 5162 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5163 bool SuppressUserConversions, 5164 bool InOverloadResolution, 5165 bool AllowObjCWritebackConversion, 5166 bool AllowExplicit) { 5167 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5168 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5169 InOverloadResolution,AllowObjCWritebackConversion); 5170 5171 if (ToType->isReferenceType()) 5172 return TryReferenceInit(S, From, ToType, 5173 /*FIXME:*/ From->getBeginLoc(), 5174 SuppressUserConversions, AllowExplicit); 5175 5176 return TryImplicitConversion(S, From, ToType, 5177 SuppressUserConversions, 5178 /*AllowExplicit=*/false, 5179 InOverloadResolution, 5180 /*CStyle=*/false, 5181 AllowObjCWritebackConversion, 5182 /*AllowObjCConversionOnExplicit=*/false); 5183 } 5184 5185 static bool TryCopyInitialization(const CanQualType FromQTy, 5186 const CanQualType ToQTy, 5187 Sema &S, 5188 SourceLocation Loc, 5189 ExprValueKind FromVK) { 5190 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5191 ImplicitConversionSequence ICS = 5192 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5193 5194 return !ICS.isBad(); 5195 } 5196 5197 /// TryObjectArgumentInitialization - Try to initialize the object 5198 /// parameter of the given member function (@c Method) from the 5199 /// expression @p From. 5200 static ImplicitConversionSequence 5201 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5202 Expr::Classification FromClassification, 5203 CXXMethodDecl *Method, 5204 CXXRecordDecl *ActingContext) { 5205 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5206 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5207 // const volatile object. 5208 Qualifiers Quals = Method->getMethodQualifiers(); 5209 if (isa<CXXDestructorDecl>(Method)) { 5210 Quals.addConst(); 5211 Quals.addVolatile(); 5212 } 5213 5214 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5215 5216 // Set up the conversion sequence as a "bad" conversion, to allow us 5217 // to exit early. 5218 ImplicitConversionSequence ICS; 5219 5220 // We need to have an object of class type. 5221 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5222 FromType = PT->getPointeeType(); 5223 5224 // When we had a pointer, it's implicitly dereferenced, so we 5225 // better have an lvalue. 5226 assert(FromClassification.isLValue()); 5227 } 5228 5229 assert(FromType->isRecordType()); 5230 5231 // C++0x [over.match.funcs]p4: 5232 // For non-static member functions, the type of the implicit object 5233 // parameter is 5234 // 5235 // - "lvalue reference to cv X" for functions declared without a 5236 // ref-qualifier or with the & ref-qualifier 5237 // - "rvalue reference to cv X" for functions declared with the && 5238 // ref-qualifier 5239 // 5240 // where X is the class of which the function is a member and cv is the 5241 // cv-qualification on the member function declaration. 5242 // 5243 // However, when finding an implicit conversion sequence for the argument, we 5244 // are not allowed to perform user-defined conversions 5245 // (C++ [over.match.funcs]p5). We perform a simplified version of 5246 // reference binding here, that allows class rvalues to bind to 5247 // non-constant references. 5248 5249 // First check the qualifiers. 5250 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5251 if (ImplicitParamType.getCVRQualifiers() 5252 != FromTypeCanon.getLocalCVRQualifiers() && 5253 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5254 ICS.setBad(BadConversionSequence::bad_qualifiers, 5255 FromType, ImplicitParamType); 5256 return ICS; 5257 } 5258 5259 if (FromTypeCanon.hasAddressSpace()) { 5260 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5261 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5262 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5263 ICS.setBad(BadConversionSequence::bad_qualifiers, 5264 FromType, ImplicitParamType); 5265 return ICS; 5266 } 5267 } 5268 5269 // Check that we have either the same type or a derived type. It 5270 // affects the conversion rank. 5271 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5272 ImplicitConversionKind SecondKind; 5273 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5274 SecondKind = ICK_Identity; 5275 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5276 SecondKind = ICK_Derived_To_Base; 5277 else { 5278 ICS.setBad(BadConversionSequence::unrelated_class, 5279 FromType, ImplicitParamType); 5280 return ICS; 5281 } 5282 5283 // Check the ref-qualifier. 5284 switch (Method->getRefQualifier()) { 5285 case RQ_None: 5286 // Do nothing; we don't care about lvalueness or rvalueness. 5287 break; 5288 5289 case RQ_LValue: 5290 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5291 // non-const lvalue reference cannot bind to an rvalue 5292 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5293 ImplicitParamType); 5294 return ICS; 5295 } 5296 break; 5297 5298 case RQ_RValue: 5299 if (!FromClassification.isRValue()) { 5300 // rvalue reference cannot bind to an lvalue 5301 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5302 ImplicitParamType); 5303 return ICS; 5304 } 5305 break; 5306 } 5307 5308 // Success. Mark this as a reference binding. 5309 ICS.setStandard(); 5310 ICS.Standard.setAsIdentityConversion(); 5311 ICS.Standard.Second = SecondKind; 5312 ICS.Standard.setFromType(FromType); 5313 ICS.Standard.setAllToTypes(ImplicitParamType); 5314 ICS.Standard.ReferenceBinding = true; 5315 ICS.Standard.DirectBinding = true; 5316 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5317 ICS.Standard.BindsToFunctionLvalue = false; 5318 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5319 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5320 = (Method->getRefQualifier() == RQ_None); 5321 return ICS; 5322 } 5323 5324 /// PerformObjectArgumentInitialization - Perform initialization of 5325 /// the implicit object parameter for the given Method with the given 5326 /// expression. 5327 ExprResult 5328 Sema::PerformObjectArgumentInitialization(Expr *From, 5329 NestedNameSpecifier *Qualifier, 5330 NamedDecl *FoundDecl, 5331 CXXMethodDecl *Method) { 5332 QualType FromRecordType, DestType; 5333 QualType ImplicitParamRecordType = 5334 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5335 5336 Expr::Classification FromClassification; 5337 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5338 FromRecordType = PT->getPointeeType(); 5339 DestType = Method->getThisType(); 5340 FromClassification = Expr::Classification::makeSimpleLValue(); 5341 } else { 5342 FromRecordType = From->getType(); 5343 DestType = ImplicitParamRecordType; 5344 FromClassification = From->Classify(Context); 5345 5346 // When performing member access on an rvalue, materialize a temporary. 5347 if (From->isRValue()) { 5348 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5349 Method->getRefQualifier() != 5350 RefQualifierKind::RQ_RValue); 5351 } 5352 } 5353 5354 // Note that we always use the true parent context when performing 5355 // the actual argument initialization. 5356 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5357 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5358 Method->getParent()); 5359 if (ICS.isBad()) { 5360 switch (ICS.Bad.Kind) { 5361 case BadConversionSequence::bad_qualifiers: { 5362 Qualifiers FromQs = FromRecordType.getQualifiers(); 5363 Qualifiers ToQs = DestType.getQualifiers(); 5364 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5365 if (CVR) { 5366 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5367 << Method->getDeclName() << FromRecordType << (CVR - 1) 5368 << From->getSourceRange(); 5369 Diag(Method->getLocation(), diag::note_previous_decl) 5370 << Method->getDeclName(); 5371 return ExprError(); 5372 } 5373 break; 5374 } 5375 5376 case BadConversionSequence::lvalue_ref_to_rvalue: 5377 case BadConversionSequence::rvalue_ref_to_lvalue: { 5378 bool IsRValueQualified = 5379 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5380 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5381 << Method->getDeclName() << FromClassification.isRValue() 5382 << IsRValueQualified; 5383 Diag(Method->getLocation(), diag::note_previous_decl) 5384 << Method->getDeclName(); 5385 return ExprError(); 5386 } 5387 5388 case BadConversionSequence::no_conversion: 5389 case BadConversionSequence::unrelated_class: 5390 break; 5391 } 5392 5393 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5394 << ImplicitParamRecordType << FromRecordType 5395 << From->getSourceRange(); 5396 } 5397 5398 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5399 ExprResult FromRes = 5400 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5401 if (FromRes.isInvalid()) 5402 return ExprError(); 5403 From = FromRes.get(); 5404 } 5405 5406 if (!Context.hasSameType(From->getType(), DestType)) { 5407 CastKind CK; 5408 QualType PteeTy = DestType->getPointeeType(); 5409 LangAS DestAS = 5410 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5411 if (FromRecordType.getAddressSpace() != DestAS) 5412 CK = CK_AddressSpaceConversion; 5413 else 5414 CK = CK_NoOp; 5415 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5416 } 5417 return From; 5418 } 5419 5420 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5421 /// expression From to bool (C++0x [conv]p3). 5422 static ImplicitConversionSequence 5423 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5424 return TryImplicitConversion(S, From, S.Context.BoolTy, 5425 /*SuppressUserConversions=*/false, 5426 /*AllowExplicit=*/true, 5427 /*InOverloadResolution=*/false, 5428 /*CStyle=*/false, 5429 /*AllowObjCWritebackConversion=*/false, 5430 /*AllowObjCConversionOnExplicit=*/false); 5431 } 5432 5433 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5434 /// of the expression From to bool (C++0x [conv]p3). 5435 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5436 if (checkPlaceholderForOverload(*this, From)) 5437 return ExprError(); 5438 5439 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5440 if (!ICS.isBad()) 5441 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5442 5443 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5444 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5445 << From->getType() << From->getSourceRange(); 5446 return ExprError(); 5447 } 5448 5449 /// Check that the specified conversion is permitted in a converted constant 5450 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5451 /// is acceptable. 5452 static bool CheckConvertedConstantConversions(Sema &S, 5453 StandardConversionSequence &SCS) { 5454 // Since we know that the target type is an integral or unscoped enumeration 5455 // type, most conversion kinds are impossible. All possible First and Third 5456 // conversions are fine. 5457 switch (SCS.Second) { 5458 case ICK_Identity: 5459 case ICK_Function_Conversion: 5460 case ICK_Integral_Promotion: 5461 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5462 case ICK_Zero_Queue_Conversion: 5463 return true; 5464 5465 case ICK_Boolean_Conversion: 5466 // Conversion from an integral or unscoped enumeration type to bool is 5467 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5468 // conversion, so we allow it in a converted constant expression. 5469 // 5470 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5471 // a lot of popular code. We should at least add a warning for this 5472 // (non-conforming) extension. 5473 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5474 SCS.getToType(2)->isBooleanType(); 5475 5476 case ICK_Pointer_Conversion: 5477 case ICK_Pointer_Member: 5478 // C++1z: null pointer conversions and null member pointer conversions are 5479 // only permitted if the source type is std::nullptr_t. 5480 return SCS.getFromType()->isNullPtrType(); 5481 5482 case ICK_Floating_Promotion: 5483 case ICK_Complex_Promotion: 5484 case ICK_Floating_Conversion: 5485 case ICK_Complex_Conversion: 5486 case ICK_Floating_Integral: 5487 case ICK_Compatible_Conversion: 5488 case ICK_Derived_To_Base: 5489 case ICK_Vector_Conversion: 5490 case ICK_Vector_Splat: 5491 case ICK_Complex_Real: 5492 case ICK_Block_Pointer_Conversion: 5493 case ICK_TransparentUnionConversion: 5494 case ICK_Writeback_Conversion: 5495 case ICK_Zero_Event_Conversion: 5496 case ICK_C_Only_Conversion: 5497 case ICK_Incompatible_Pointer_Conversion: 5498 return false; 5499 5500 case ICK_Lvalue_To_Rvalue: 5501 case ICK_Array_To_Pointer: 5502 case ICK_Function_To_Pointer: 5503 llvm_unreachable("found a first conversion kind in Second"); 5504 5505 case ICK_Qualification: 5506 llvm_unreachable("found a third conversion kind in Second"); 5507 5508 case ICK_Num_Conversion_Kinds: 5509 break; 5510 } 5511 5512 llvm_unreachable("unknown conversion kind"); 5513 } 5514 5515 /// CheckConvertedConstantExpression - Check that the expression From is a 5516 /// converted constant expression of type T, perform the conversion and produce 5517 /// the converted expression, per C++11 [expr.const]p3. 5518 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5519 QualType T, APValue &Value, 5520 Sema::CCEKind CCE, 5521 bool RequireInt) { 5522 assert(S.getLangOpts().CPlusPlus11 && 5523 "converted constant expression outside C++11"); 5524 5525 if (checkPlaceholderForOverload(S, From)) 5526 return ExprError(); 5527 5528 // C++1z [expr.const]p3: 5529 // A converted constant expression of type T is an expression, 5530 // implicitly converted to type T, where the converted 5531 // expression is a constant expression and the implicit conversion 5532 // sequence contains only [... list of conversions ...]. 5533 // C++1z [stmt.if]p2: 5534 // If the if statement is of the form if constexpr, the value of the 5535 // condition shall be a contextually converted constant expression of type 5536 // bool. 5537 ImplicitConversionSequence ICS = 5538 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5539 ? TryContextuallyConvertToBool(S, From) 5540 : TryCopyInitialization(S, From, T, 5541 /*SuppressUserConversions=*/false, 5542 /*InOverloadResolution=*/false, 5543 /*AllowObjCWritebackConversion=*/false, 5544 /*AllowExplicit=*/false); 5545 StandardConversionSequence *SCS = nullptr; 5546 switch (ICS.getKind()) { 5547 case ImplicitConversionSequence::StandardConversion: 5548 SCS = &ICS.Standard; 5549 break; 5550 case ImplicitConversionSequence::UserDefinedConversion: 5551 // We are converting to a non-class type, so the Before sequence 5552 // must be trivial. 5553 SCS = &ICS.UserDefined.After; 5554 break; 5555 case ImplicitConversionSequence::AmbiguousConversion: 5556 case ImplicitConversionSequence::BadConversion: 5557 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5558 return S.Diag(From->getBeginLoc(), 5559 diag::err_typecheck_converted_constant_expression) 5560 << From->getType() << From->getSourceRange() << T; 5561 return ExprError(); 5562 5563 case ImplicitConversionSequence::EllipsisConversion: 5564 llvm_unreachable("ellipsis conversion in converted constant expression"); 5565 } 5566 5567 // Check that we would only use permitted conversions. 5568 if (!CheckConvertedConstantConversions(S, *SCS)) { 5569 return S.Diag(From->getBeginLoc(), 5570 diag::err_typecheck_converted_constant_expression_disallowed) 5571 << From->getType() << From->getSourceRange() << T; 5572 } 5573 // [...] and where the reference binding (if any) binds directly. 5574 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5575 return S.Diag(From->getBeginLoc(), 5576 diag::err_typecheck_converted_constant_expression_indirect) 5577 << From->getType() << From->getSourceRange() << T; 5578 } 5579 5580 ExprResult Result = 5581 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5582 if (Result.isInvalid()) 5583 return Result; 5584 5585 // C++2a [intro.execution]p5: 5586 // A full-expression is [...] a constant-expression [...] 5587 Result = 5588 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5589 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5590 if (Result.isInvalid()) 5591 return Result; 5592 5593 // Check for a narrowing implicit conversion. 5594 APValue PreNarrowingValue; 5595 QualType PreNarrowingType; 5596 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5597 PreNarrowingType)) { 5598 case NK_Dependent_Narrowing: 5599 // Implicit conversion to a narrower type, but the expression is 5600 // value-dependent so we can't tell whether it's actually narrowing. 5601 case NK_Variable_Narrowing: 5602 // Implicit conversion to a narrower type, and the value is not a constant 5603 // expression. We'll diagnose this in a moment. 5604 case NK_Not_Narrowing: 5605 break; 5606 5607 case NK_Constant_Narrowing: 5608 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5609 << CCE << /*Constant*/ 1 5610 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5611 break; 5612 5613 case NK_Type_Narrowing: 5614 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5615 << CCE << /*Constant*/ 0 << From->getType() << T; 5616 break; 5617 } 5618 5619 if (Result.get()->isValueDependent()) { 5620 Value = APValue(); 5621 return Result; 5622 } 5623 5624 // Check the expression is a constant expression. 5625 SmallVector<PartialDiagnosticAt, 8> Notes; 5626 Expr::EvalResult Eval; 5627 Eval.Diag = &Notes; 5628 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5629 ? Expr::EvaluateForMangling 5630 : Expr::EvaluateForCodeGen; 5631 5632 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5633 (RequireInt && !Eval.Val.isInt())) { 5634 // The expression can't be folded, so we can't keep it at this position in 5635 // the AST. 5636 Result = ExprError(); 5637 } else { 5638 Value = Eval.Val; 5639 5640 if (Notes.empty()) { 5641 // It's a constant expression. 5642 return ConstantExpr::Create(S.Context, Result.get(), Value); 5643 } 5644 } 5645 5646 // It's not a constant expression. Produce an appropriate diagnostic. 5647 if (Notes.size() == 1 && 5648 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5649 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5650 else { 5651 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5652 << CCE << From->getSourceRange(); 5653 for (unsigned I = 0; I < Notes.size(); ++I) 5654 S.Diag(Notes[I].first, Notes[I].second); 5655 } 5656 return ExprError(); 5657 } 5658 5659 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5660 APValue &Value, CCEKind CCE) { 5661 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5662 } 5663 5664 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5665 llvm::APSInt &Value, 5666 CCEKind CCE) { 5667 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5668 5669 APValue V; 5670 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5671 if (!R.isInvalid() && !R.get()->isValueDependent()) 5672 Value = V.getInt(); 5673 return R; 5674 } 5675 5676 5677 /// dropPointerConversions - If the given standard conversion sequence 5678 /// involves any pointer conversions, remove them. This may change 5679 /// the result type of the conversion sequence. 5680 static void dropPointerConversion(StandardConversionSequence &SCS) { 5681 if (SCS.Second == ICK_Pointer_Conversion) { 5682 SCS.Second = ICK_Identity; 5683 SCS.Third = ICK_Identity; 5684 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5685 } 5686 } 5687 5688 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5689 /// convert the expression From to an Objective-C pointer type. 5690 static ImplicitConversionSequence 5691 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5692 // Do an implicit conversion to 'id'. 5693 QualType Ty = S.Context.getObjCIdType(); 5694 ImplicitConversionSequence ICS 5695 = TryImplicitConversion(S, From, Ty, 5696 // FIXME: Are these flags correct? 5697 /*SuppressUserConversions=*/false, 5698 /*AllowExplicit=*/true, 5699 /*InOverloadResolution=*/false, 5700 /*CStyle=*/false, 5701 /*AllowObjCWritebackConversion=*/false, 5702 /*AllowObjCConversionOnExplicit=*/true); 5703 5704 // Strip off any final conversions to 'id'. 5705 switch (ICS.getKind()) { 5706 case ImplicitConversionSequence::BadConversion: 5707 case ImplicitConversionSequence::AmbiguousConversion: 5708 case ImplicitConversionSequence::EllipsisConversion: 5709 break; 5710 5711 case ImplicitConversionSequence::UserDefinedConversion: 5712 dropPointerConversion(ICS.UserDefined.After); 5713 break; 5714 5715 case ImplicitConversionSequence::StandardConversion: 5716 dropPointerConversion(ICS.Standard); 5717 break; 5718 } 5719 5720 return ICS; 5721 } 5722 5723 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5724 /// conversion of the expression From to an Objective-C pointer type. 5725 /// Returns a valid but null ExprResult if no conversion sequence exists. 5726 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5727 if (checkPlaceholderForOverload(*this, From)) 5728 return ExprError(); 5729 5730 QualType Ty = Context.getObjCIdType(); 5731 ImplicitConversionSequence ICS = 5732 TryContextuallyConvertToObjCPointer(*this, From); 5733 if (!ICS.isBad()) 5734 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5735 return ExprResult(); 5736 } 5737 5738 /// Determine whether the provided type is an integral type, or an enumeration 5739 /// type of a permitted flavor. 5740 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5741 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5742 : T->isIntegralOrUnscopedEnumerationType(); 5743 } 5744 5745 static ExprResult 5746 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5747 Sema::ContextualImplicitConverter &Converter, 5748 QualType T, UnresolvedSetImpl &ViableConversions) { 5749 5750 if (Converter.Suppress) 5751 return ExprError(); 5752 5753 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5754 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5755 CXXConversionDecl *Conv = 5756 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5757 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5758 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5759 } 5760 return From; 5761 } 5762 5763 static bool 5764 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5765 Sema::ContextualImplicitConverter &Converter, 5766 QualType T, bool HadMultipleCandidates, 5767 UnresolvedSetImpl &ExplicitConversions) { 5768 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5769 DeclAccessPair Found = ExplicitConversions[0]; 5770 CXXConversionDecl *Conversion = 5771 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5772 5773 // The user probably meant to invoke the given explicit 5774 // conversion; use it. 5775 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5776 std::string TypeStr; 5777 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5778 5779 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5780 << FixItHint::CreateInsertion(From->getBeginLoc(), 5781 "static_cast<" + TypeStr + ">(") 5782 << FixItHint::CreateInsertion( 5783 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5784 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5785 5786 // If we aren't in a SFINAE context, build a call to the 5787 // explicit conversion function. 5788 if (SemaRef.isSFINAEContext()) 5789 return true; 5790 5791 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5792 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5793 HadMultipleCandidates); 5794 if (Result.isInvalid()) 5795 return true; 5796 // Record usage of conversion in an implicit cast. 5797 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5798 CK_UserDefinedConversion, Result.get(), 5799 nullptr, Result.get()->getValueKind()); 5800 } 5801 return false; 5802 } 5803 5804 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5805 Sema::ContextualImplicitConverter &Converter, 5806 QualType T, bool HadMultipleCandidates, 5807 DeclAccessPair &Found) { 5808 CXXConversionDecl *Conversion = 5809 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5810 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5811 5812 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5813 if (!Converter.SuppressConversion) { 5814 if (SemaRef.isSFINAEContext()) 5815 return true; 5816 5817 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5818 << From->getSourceRange(); 5819 } 5820 5821 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5822 HadMultipleCandidates); 5823 if (Result.isInvalid()) 5824 return true; 5825 // Record usage of conversion in an implicit cast. 5826 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5827 CK_UserDefinedConversion, Result.get(), 5828 nullptr, Result.get()->getValueKind()); 5829 return false; 5830 } 5831 5832 static ExprResult finishContextualImplicitConversion( 5833 Sema &SemaRef, SourceLocation Loc, Expr *From, 5834 Sema::ContextualImplicitConverter &Converter) { 5835 if (!Converter.match(From->getType()) && !Converter.Suppress) 5836 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5837 << From->getSourceRange(); 5838 5839 return SemaRef.DefaultLvalueConversion(From); 5840 } 5841 5842 static void 5843 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5844 UnresolvedSetImpl &ViableConversions, 5845 OverloadCandidateSet &CandidateSet) { 5846 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5847 DeclAccessPair FoundDecl = ViableConversions[I]; 5848 NamedDecl *D = FoundDecl.getDecl(); 5849 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5850 if (isa<UsingShadowDecl>(D)) 5851 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5852 5853 CXXConversionDecl *Conv; 5854 FunctionTemplateDecl *ConvTemplate; 5855 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5856 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5857 else 5858 Conv = cast<CXXConversionDecl>(D); 5859 5860 if (ConvTemplate) 5861 SemaRef.AddTemplateConversionCandidate( 5862 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5863 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5864 else 5865 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5866 ToType, CandidateSet, 5867 /*AllowObjCConversionOnExplicit=*/false, 5868 /*AllowExplicit*/ true); 5869 } 5870 } 5871 5872 /// Attempt to convert the given expression to a type which is accepted 5873 /// by the given converter. 5874 /// 5875 /// This routine will attempt to convert an expression of class type to a 5876 /// type accepted by the specified converter. In C++11 and before, the class 5877 /// must have a single non-explicit conversion function converting to a matching 5878 /// type. In C++1y, there can be multiple such conversion functions, but only 5879 /// one target type. 5880 /// 5881 /// \param Loc The source location of the construct that requires the 5882 /// conversion. 5883 /// 5884 /// \param From The expression we're converting from. 5885 /// 5886 /// \param Converter Used to control and diagnose the conversion process. 5887 /// 5888 /// \returns The expression, converted to an integral or enumeration type if 5889 /// successful. 5890 ExprResult Sema::PerformContextualImplicitConversion( 5891 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5892 // We can't perform any more checking for type-dependent expressions. 5893 if (From->isTypeDependent()) 5894 return From; 5895 5896 // Process placeholders immediately. 5897 if (From->hasPlaceholderType()) { 5898 ExprResult result = CheckPlaceholderExpr(From); 5899 if (result.isInvalid()) 5900 return result; 5901 From = result.get(); 5902 } 5903 5904 // If the expression already has a matching type, we're golden. 5905 QualType T = From->getType(); 5906 if (Converter.match(T)) 5907 return DefaultLvalueConversion(From); 5908 5909 // FIXME: Check for missing '()' if T is a function type? 5910 5911 // We can only perform contextual implicit conversions on objects of class 5912 // type. 5913 const RecordType *RecordTy = T->getAs<RecordType>(); 5914 if (!RecordTy || !getLangOpts().CPlusPlus) { 5915 if (!Converter.Suppress) 5916 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5917 return From; 5918 } 5919 5920 // We must have a complete class type. 5921 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5922 ContextualImplicitConverter &Converter; 5923 Expr *From; 5924 5925 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5926 : Converter(Converter), From(From) {} 5927 5928 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5929 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5930 } 5931 } IncompleteDiagnoser(Converter, From); 5932 5933 if (Converter.Suppress ? !isCompleteType(Loc, T) 5934 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5935 return From; 5936 5937 // Look for a conversion to an integral or enumeration type. 5938 UnresolvedSet<4> 5939 ViableConversions; // These are *potentially* viable in C++1y. 5940 UnresolvedSet<4> ExplicitConversions; 5941 const auto &Conversions = 5942 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5943 5944 bool HadMultipleCandidates = 5945 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5946 5947 // To check that there is only one target type, in C++1y: 5948 QualType ToType; 5949 bool HasUniqueTargetType = true; 5950 5951 // Collect explicit or viable (potentially in C++1y) conversions. 5952 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5953 NamedDecl *D = (*I)->getUnderlyingDecl(); 5954 CXXConversionDecl *Conversion; 5955 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5956 if (ConvTemplate) { 5957 if (getLangOpts().CPlusPlus14) 5958 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5959 else 5960 continue; // C++11 does not consider conversion operator templates(?). 5961 } else 5962 Conversion = cast<CXXConversionDecl>(D); 5963 5964 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5965 "Conversion operator templates are considered potentially " 5966 "viable in C++1y"); 5967 5968 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5969 if (Converter.match(CurToType) || ConvTemplate) { 5970 5971 if (Conversion->isExplicit()) { 5972 // FIXME: For C++1y, do we need this restriction? 5973 // cf. diagnoseNoViableConversion() 5974 if (!ConvTemplate) 5975 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5976 } else { 5977 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5978 if (ToType.isNull()) 5979 ToType = CurToType.getUnqualifiedType(); 5980 else if (HasUniqueTargetType && 5981 (CurToType.getUnqualifiedType() != ToType)) 5982 HasUniqueTargetType = false; 5983 } 5984 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5985 } 5986 } 5987 } 5988 5989 if (getLangOpts().CPlusPlus14) { 5990 // C++1y [conv]p6: 5991 // ... An expression e of class type E appearing in such a context 5992 // is said to be contextually implicitly converted to a specified 5993 // type T and is well-formed if and only if e can be implicitly 5994 // converted to a type T that is determined as follows: E is searched 5995 // for conversion functions whose return type is cv T or reference to 5996 // cv T such that T is allowed by the context. There shall be 5997 // exactly one such T. 5998 5999 // If no unique T is found: 6000 if (ToType.isNull()) { 6001 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6002 HadMultipleCandidates, 6003 ExplicitConversions)) 6004 return ExprError(); 6005 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6006 } 6007 6008 // If more than one unique Ts are found: 6009 if (!HasUniqueTargetType) 6010 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6011 ViableConversions); 6012 6013 // If one unique T is found: 6014 // First, build a candidate set from the previously recorded 6015 // potentially viable conversions. 6016 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6017 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6018 CandidateSet); 6019 6020 // Then, perform overload resolution over the candidate set. 6021 OverloadCandidateSet::iterator Best; 6022 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6023 case OR_Success: { 6024 // Apply this conversion. 6025 DeclAccessPair Found = 6026 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6027 if (recordConversion(*this, Loc, From, Converter, T, 6028 HadMultipleCandidates, Found)) 6029 return ExprError(); 6030 break; 6031 } 6032 case OR_Ambiguous: 6033 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6034 ViableConversions); 6035 case OR_No_Viable_Function: 6036 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6037 HadMultipleCandidates, 6038 ExplicitConversions)) 6039 return ExprError(); 6040 LLVM_FALLTHROUGH; 6041 case OR_Deleted: 6042 // We'll complain below about a non-integral condition type. 6043 break; 6044 } 6045 } else { 6046 switch (ViableConversions.size()) { 6047 case 0: { 6048 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6049 HadMultipleCandidates, 6050 ExplicitConversions)) 6051 return ExprError(); 6052 6053 // We'll complain below about a non-integral condition type. 6054 break; 6055 } 6056 case 1: { 6057 // Apply this conversion. 6058 DeclAccessPair Found = ViableConversions[0]; 6059 if (recordConversion(*this, Loc, From, Converter, T, 6060 HadMultipleCandidates, Found)) 6061 return ExprError(); 6062 break; 6063 } 6064 default: 6065 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6066 ViableConversions); 6067 } 6068 } 6069 6070 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6071 } 6072 6073 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6074 /// an acceptable non-member overloaded operator for a call whose 6075 /// arguments have types T1 (and, if non-empty, T2). This routine 6076 /// implements the check in C++ [over.match.oper]p3b2 concerning 6077 /// enumeration types. 6078 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6079 FunctionDecl *Fn, 6080 ArrayRef<Expr *> Args) { 6081 QualType T1 = Args[0]->getType(); 6082 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6083 6084 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6085 return true; 6086 6087 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6088 return true; 6089 6090 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 6091 if (Proto->getNumParams() < 1) 6092 return false; 6093 6094 if (T1->isEnumeralType()) { 6095 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6096 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6097 return true; 6098 } 6099 6100 if (Proto->getNumParams() < 2) 6101 return false; 6102 6103 if (!T2.isNull() && T2->isEnumeralType()) { 6104 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6105 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6106 return true; 6107 } 6108 6109 return false; 6110 } 6111 6112 /// AddOverloadCandidate - Adds the given function to the set of 6113 /// candidate functions, using the given function call arguments. If 6114 /// @p SuppressUserConversions, then don't allow user-defined 6115 /// conversions via constructors or conversion operators. 6116 /// 6117 /// \param PartialOverloading true if we are performing "partial" overloading 6118 /// based on an incomplete set of function arguments. This feature is used by 6119 /// code completion. 6120 void Sema::AddOverloadCandidate( 6121 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6122 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6123 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6124 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6125 OverloadCandidateParamOrder PO) { 6126 const FunctionProtoType *Proto 6127 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6128 assert(Proto && "Functions without a prototype cannot be overloaded"); 6129 assert(!Function->getDescribedFunctionTemplate() && 6130 "Use AddTemplateOverloadCandidate for function templates"); 6131 6132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6133 if (!isa<CXXConstructorDecl>(Method)) { 6134 // If we get here, it's because we're calling a member function 6135 // that is named without a member access expression (e.g., 6136 // "this->f") that was either written explicitly or created 6137 // implicitly. This can happen with a qualified call to a member 6138 // function, e.g., X::f(). We use an empty type for the implied 6139 // object argument (C++ [over.call.func]p3), and the acting context 6140 // is irrelevant. 6141 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6142 Expr::Classification::makeSimpleLValue(), Args, 6143 CandidateSet, SuppressUserConversions, 6144 PartialOverloading, EarlyConversions, PO); 6145 return; 6146 } 6147 // We treat a constructor like a non-member function, since its object 6148 // argument doesn't participate in overload resolution. 6149 } 6150 6151 if (!CandidateSet.isNewCandidate(Function, PO)) 6152 return; 6153 6154 // C++11 [class.copy]p11: [DR1402] 6155 // A defaulted move constructor that is defined as deleted is ignored by 6156 // overload resolution. 6157 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6158 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6159 Constructor->isMoveConstructor()) 6160 return; 6161 6162 // Overload resolution is always an unevaluated context. 6163 EnterExpressionEvaluationContext Unevaluated( 6164 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6165 6166 // C++ [over.match.oper]p3: 6167 // if no operand has a class type, only those non-member functions in the 6168 // lookup set that have a first parameter of type T1 or "reference to 6169 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6170 // is a right operand) a second parameter of type T2 or "reference to 6171 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6172 // candidate functions. 6173 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6174 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6175 return; 6176 6177 // Add this candidate 6178 OverloadCandidate &Candidate = 6179 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6180 Candidate.FoundDecl = FoundDecl; 6181 Candidate.Function = Function; 6182 Candidate.Viable = true; 6183 Candidate.RewriteKind = 6184 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6185 Candidate.IsSurrogate = false; 6186 Candidate.IsADLCandidate = IsADLCandidate; 6187 Candidate.IgnoreObjectArgument = false; 6188 Candidate.ExplicitCallArguments = Args.size(); 6189 6190 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6191 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6192 Candidate.Viable = false; 6193 Candidate.FailureKind = ovl_non_default_multiversion_function; 6194 return; 6195 } 6196 6197 if (Constructor) { 6198 // C++ [class.copy]p3: 6199 // A member function template is never instantiated to perform the copy 6200 // of a class object to an object of its class type. 6201 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6202 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6203 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6204 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6205 ClassType))) { 6206 Candidate.Viable = false; 6207 Candidate.FailureKind = ovl_fail_illegal_constructor; 6208 return; 6209 } 6210 6211 // C++ [over.match.funcs]p8: (proposed DR resolution) 6212 // A constructor inherited from class type C that has a first parameter 6213 // of type "reference to P" (including such a constructor instantiated 6214 // from a template) is excluded from the set of candidate functions when 6215 // constructing an object of type cv D if the argument list has exactly 6216 // one argument and D is reference-related to P and P is reference-related 6217 // to C. 6218 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6219 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6220 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6221 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6222 QualType C = Context.getRecordType(Constructor->getParent()); 6223 QualType D = Context.getRecordType(Shadow->getParent()); 6224 SourceLocation Loc = Args.front()->getExprLoc(); 6225 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6226 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6227 Candidate.Viable = false; 6228 Candidate.FailureKind = ovl_fail_inhctor_slice; 6229 return; 6230 } 6231 } 6232 6233 // Check that the constructor is capable of constructing an object in the 6234 // destination address space. 6235 if (!Qualifiers::isAddressSpaceSupersetOf( 6236 Constructor->getMethodQualifiers().getAddressSpace(), 6237 CandidateSet.getDestAS())) { 6238 Candidate.Viable = false; 6239 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6240 } 6241 } 6242 6243 unsigned NumParams = Proto->getNumParams(); 6244 6245 // (C++ 13.3.2p2): A candidate function having fewer than m 6246 // parameters is viable only if it has an ellipsis in its parameter 6247 // list (8.3.5). 6248 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6249 !Proto->isVariadic()) { 6250 Candidate.Viable = false; 6251 Candidate.FailureKind = ovl_fail_too_many_arguments; 6252 return; 6253 } 6254 6255 // (C++ 13.3.2p2): A candidate function having more than m parameters 6256 // is viable only if the (m+1)st parameter has a default argument 6257 // (8.3.6). For the purposes of overload resolution, the 6258 // parameter list is truncated on the right, so that there are 6259 // exactly m parameters. 6260 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6261 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6262 // Not enough arguments. 6263 Candidate.Viable = false; 6264 Candidate.FailureKind = ovl_fail_too_few_arguments; 6265 return; 6266 } 6267 6268 // (CUDA B.1): Check for invalid calls between targets. 6269 if (getLangOpts().CUDA) 6270 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6271 // Skip the check for callers that are implicit members, because in this 6272 // case we may not yet know what the member's target is; the target is 6273 // inferred for the member automatically, based on the bases and fields of 6274 // the class. 6275 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6276 Candidate.Viable = false; 6277 Candidate.FailureKind = ovl_fail_bad_target; 6278 return; 6279 } 6280 6281 // Determine the implicit conversion sequences for each of the 6282 // arguments. 6283 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6284 unsigned ConvIdx = 6285 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6286 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6287 // We already formed a conversion sequence for this parameter during 6288 // template argument deduction. 6289 } else if (ArgIdx < NumParams) { 6290 // (C++ 13.3.2p3): for F to be a viable function, there shall 6291 // exist for each argument an implicit conversion sequence 6292 // (13.3.3.1) that converts that argument to the corresponding 6293 // parameter of F. 6294 QualType ParamType = Proto->getParamType(ArgIdx); 6295 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6296 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6297 /*InOverloadResolution=*/true, 6298 /*AllowObjCWritebackConversion=*/ 6299 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6300 if (Candidate.Conversions[ConvIdx].isBad()) { 6301 Candidate.Viable = false; 6302 Candidate.FailureKind = ovl_fail_bad_conversion; 6303 return; 6304 } 6305 } else { 6306 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6307 // argument for which there is no corresponding parameter is 6308 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6309 Candidate.Conversions[ConvIdx].setEllipsis(); 6310 } 6311 } 6312 6313 if (!AllowExplicit) { 6314 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); 6315 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { 6316 Candidate.Viable = false; 6317 Candidate.FailureKind = ovl_fail_explicit_resolved; 6318 return; 6319 } 6320 } 6321 6322 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6323 Candidate.Viable = false; 6324 Candidate.FailureKind = ovl_fail_enable_if; 6325 Candidate.DeductionFailure.Data = FailedAttr; 6326 return; 6327 } 6328 6329 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6330 Candidate.Viable = false; 6331 Candidate.FailureKind = ovl_fail_ext_disabled; 6332 return; 6333 } 6334 } 6335 6336 ObjCMethodDecl * 6337 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6338 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6339 if (Methods.size() <= 1) 6340 return nullptr; 6341 6342 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6343 bool Match = true; 6344 ObjCMethodDecl *Method = Methods[b]; 6345 unsigned NumNamedArgs = Sel.getNumArgs(); 6346 // Method might have more arguments than selector indicates. This is due 6347 // to addition of c-style arguments in method. 6348 if (Method->param_size() > NumNamedArgs) 6349 NumNamedArgs = Method->param_size(); 6350 if (Args.size() < NumNamedArgs) 6351 continue; 6352 6353 for (unsigned i = 0; i < NumNamedArgs; i++) { 6354 // We can't do any type-checking on a type-dependent argument. 6355 if (Args[i]->isTypeDependent()) { 6356 Match = false; 6357 break; 6358 } 6359 6360 ParmVarDecl *param = Method->parameters()[i]; 6361 Expr *argExpr = Args[i]; 6362 assert(argExpr && "SelectBestMethod(): missing expression"); 6363 6364 // Strip the unbridged-cast placeholder expression off unless it's 6365 // a consumed argument. 6366 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6367 !param->hasAttr<CFConsumedAttr>()) 6368 argExpr = stripARCUnbridgedCast(argExpr); 6369 6370 // If the parameter is __unknown_anytype, move on to the next method. 6371 if (param->getType() == Context.UnknownAnyTy) { 6372 Match = false; 6373 break; 6374 } 6375 6376 ImplicitConversionSequence ConversionState 6377 = TryCopyInitialization(*this, argExpr, param->getType(), 6378 /*SuppressUserConversions*/false, 6379 /*InOverloadResolution=*/true, 6380 /*AllowObjCWritebackConversion=*/ 6381 getLangOpts().ObjCAutoRefCount, 6382 /*AllowExplicit*/false); 6383 // This function looks for a reasonably-exact match, so we consider 6384 // incompatible pointer conversions to be a failure here. 6385 if (ConversionState.isBad() || 6386 (ConversionState.isStandard() && 6387 ConversionState.Standard.Second == 6388 ICK_Incompatible_Pointer_Conversion)) { 6389 Match = false; 6390 break; 6391 } 6392 } 6393 // Promote additional arguments to variadic methods. 6394 if (Match && Method->isVariadic()) { 6395 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6396 if (Args[i]->isTypeDependent()) { 6397 Match = false; 6398 break; 6399 } 6400 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6401 nullptr); 6402 if (Arg.isInvalid()) { 6403 Match = false; 6404 break; 6405 } 6406 } 6407 } else { 6408 // Check for extra arguments to non-variadic methods. 6409 if (Args.size() != NumNamedArgs) 6410 Match = false; 6411 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6412 // Special case when selectors have no argument. In this case, select 6413 // one with the most general result type of 'id'. 6414 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6415 QualType ReturnT = Methods[b]->getReturnType(); 6416 if (ReturnT->isObjCIdType()) 6417 return Methods[b]; 6418 } 6419 } 6420 } 6421 6422 if (Match) 6423 return Method; 6424 } 6425 return nullptr; 6426 } 6427 6428 static bool 6429 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6430 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6431 bool MissingImplicitThis, Expr *&ConvertedThis, 6432 SmallVectorImpl<Expr *> &ConvertedArgs) { 6433 if (ThisArg) { 6434 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6435 assert(!isa<CXXConstructorDecl>(Method) && 6436 "Shouldn't have `this` for ctors!"); 6437 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6438 ExprResult R = S.PerformObjectArgumentInitialization( 6439 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6440 if (R.isInvalid()) 6441 return false; 6442 ConvertedThis = R.get(); 6443 } else { 6444 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6445 (void)MD; 6446 assert((MissingImplicitThis || MD->isStatic() || 6447 isa<CXXConstructorDecl>(MD)) && 6448 "Expected `this` for non-ctor instance methods"); 6449 } 6450 ConvertedThis = nullptr; 6451 } 6452 6453 // Ignore any variadic arguments. Converting them is pointless, since the 6454 // user can't refer to them in the function condition. 6455 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6456 6457 // Convert the arguments. 6458 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6459 ExprResult R; 6460 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6461 S.Context, Function->getParamDecl(I)), 6462 SourceLocation(), Args[I]); 6463 6464 if (R.isInvalid()) 6465 return false; 6466 6467 ConvertedArgs.push_back(R.get()); 6468 } 6469 6470 if (Trap.hasErrorOccurred()) 6471 return false; 6472 6473 // Push default arguments if needed. 6474 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6475 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6476 ParmVarDecl *P = Function->getParamDecl(i); 6477 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6478 ? P->getUninstantiatedDefaultArg() 6479 : P->getDefaultArg(); 6480 // This can only happen in code completion, i.e. when PartialOverloading 6481 // is true. 6482 if (!DefArg) 6483 return false; 6484 ExprResult R = 6485 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6486 S.Context, Function->getParamDecl(i)), 6487 SourceLocation(), DefArg); 6488 if (R.isInvalid()) 6489 return false; 6490 ConvertedArgs.push_back(R.get()); 6491 } 6492 6493 if (Trap.hasErrorOccurred()) 6494 return false; 6495 } 6496 return true; 6497 } 6498 6499 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6500 bool MissingImplicitThis) { 6501 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6502 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6503 return nullptr; 6504 6505 SFINAETrap Trap(*this); 6506 SmallVector<Expr *, 16> ConvertedArgs; 6507 // FIXME: We should look into making enable_if late-parsed. 6508 Expr *DiscardedThis; 6509 if (!convertArgsForAvailabilityChecks( 6510 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6511 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6512 return *EnableIfAttrs.begin(); 6513 6514 for (auto *EIA : EnableIfAttrs) { 6515 APValue Result; 6516 // FIXME: This doesn't consider value-dependent cases, because doing so is 6517 // very difficult. Ideally, we should handle them more gracefully. 6518 if (EIA->getCond()->isValueDependent() || 6519 !EIA->getCond()->EvaluateWithSubstitution( 6520 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6521 return EIA; 6522 6523 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6524 return EIA; 6525 } 6526 return nullptr; 6527 } 6528 6529 template <typename CheckFn> 6530 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6531 bool ArgDependent, SourceLocation Loc, 6532 CheckFn &&IsSuccessful) { 6533 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6534 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6535 if (ArgDependent == DIA->getArgDependent()) 6536 Attrs.push_back(DIA); 6537 } 6538 6539 // Common case: No diagnose_if attributes, so we can quit early. 6540 if (Attrs.empty()) 6541 return false; 6542 6543 auto WarningBegin = std::stable_partition( 6544 Attrs.begin(), Attrs.end(), 6545 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6546 6547 // Note that diagnose_if attributes are late-parsed, so they appear in the 6548 // correct order (unlike enable_if attributes). 6549 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6550 IsSuccessful); 6551 if (ErrAttr != WarningBegin) { 6552 const DiagnoseIfAttr *DIA = *ErrAttr; 6553 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6554 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6555 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6556 return true; 6557 } 6558 6559 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6560 if (IsSuccessful(DIA)) { 6561 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6562 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6563 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6564 } 6565 6566 return false; 6567 } 6568 6569 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6570 const Expr *ThisArg, 6571 ArrayRef<const Expr *> Args, 6572 SourceLocation Loc) { 6573 return diagnoseDiagnoseIfAttrsWith( 6574 *this, Function, /*ArgDependent=*/true, Loc, 6575 [&](const DiagnoseIfAttr *DIA) { 6576 APValue Result; 6577 // It's sane to use the same Args for any redecl of this function, since 6578 // EvaluateWithSubstitution only cares about the position of each 6579 // argument in the arg list, not the ParmVarDecl* it maps to. 6580 if (!DIA->getCond()->EvaluateWithSubstitution( 6581 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6582 return false; 6583 return Result.isInt() && Result.getInt().getBoolValue(); 6584 }); 6585 } 6586 6587 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6588 SourceLocation Loc) { 6589 return diagnoseDiagnoseIfAttrsWith( 6590 *this, ND, /*ArgDependent=*/false, Loc, 6591 [&](const DiagnoseIfAttr *DIA) { 6592 bool Result; 6593 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6594 Result; 6595 }); 6596 } 6597 6598 /// Add all of the function declarations in the given function set to 6599 /// the overload candidate set. 6600 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6601 ArrayRef<Expr *> Args, 6602 OverloadCandidateSet &CandidateSet, 6603 TemplateArgumentListInfo *ExplicitTemplateArgs, 6604 bool SuppressUserConversions, 6605 bool PartialOverloading, 6606 bool FirstArgumentIsBase) { 6607 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6608 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6609 ArrayRef<Expr *> FunctionArgs = Args; 6610 6611 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6612 FunctionDecl *FD = 6613 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6614 6615 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6616 QualType ObjectType; 6617 Expr::Classification ObjectClassification; 6618 if (Args.size() > 0) { 6619 if (Expr *E = Args[0]) { 6620 // Use the explicit base to restrict the lookup: 6621 ObjectType = E->getType(); 6622 // Pointers in the object arguments are implicitly dereferenced, so we 6623 // always classify them as l-values. 6624 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6625 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6626 else 6627 ObjectClassification = E->Classify(Context); 6628 } // .. else there is an implicit base. 6629 FunctionArgs = Args.slice(1); 6630 } 6631 if (FunTmpl) { 6632 AddMethodTemplateCandidate( 6633 FunTmpl, F.getPair(), 6634 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6635 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6636 FunctionArgs, CandidateSet, SuppressUserConversions, 6637 PartialOverloading); 6638 } else { 6639 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6640 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6641 ObjectClassification, FunctionArgs, CandidateSet, 6642 SuppressUserConversions, PartialOverloading); 6643 } 6644 } else { 6645 // This branch handles both standalone functions and static methods. 6646 6647 // Slice the first argument (which is the base) when we access 6648 // static method as non-static. 6649 if (Args.size() > 0 && 6650 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6651 !isa<CXXConstructorDecl>(FD)))) { 6652 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6653 FunctionArgs = Args.slice(1); 6654 } 6655 if (FunTmpl) { 6656 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6657 ExplicitTemplateArgs, FunctionArgs, 6658 CandidateSet, SuppressUserConversions, 6659 PartialOverloading); 6660 } else { 6661 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6662 SuppressUserConversions, PartialOverloading); 6663 } 6664 } 6665 } 6666 } 6667 6668 /// AddMethodCandidate - Adds a named decl (which is some kind of 6669 /// method) as a method candidate to the given overload set. 6670 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6671 Expr::Classification ObjectClassification, 6672 ArrayRef<Expr *> Args, 6673 OverloadCandidateSet &CandidateSet, 6674 bool SuppressUserConversions, 6675 OverloadCandidateParamOrder PO) { 6676 NamedDecl *Decl = FoundDecl.getDecl(); 6677 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6678 6679 if (isa<UsingShadowDecl>(Decl)) 6680 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6681 6682 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6683 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6684 "Expected a member function template"); 6685 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6686 /*ExplicitArgs*/ nullptr, ObjectType, 6687 ObjectClassification, Args, CandidateSet, 6688 SuppressUserConversions, false, PO); 6689 } else { 6690 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6691 ObjectType, ObjectClassification, Args, CandidateSet, 6692 SuppressUserConversions, false, None, PO); 6693 } 6694 } 6695 6696 /// AddMethodCandidate - Adds the given C++ member function to the set 6697 /// of candidate functions, using the given function call arguments 6698 /// and the object argument (@c Object). For example, in a call 6699 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6700 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6701 /// allow user-defined conversions via constructors or conversion 6702 /// operators. 6703 void 6704 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6705 CXXRecordDecl *ActingContext, QualType ObjectType, 6706 Expr::Classification ObjectClassification, 6707 ArrayRef<Expr *> Args, 6708 OverloadCandidateSet &CandidateSet, 6709 bool SuppressUserConversions, 6710 bool PartialOverloading, 6711 ConversionSequenceList EarlyConversions, 6712 OverloadCandidateParamOrder PO) { 6713 const FunctionProtoType *Proto 6714 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6715 assert(Proto && "Methods without a prototype cannot be overloaded"); 6716 assert(!isa<CXXConstructorDecl>(Method) && 6717 "Use AddOverloadCandidate for constructors"); 6718 6719 if (!CandidateSet.isNewCandidate(Method, PO)) 6720 return; 6721 6722 // C++11 [class.copy]p23: [DR1402] 6723 // A defaulted move assignment operator that is defined as deleted is 6724 // ignored by overload resolution. 6725 if (Method->isDefaulted() && Method->isDeleted() && 6726 Method->isMoveAssignmentOperator()) 6727 return; 6728 6729 // Overload resolution is always an unevaluated context. 6730 EnterExpressionEvaluationContext Unevaluated( 6731 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6732 6733 // Add this candidate 6734 OverloadCandidate &Candidate = 6735 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6736 Candidate.FoundDecl = FoundDecl; 6737 Candidate.Function = Method; 6738 Candidate.RewriteKind = 6739 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6740 Candidate.IsSurrogate = false; 6741 Candidate.IgnoreObjectArgument = false; 6742 Candidate.ExplicitCallArguments = Args.size(); 6743 6744 unsigned NumParams = Proto->getNumParams(); 6745 6746 // (C++ 13.3.2p2): A candidate function having fewer than m 6747 // parameters is viable only if it has an ellipsis in its parameter 6748 // list (8.3.5). 6749 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6750 !Proto->isVariadic()) { 6751 Candidate.Viable = false; 6752 Candidate.FailureKind = ovl_fail_too_many_arguments; 6753 return; 6754 } 6755 6756 // (C++ 13.3.2p2): A candidate function having more than m parameters 6757 // is viable only if the (m+1)st parameter has a default argument 6758 // (8.3.6). For the purposes of overload resolution, the 6759 // parameter list is truncated on the right, so that there are 6760 // exactly m parameters. 6761 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6762 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6763 // Not enough arguments. 6764 Candidate.Viable = false; 6765 Candidate.FailureKind = ovl_fail_too_few_arguments; 6766 return; 6767 } 6768 6769 Candidate.Viable = true; 6770 6771 if (Method->isStatic() || ObjectType.isNull()) 6772 // The implicit object argument is ignored. 6773 Candidate.IgnoreObjectArgument = true; 6774 else { 6775 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6776 // Determine the implicit conversion sequence for the object 6777 // parameter. 6778 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6779 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6780 Method, ActingContext); 6781 if (Candidate.Conversions[ConvIdx].isBad()) { 6782 Candidate.Viable = false; 6783 Candidate.FailureKind = ovl_fail_bad_conversion; 6784 return; 6785 } 6786 } 6787 6788 // (CUDA B.1): Check for invalid calls between targets. 6789 if (getLangOpts().CUDA) 6790 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6791 if (!IsAllowedCUDACall(Caller, Method)) { 6792 Candidate.Viable = false; 6793 Candidate.FailureKind = ovl_fail_bad_target; 6794 return; 6795 } 6796 6797 // Determine the implicit conversion sequences for each of the 6798 // arguments. 6799 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6800 unsigned ConvIdx = 6801 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6802 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6803 // We already formed a conversion sequence for this parameter during 6804 // template argument deduction. 6805 } else if (ArgIdx < NumParams) { 6806 // (C++ 13.3.2p3): for F to be a viable function, there shall 6807 // exist for each argument an implicit conversion sequence 6808 // (13.3.3.1) that converts that argument to the corresponding 6809 // parameter of F. 6810 QualType ParamType = Proto->getParamType(ArgIdx); 6811 Candidate.Conversions[ConvIdx] 6812 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6813 SuppressUserConversions, 6814 /*InOverloadResolution=*/true, 6815 /*AllowObjCWritebackConversion=*/ 6816 getLangOpts().ObjCAutoRefCount); 6817 if (Candidate.Conversions[ConvIdx].isBad()) { 6818 Candidate.Viable = false; 6819 Candidate.FailureKind = ovl_fail_bad_conversion; 6820 return; 6821 } 6822 } else { 6823 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6824 // argument for which there is no corresponding parameter is 6825 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6826 Candidate.Conversions[ConvIdx].setEllipsis(); 6827 } 6828 } 6829 6830 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6831 Candidate.Viable = false; 6832 Candidate.FailureKind = ovl_fail_enable_if; 6833 Candidate.DeductionFailure.Data = FailedAttr; 6834 return; 6835 } 6836 6837 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6838 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6839 Candidate.Viable = false; 6840 Candidate.FailureKind = ovl_non_default_multiversion_function; 6841 } 6842 } 6843 6844 /// Add a C++ member function template as a candidate to the candidate 6845 /// set, using template argument deduction to produce an appropriate member 6846 /// function template specialization. 6847 void Sema::AddMethodTemplateCandidate( 6848 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6849 CXXRecordDecl *ActingContext, 6850 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6851 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6852 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6853 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6854 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6855 return; 6856 6857 // C++ [over.match.funcs]p7: 6858 // In each case where a candidate is a function template, candidate 6859 // function template specializations are generated using template argument 6860 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6861 // candidate functions in the usual way.113) A given name can refer to one 6862 // or more function templates and also to a set of overloaded non-template 6863 // functions. In such a case, the candidate functions generated from each 6864 // function template are combined with the set of non-template candidate 6865 // functions. 6866 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6867 FunctionDecl *Specialization = nullptr; 6868 ConversionSequenceList Conversions; 6869 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6870 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6871 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6872 return CheckNonDependentConversions( 6873 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6874 SuppressUserConversions, ActingContext, ObjectType, 6875 ObjectClassification, PO); 6876 })) { 6877 OverloadCandidate &Candidate = 6878 CandidateSet.addCandidate(Conversions.size(), Conversions); 6879 Candidate.FoundDecl = FoundDecl; 6880 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6881 Candidate.Viable = false; 6882 Candidate.RewriteKind = 6883 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6884 Candidate.IsSurrogate = false; 6885 Candidate.IgnoreObjectArgument = 6886 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6887 ObjectType.isNull(); 6888 Candidate.ExplicitCallArguments = Args.size(); 6889 if (Result == TDK_NonDependentConversionFailure) 6890 Candidate.FailureKind = ovl_fail_bad_conversion; 6891 else { 6892 Candidate.FailureKind = ovl_fail_bad_deduction; 6893 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6894 Info); 6895 } 6896 return; 6897 } 6898 6899 // Add the function template specialization produced by template argument 6900 // deduction as a candidate. 6901 assert(Specialization && "Missing member function template specialization?"); 6902 assert(isa<CXXMethodDecl>(Specialization) && 6903 "Specialization is not a member function?"); 6904 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6905 ActingContext, ObjectType, ObjectClassification, Args, 6906 CandidateSet, SuppressUserConversions, PartialOverloading, 6907 Conversions, PO); 6908 } 6909 6910 /// Add a C++ function template specialization as a candidate 6911 /// in the candidate set, using template argument deduction to produce 6912 /// an appropriate function template specialization. 6913 void Sema::AddTemplateOverloadCandidate( 6914 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6915 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6916 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6917 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6918 OverloadCandidateParamOrder PO) { 6919 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6920 return; 6921 6922 // C++ [over.match.funcs]p7: 6923 // In each case where a candidate is a function template, candidate 6924 // function template specializations are generated using template argument 6925 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6926 // candidate functions in the usual way.113) A given name can refer to one 6927 // or more function templates and also to a set of overloaded non-template 6928 // functions. In such a case, the candidate functions generated from each 6929 // function template are combined with the set of non-template candidate 6930 // functions. 6931 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6932 FunctionDecl *Specialization = nullptr; 6933 ConversionSequenceList Conversions; 6934 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6935 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6936 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6937 return CheckNonDependentConversions( 6938 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 6939 SuppressUserConversions, nullptr, QualType(), {}, PO); 6940 })) { 6941 OverloadCandidate &Candidate = 6942 CandidateSet.addCandidate(Conversions.size(), Conversions); 6943 Candidate.FoundDecl = FoundDecl; 6944 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6945 Candidate.Viable = false; 6946 Candidate.RewriteKind = 6947 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6948 Candidate.IsSurrogate = false; 6949 Candidate.IsADLCandidate = IsADLCandidate; 6950 // Ignore the object argument if there is one, since we don't have an object 6951 // type. 6952 Candidate.IgnoreObjectArgument = 6953 isa<CXXMethodDecl>(Candidate.Function) && 6954 !isa<CXXConstructorDecl>(Candidate.Function); 6955 Candidate.ExplicitCallArguments = Args.size(); 6956 if (Result == TDK_NonDependentConversionFailure) 6957 Candidate.FailureKind = ovl_fail_bad_conversion; 6958 else { 6959 Candidate.FailureKind = ovl_fail_bad_deduction; 6960 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6961 Info); 6962 } 6963 return; 6964 } 6965 6966 // Add the function template specialization produced by template argument 6967 // deduction as a candidate. 6968 assert(Specialization && "Missing function template specialization?"); 6969 AddOverloadCandidate( 6970 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 6971 PartialOverloading, AllowExplicit, 6972 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 6973 } 6974 6975 /// Check that implicit conversion sequences can be formed for each argument 6976 /// whose corresponding parameter has a non-dependent type, per DR1391's 6977 /// [temp.deduct.call]p10. 6978 bool Sema::CheckNonDependentConversions( 6979 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6980 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6981 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6982 CXXRecordDecl *ActingContext, QualType ObjectType, 6983 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 6984 // FIXME: The cases in which we allow explicit conversions for constructor 6985 // arguments never consider calling a constructor template. It's not clear 6986 // that is correct. 6987 const bool AllowExplicit = false; 6988 6989 auto *FD = FunctionTemplate->getTemplatedDecl(); 6990 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6991 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6992 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6993 6994 Conversions = 6995 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6996 6997 // Overload resolution is always an unevaluated context. 6998 EnterExpressionEvaluationContext Unevaluated( 6999 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7000 7001 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7002 // require that, but this check should never result in a hard error, and 7003 // overload resolution is permitted to sidestep instantiations. 7004 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7005 !ObjectType.isNull()) { 7006 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7007 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7008 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7009 Method, ActingContext); 7010 if (Conversions[ConvIdx].isBad()) 7011 return true; 7012 } 7013 7014 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7015 ++I) { 7016 QualType ParamType = ParamTypes[I]; 7017 if (!ParamType->isDependentType()) { 7018 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7019 ? 0 7020 : (ThisConversions + I); 7021 Conversions[ConvIdx] 7022 = TryCopyInitialization(*this, Args[I], ParamType, 7023 SuppressUserConversions, 7024 /*InOverloadResolution=*/true, 7025 /*AllowObjCWritebackConversion=*/ 7026 getLangOpts().ObjCAutoRefCount, 7027 AllowExplicit); 7028 if (Conversions[ConvIdx].isBad()) 7029 return true; 7030 } 7031 } 7032 7033 return false; 7034 } 7035 7036 /// Determine whether this is an allowable conversion from the result 7037 /// of an explicit conversion operator to the expected type, per C++ 7038 /// [over.match.conv]p1 and [over.match.ref]p1. 7039 /// 7040 /// \param ConvType The return type of the conversion function. 7041 /// 7042 /// \param ToType The type we are converting to. 7043 /// 7044 /// \param AllowObjCPointerConversion Allow a conversion from one 7045 /// Objective-C pointer to another. 7046 /// 7047 /// \returns true if the conversion is allowable, false otherwise. 7048 static bool isAllowableExplicitConversion(Sema &S, 7049 QualType ConvType, QualType ToType, 7050 bool AllowObjCPointerConversion) { 7051 QualType ToNonRefType = ToType.getNonReferenceType(); 7052 7053 // Easy case: the types are the same. 7054 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7055 return true; 7056 7057 // Allow qualification conversions. 7058 bool ObjCLifetimeConversion; 7059 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7060 ObjCLifetimeConversion)) 7061 return true; 7062 7063 // If we're not allowed to consider Objective-C pointer conversions, 7064 // we're done. 7065 if (!AllowObjCPointerConversion) 7066 return false; 7067 7068 // Is this an Objective-C pointer conversion? 7069 bool IncompatibleObjC = false; 7070 QualType ConvertedType; 7071 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7072 IncompatibleObjC); 7073 } 7074 7075 /// AddConversionCandidate - Add a C++ conversion function as a 7076 /// candidate in the candidate set (C++ [over.match.conv], 7077 /// C++ [over.match.copy]). From is the expression we're converting from, 7078 /// and ToType is the type that we're eventually trying to convert to 7079 /// (which may or may not be the same type as the type that the 7080 /// conversion function produces). 7081 void Sema::AddConversionCandidate( 7082 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7083 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7084 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7085 bool AllowExplicit, bool AllowResultConversion) { 7086 assert(!Conversion->getDescribedFunctionTemplate() && 7087 "Conversion function templates use AddTemplateConversionCandidate"); 7088 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7089 if (!CandidateSet.isNewCandidate(Conversion)) 7090 return; 7091 7092 // If the conversion function has an undeduced return type, trigger its 7093 // deduction now. 7094 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7095 if (DeduceReturnType(Conversion, From->getExprLoc())) 7096 return; 7097 ConvType = Conversion->getConversionType().getNonReferenceType(); 7098 } 7099 7100 // If we don't allow any conversion of the result type, ignore conversion 7101 // functions that don't convert to exactly (possibly cv-qualified) T. 7102 if (!AllowResultConversion && 7103 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7104 return; 7105 7106 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7107 // operator is only a candidate if its return type is the target type or 7108 // can be converted to the target type with a qualification conversion. 7109 if (Conversion->isExplicit() && 7110 !isAllowableExplicitConversion(*this, ConvType, ToType, 7111 AllowObjCConversionOnExplicit)) 7112 return; 7113 7114 // Overload resolution is always an unevaluated context. 7115 EnterExpressionEvaluationContext Unevaluated( 7116 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7117 7118 // Add this candidate 7119 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7120 Candidate.FoundDecl = FoundDecl; 7121 Candidate.Function = Conversion; 7122 Candidate.IsSurrogate = false; 7123 Candidate.IgnoreObjectArgument = false; 7124 Candidate.FinalConversion.setAsIdentityConversion(); 7125 Candidate.FinalConversion.setFromType(ConvType); 7126 Candidate.FinalConversion.setAllToTypes(ToType); 7127 Candidate.Viable = true; 7128 Candidate.ExplicitCallArguments = 1; 7129 7130 // C++ [over.match.funcs]p4: 7131 // For conversion functions, the function is considered to be a member of 7132 // the class of the implicit implied object argument for the purpose of 7133 // defining the type of the implicit object parameter. 7134 // 7135 // Determine the implicit conversion sequence for the implicit 7136 // object parameter. 7137 QualType ImplicitParamType = From->getType(); 7138 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7139 ImplicitParamType = FromPtrType->getPointeeType(); 7140 CXXRecordDecl *ConversionContext 7141 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7142 7143 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7144 *this, CandidateSet.getLocation(), From->getType(), 7145 From->Classify(Context), Conversion, ConversionContext); 7146 7147 if (Candidate.Conversions[0].isBad()) { 7148 Candidate.Viable = false; 7149 Candidate.FailureKind = ovl_fail_bad_conversion; 7150 return; 7151 } 7152 7153 // We won't go through a user-defined type conversion function to convert a 7154 // derived to base as such conversions are given Conversion Rank. They only 7155 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7156 QualType FromCanon 7157 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7158 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7159 if (FromCanon == ToCanon || 7160 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7161 Candidate.Viable = false; 7162 Candidate.FailureKind = ovl_fail_trivial_conversion; 7163 return; 7164 } 7165 7166 // To determine what the conversion from the result of calling the 7167 // conversion function to the type we're eventually trying to 7168 // convert to (ToType), we need to synthesize a call to the 7169 // conversion function and attempt copy initialization from it. This 7170 // makes sure that we get the right semantics with respect to 7171 // lvalues/rvalues and the type. Fortunately, we can allocate this 7172 // call on the stack and we don't need its arguments to be 7173 // well-formed. 7174 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7175 VK_LValue, From->getBeginLoc()); 7176 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7177 Context.getPointerType(Conversion->getType()), 7178 CK_FunctionToPointerDecay, 7179 &ConversionRef, VK_RValue); 7180 7181 QualType ConversionType = Conversion->getConversionType(); 7182 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7183 Candidate.Viable = false; 7184 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7185 return; 7186 } 7187 7188 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7189 7190 // Note that it is safe to allocate CallExpr on the stack here because 7191 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7192 // allocator). 7193 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7194 7195 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7196 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7197 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7198 7199 ImplicitConversionSequence ICS = 7200 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7201 /*SuppressUserConversions=*/true, 7202 /*InOverloadResolution=*/false, 7203 /*AllowObjCWritebackConversion=*/false); 7204 7205 switch (ICS.getKind()) { 7206 case ImplicitConversionSequence::StandardConversion: 7207 Candidate.FinalConversion = ICS.Standard; 7208 7209 // C++ [over.ics.user]p3: 7210 // If the user-defined conversion is specified by a specialization of a 7211 // conversion function template, the second standard conversion sequence 7212 // shall have exact match rank. 7213 if (Conversion->getPrimaryTemplate() && 7214 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7215 Candidate.Viable = false; 7216 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7217 return; 7218 } 7219 7220 // C++0x [dcl.init.ref]p5: 7221 // In the second case, if the reference is an rvalue reference and 7222 // the second standard conversion sequence of the user-defined 7223 // conversion sequence includes an lvalue-to-rvalue conversion, the 7224 // program is ill-formed. 7225 if (ToType->isRValueReferenceType() && 7226 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7227 Candidate.Viable = false; 7228 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7229 return; 7230 } 7231 break; 7232 7233 case ImplicitConversionSequence::BadConversion: 7234 Candidate.Viable = false; 7235 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7236 return; 7237 7238 default: 7239 llvm_unreachable( 7240 "Can only end up with a standard conversion sequence or failure"); 7241 } 7242 7243 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != 7244 ExplicitSpecKind::ResolvedFalse) { 7245 Candidate.Viable = false; 7246 Candidate.FailureKind = ovl_fail_explicit_resolved; 7247 return; 7248 } 7249 7250 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7251 Candidate.Viable = false; 7252 Candidate.FailureKind = ovl_fail_enable_if; 7253 Candidate.DeductionFailure.Data = FailedAttr; 7254 return; 7255 } 7256 7257 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7258 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7259 Candidate.Viable = false; 7260 Candidate.FailureKind = ovl_non_default_multiversion_function; 7261 } 7262 } 7263 7264 /// Adds a conversion function template specialization 7265 /// candidate to the overload set, using template argument deduction 7266 /// to deduce the template arguments of the conversion function 7267 /// template from the type that we are converting to (C++ 7268 /// [temp.deduct.conv]). 7269 void Sema::AddTemplateConversionCandidate( 7270 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7271 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7272 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7273 bool AllowExplicit, bool AllowResultConversion) { 7274 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7275 "Only conversion function templates permitted here"); 7276 7277 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7278 return; 7279 7280 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7281 CXXConversionDecl *Specialization = nullptr; 7282 if (TemplateDeductionResult Result 7283 = DeduceTemplateArguments(FunctionTemplate, ToType, 7284 Specialization, Info)) { 7285 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7286 Candidate.FoundDecl = FoundDecl; 7287 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7288 Candidate.Viable = false; 7289 Candidate.FailureKind = ovl_fail_bad_deduction; 7290 Candidate.IsSurrogate = false; 7291 Candidate.IgnoreObjectArgument = false; 7292 Candidate.ExplicitCallArguments = 1; 7293 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7294 Info); 7295 return; 7296 } 7297 7298 // Add the conversion function template specialization produced by 7299 // template argument deduction as a candidate. 7300 assert(Specialization && "Missing function template specialization?"); 7301 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7302 CandidateSet, AllowObjCConversionOnExplicit, 7303 AllowExplicit, AllowResultConversion); 7304 } 7305 7306 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7307 /// converts the given @c Object to a function pointer via the 7308 /// conversion function @c Conversion, and then attempts to call it 7309 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7310 /// the type of function that we'll eventually be calling. 7311 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7312 DeclAccessPair FoundDecl, 7313 CXXRecordDecl *ActingContext, 7314 const FunctionProtoType *Proto, 7315 Expr *Object, 7316 ArrayRef<Expr *> Args, 7317 OverloadCandidateSet& CandidateSet) { 7318 if (!CandidateSet.isNewCandidate(Conversion)) 7319 return; 7320 7321 // Overload resolution is always an unevaluated context. 7322 EnterExpressionEvaluationContext Unevaluated( 7323 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7324 7325 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7326 Candidate.FoundDecl = FoundDecl; 7327 Candidate.Function = nullptr; 7328 Candidate.Surrogate = Conversion; 7329 Candidate.Viable = true; 7330 Candidate.IsSurrogate = true; 7331 Candidate.IgnoreObjectArgument = false; 7332 Candidate.ExplicitCallArguments = Args.size(); 7333 7334 // Determine the implicit conversion sequence for the implicit 7335 // object parameter. 7336 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7337 *this, CandidateSet.getLocation(), Object->getType(), 7338 Object->Classify(Context), Conversion, ActingContext); 7339 if (ObjectInit.isBad()) { 7340 Candidate.Viable = false; 7341 Candidate.FailureKind = ovl_fail_bad_conversion; 7342 Candidate.Conversions[0] = ObjectInit; 7343 return; 7344 } 7345 7346 // The first conversion is actually a user-defined conversion whose 7347 // first conversion is ObjectInit's standard conversion (which is 7348 // effectively a reference binding). Record it as such. 7349 Candidate.Conversions[0].setUserDefined(); 7350 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7351 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7352 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7353 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7354 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7355 Candidate.Conversions[0].UserDefined.After 7356 = Candidate.Conversions[0].UserDefined.Before; 7357 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7358 7359 // Find the 7360 unsigned NumParams = Proto->getNumParams(); 7361 7362 // (C++ 13.3.2p2): A candidate function having fewer than m 7363 // parameters is viable only if it has an ellipsis in its parameter 7364 // list (8.3.5). 7365 if (Args.size() > NumParams && !Proto->isVariadic()) { 7366 Candidate.Viable = false; 7367 Candidate.FailureKind = ovl_fail_too_many_arguments; 7368 return; 7369 } 7370 7371 // Function types don't have any default arguments, so just check if 7372 // we have enough arguments. 7373 if (Args.size() < NumParams) { 7374 // Not enough arguments. 7375 Candidate.Viable = false; 7376 Candidate.FailureKind = ovl_fail_too_few_arguments; 7377 return; 7378 } 7379 7380 // Determine the implicit conversion sequences for each of the 7381 // arguments. 7382 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7383 if (ArgIdx < NumParams) { 7384 // (C++ 13.3.2p3): for F to be a viable function, there shall 7385 // exist for each argument an implicit conversion sequence 7386 // (13.3.3.1) that converts that argument to the corresponding 7387 // parameter of F. 7388 QualType ParamType = Proto->getParamType(ArgIdx); 7389 Candidate.Conversions[ArgIdx + 1] 7390 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7391 /*SuppressUserConversions=*/false, 7392 /*InOverloadResolution=*/false, 7393 /*AllowObjCWritebackConversion=*/ 7394 getLangOpts().ObjCAutoRefCount); 7395 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7396 Candidate.Viable = false; 7397 Candidate.FailureKind = ovl_fail_bad_conversion; 7398 return; 7399 } 7400 } else { 7401 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7402 // argument for which there is no corresponding parameter is 7403 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7404 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7405 } 7406 } 7407 7408 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7409 Candidate.Viable = false; 7410 Candidate.FailureKind = ovl_fail_enable_if; 7411 Candidate.DeductionFailure.Data = FailedAttr; 7412 return; 7413 } 7414 } 7415 7416 /// Add all of the non-member operator function declarations in the given 7417 /// function set to the overload candidate set. 7418 void Sema::AddNonMemberOperatorCandidates( 7419 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7420 OverloadCandidateSet &CandidateSet, 7421 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7422 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7423 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7424 ArrayRef<Expr *> FunctionArgs = Args; 7425 7426 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7427 FunctionDecl *FD = 7428 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7429 7430 // Don't consider rewritten functions if we're not rewriting. 7431 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7432 continue; 7433 7434 assert(!isa<CXXMethodDecl>(FD) && 7435 "unqualified operator lookup found a member function"); 7436 7437 if (FunTmpl) { 7438 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7439 FunctionArgs, CandidateSet); 7440 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7441 AddTemplateOverloadCandidate( 7442 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7443 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7444 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7445 } else { 7446 if (ExplicitTemplateArgs) 7447 continue; 7448 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7449 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7450 AddOverloadCandidate(FD, F.getPair(), 7451 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7452 false, false, true, false, ADLCallKind::NotADL, 7453 None, OverloadCandidateParamOrder::Reversed); 7454 } 7455 } 7456 } 7457 7458 /// Add overload candidates for overloaded operators that are 7459 /// member functions. 7460 /// 7461 /// Add the overloaded operator candidates that are member functions 7462 /// for the operator Op that was used in an operator expression such 7463 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7464 /// CandidateSet will store the added overload candidates. (C++ 7465 /// [over.match.oper]). 7466 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7467 SourceLocation OpLoc, 7468 ArrayRef<Expr *> Args, 7469 OverloadCandidateSet &CandidateSet, 7470 OverloadCandidateParamOrder PO) { 7471 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7472 7473 // C++ [over.match.oper]p3: 7474 // For a unary operator @ with an operand of a type whose 7475 // cv-unqualified version is T1, and for a binary operator @ with 7476 // a left operand of a type whose cv-unqualified version is T1 and 7477 // a right operand of a type whose cv-unqualified version is T2, 7478 // three sets of candidate functions, designated member 7479 // candidates, non-member candidates and built-in candidates, are 7480 // constructed as follows: 7481 QualType T1 = Args[0]->getType(); 7482 7483 // -- If T1 is a complete class type or a class currently being 7484 // defined, the set of member candidates is the result of the 7485 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7486 // the set of member candidates is empty. 7487 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7488 // Complete the type if it can be completed. 7489 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7490 return; 7491 // If the type is neither complete nor being defined, bail out now. 7492 if (!T1Rec->getDecl()->getDefinition()) 7493 return; 7494 7495 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7496 LookupQualifiedName(Operators, T1Rec->getDecl()); 7497 Operators.suppressDiagnostics(); 7498 7499 for (LookupResult::iterator Oper = Operators.begin(), 7500 OperEnd = Operators.end(); 7501 Oper != OperEnd; 7502 ++Oper) 7503 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7504 Args[0]->Classify(Context), Args.slice(1), 7505 CandidateSet, /*SuppressUserConversion=*/false, PO); 7506 } 7507 } 7508 7509 /// AddBuiltinCandidate - Add a candidate for a built-in 7510 /// operator. ResultTy and ParamTys are the result and parameter types 7511 /// of the built-in candidate, respectively. Args and NumArgs are the 7512 /// arguments being passed to the candidate. IsAssignmentOperator 7513 /// should be true when this built-in candidate is an assignment 7514 /// operator. NumContextualBoolArguments is the number of arguments 7515 /// (at the beginning of the argument list) that will be contextually 7516 /// converted to bool. 7517 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7518 OverloadCandidateSet& CandidateSet, 7519 bool IsAssignmentOperator, 7520 unsigned NumContextualBoolArguments) { 7521 // Overload resolution is always an unevaluated context. 7522 EnterExpressionEvaluationContext Unevaluated( 7523 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7524 7525 // Add this candidate 7526 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7527 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7528 Candidate.Function = nullptr; 7529 Candidate.IsSurrogate = false; 7530 Candidate.IgnoreObjectArgument = false; 7531 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7532 7533 // Determine the implicit conversion sequences for each of the 7534 // arguments. 7535 Candidate.Viable = true; 7536 Candidate.ExplicitCallArguments = Args.size(); 7537 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7538 // C++ [over.match.oper]p4: 7539 // For the built-in assignment operators, conversions of the 7540 // left operand are restricted as follows: 7541 // -- no temporaries are introduced to hold the left operand, and 7542 // -- no user-defined conversions are applied to the left 7543 // operand to achieve a type match with the left-most 7544 // parameter of a built-in candidate. 7545 // 7546 // We block these conversions by turning off user-defined 7547 // conversions, since that is the only way that initialization of 7548 // a reference to a non-class type can occur from something that 7549 // is not of the same type. 7550 if (ArgIdx < NumContextualBoolArguments) { 7551 assert(ParamTys[ArgIdx] == Context.BoolTy && 7552 "Contextual conversion to bool requires bool type"); 7553 Candidate.Conversions[ArgIdx] 7554 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7555 } else { 7556 Candidate.Conversions[ArgIdx] 7557 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7558 ArgIdx == 0 && IsAssignmentOperator, 7559 /*InOverloadResolution=*/false, 7560 /*AllowObjCWritebackConversion=*/ 7561 getLangOpts().ObjCAutoRefCount); 7562 } 7563 if (Candidate.Conversions[ArgIdx].isBad()) { 7564 Candidate.Viable = false; 7565 Candidate.FailureKind = ovl_fail_bad_conversion; 7566 break; 7567 } 7568 } 7569 } 7570 7571 namespace { 7572 7573 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7574 /// candidate operator functions for built-in operators (C++ 7575 /// [over.built]). The types are separated into pointer types and 7576 /// enumeration types. 7577 class BuiltinCandidateTypeSet { 7578 /// TypeSet - A set of types. 7579 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7580 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7581 7582 /// PointerTypes - The set of pointer types that will be used in the 7583 /// built-in candidates. 7584 TypeSet PointerTypes; 7585 7586 /// MemberPointerTypes - The set of member pointer types that will be 7587 /// used in the built-in candidates. 7588 TypeSet MemberPointerTypes; 7589 7590 /// EnumerationTypes - The set of enumeration types that will be 7591 /// used in the built-in candidates. 7592 TypeSet EnumerationTypes; 7593 7594 /// The set of vector types that will be used in the built-in 7595 /// candidates. 7596 TypeSet VectorTypes; 7597 7598 /// A flag indicating non-record types are viable candidates 7599 bool HasNonRecordTypes; 7600 7601 /// A flag indicating whether either arithmetic or enumeration types 7602 /// were present in the candidate set. 7603 bool HasArithmeticOrEnumeralTypes; 7604 7605 /// A flag indicating whether the nullptr type was present in the 7606 /// candidate set. 7607 bool HasNullPtrType; 7608 7609 /// Sema - The semantic analysis instance where we are building the 7610 /// candidate type set. 7611 Sema &SemaRef; 7612 7613 /// Context - The AST context in which we will build the type sets. 7614 ASTContext &Context; 7615 7616 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7617 const Qualifiers &VisibleQuals); 7618 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7619 7620 public: 7621 /// iterator - Iterates through the types that are part of the set. 7622 typedef TypeSet::iterator iterator; 7623 7624 BuiltinCandidateTypeSet(Sema &SemaRef) 7625 : HasNonRecordTypes(false), 7626 HasArithmeticOrEnumeralTypes(false), 7627 HasNullPtrType(false), 7628 SemaRef(SemaRef), 7629 Context(SemaRef.Context) { } 7630 7631 void AddTypesConvertedFrom(QualType Ty, 7632 SourceLocation Loc, 7633 bool AllowUserConversions, 7634 bool AllowExplicitConversions, 7635 const Qualifiers &VisibleTypeConversionsQuals); 7636 7637 /// pointer_begin - First pointer type found; 7638 iterator pointer_begin() { return PointerTypes.begin(); } 7639 7640 /// pointer_end - Past the last pointer type found; 7641 iterator pointer_end() { return PointerTypes.end(); } 7642 7643 /// member_pointer_begin - First member pointer type found; 7644 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7645 7646 /// member_pointer_end - Past the last member pointer type found; 7647 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7648 7649 /// enumeration_begin - First enumeration type found; 7650 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7651 7652 /// enumeration_end - Past the last enumeration type found; 7653 iterator enumeration_end() { return EnumerationTypes.end(); } 7654 7655 iterator vector_begin() { return VectorTypes.begin(); } 7656 iterator vector_end() { return VectorTypes.end(); } 7657 7658 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7659 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7660 bool hasNullPtrType() const { return HasNullPtrType; } 7661 }; 7662 7663 } // end anonymous namespace 7664 7665 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7666 /// the set of pointer types along with any more-qualified variants of 7667 /// that type. For example, if @p Ty is "int const *", this routine 7668 /// will add "int const *", "int const volatile *", "int const 7669 /// restrict *", and "int const volatile restrict *" to the set of 7670 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7671 /// false otherwise. 7672 /// 7673 /// FIXME: what to do about extended qualifiers? 7674 bool 7675 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7676 const Qualifiers &VisibleQuals) { 7677 7678 // Insert this type. 7679 if (!PointerTypes.insert(Ty)) 7680 return false; 7681 7682 QualType PointeeTy; 7683 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7684 bool buildObjCPtr = false; 7685 if (!PointerTy) { 7686 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7687 PointeeTy = PTy->getPointeeType(); 7688 buildObjCPtr = true; 7689 } else { 7690 PointeeTy = PointerTy->getPointeeType(); 7691 } 7692 7693 // Don't add qualified variants of arrays. For one, they're not allowed 7694 // (the qualifier would sink to the element type), and for another, the 7695 // only overload situation where it matters is subscript or pointer +- int, 7696 // and those shouldn't have qualifier variants anyway. 7697 if (PointeeTy->isArrayType()) 7698 return true; 7699 7700 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7701 bool hasVolatile = VisibleQuals.hasVolatile(); 7702 bool hasRestrict = VisibleQuals.hasRestrict(); 7703 7704 // Iterate through all strict supersets of BaseCVR. 7705 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7706 if ((CVR | BaseCVR) != CVR) continue; 7707 // Skip over volatile if no volatile found anywhere in the types. 7708 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7709 7710 // Skip over restrict if no restrict found anywhere in the types, or if 7711 // the type cannot be restrict-qualified. 7712 if ((CVR & Qualifiers::Restrict) && 7713 (!hasRestrict || 7714 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7715 continue; 7716 7717 // Build qualified pointee type. 7718 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7719 7720 // Build qualified pointer type. 7721 QualType QPointerTy; 7722 if (!buildObjCPtr) 7723 QPointerTy = Context.getPointerType(QPointeeTy); 7724 else 7725 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7726 7727 // Insert qualified pointer type. 7728 PointerTypes.insert(QPointerTy); 7729 } 7730 7731 return true; 7732 } 7733 7734 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7735 /// to the set of pointer types along with any more-qualified variants of 7736 /// that type. For example, if @p Ty is "int const *", this routine 7737 /// will add "int const *", "int const volatile *", "int const 7738 /// restrict *", and "int const volatile restrict *" to the set of 7739 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7740 /// false otherwise. 7741 /// 7742 /// FIXME: what to do about extended qualifiers? 7743 bool 7744 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7745 QualType Ty) { 7746 // Insert this type. 7747 if (!MemberPointerTypes.insert(Ty)) 7748 return false; 7749 7750 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7751 assert(PointerTy && "type was not a member pointer type!"); 7752 7753 QualType PointeeTy = PointerTy->getPointeeType(); 7754 // Don't add qualified variants of arrays. For one, they're not allowed 7755 // (the qualifier would sink to the element type), and for another, the 7756 // only overload situation where it matters is subscript or pointer +- int, 7757 // and those shouldn't have qualifier variants anyway. 7758 if (PointeeTy->isArrayType()) 7759 return true; 7760 const Type *ClassTy = PointerTy->getClass(); 7761 7762 // Iterate through all strict supersets of the pointee type's CVR 7763 // qualifiers. 7764 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7765 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7766 if ((CVR | BaseCVR) != CVR) continue; 7767 7768 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7769 MemberPointerTypes.insert( 7770 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7771 } 7772 7773 return true; 7774 } 7775 7776 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7777 /// Ty can be implicit converted to the given set of @p Types. We're 7778 /// primarily interested in pointer types and enumeration types. We also 7779 /// take member pointer types, for the conditional operator. 7780 /// AllowUserConversions is true if we should look at the conversion 7781 /// functions of a class type, and AllowExplicitConversions if we 7782 /// should also include the explicit conversion functions of a class 7783 /// type. 7784 void 7785 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7786 SourceLocation Loc, 7787 bool AllowUserConversions, 7788 bool AllowExplicitConversions, 7789 const Qualifiers &VisibleQuals) { 7790 // Only deal with canonical types. 7791 Ty = Context.getCanonicalType(Ty); 7792 7793 // Look through reference types; they aren't part of the type of an 7794 // expression for the purposes of conversions. 7795 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7796 Ty = RefTy->getPointeeType(); 7797 7798 // If we're dealing with an array type, decay to the pointer. 7799 if (Ty->isArrayType()) 7800 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7801 7802 // Otherwise, we don't care about qualifiers on the type. 7803 Ty = Ty.getLocalUnqualifiedType(); 7804 7805 // Flag if we ever add a non-record type. 7806 const RecordType *TyRec = Ty->getAs<RecordType>(); 7807 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7808 7809 // Flag if we encounter an arithmetic type. 7810 HasArithmeticOrEnumeralTypes = 7811 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7812 7813 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7814 PointerTypes.insert(Ty); 7815 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7816 // Insert our type, and its more-qualified variants, into the set 7817 // of types. 7818 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7819 return; 7820 } else if (Ty->isMemberPointerType()) { 7821 // Member pointers are far easier, since the pointee can't be converted. 7822 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7823 return; 7824 } else if (Ty->isEnumeralType()) { 7825 HasArithmeticOrEnumeralTypes = true; 7826 EnumerationTypes.insert(Ty); 7827 } else if (Ty->isVectorType()) { 7828 // We treat vector types as arithmetic types in many contexts as an 7829 // extension. 7830 HasArithmeticOrEnumeralTypes = true; 7831 VectorTypes.insert(Ty); 7832 } else if (Ty->isNullPtrType()) { 7833 HasNullPtrType = true; 7834 } else if (AllowUserConversions && TyRec) { 7835 // No conversion functions in incomplete types. 7836 if (!SemaRef.isCompleteType(Loc, Ty)) 7837 return; 7838 7839 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7840 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7841 if (isa<UsingShadowDecl>(D)) 7842 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7843 7844 // Skip conversion function templates; they don't tell us anything 7845 // about which builtin types we can convert to. 7846 if (isa<FunctionTemplateDecl>(D)) 7847 continue; 7848 7849 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7850 if (AllowExplicitConversions || !Conv->isExplicit()) { 7851 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7852 VisibleQuals); 7853 } 7854 } 7855 } 7856 } 7857 /// Helper function for adjusting address spaces for the pointer or reference 7858 /// operands of builtin operators depending on the argument. 7859 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7860 Expr *Arg) { 7861 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7862 } 7863 7864 /// Helper function for AddBuiltinOperatorCandidates() that adds 7865 /// the volatile- and non-volatile-qualified assignment operators for the 7866 /// given type to the candidate set. 7867 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7868 QualType T, 7869 ArrayRef<Expr *> Args, 7870 OverloadCandidateSet &CandidateSet) { 7871 QualType ParamTypes[2]; 7872 7873 // T& operator=(T&, T) 7874 ParamTypes[0] = S.Context.getLValueReferenceType( 7875 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7876 ParamTypes[1] = T; 7877 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7878 /*IsAssignmentOperator=*/true); 7879 7880 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7881 // volatile T& operator=(volatile T&, T) 7882 ParamTypes[0] = S.Context.getLValueReferenceType( 7883 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7884 Args[0])); 7885 ParamTypes[1] = T; 7886 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7887 /*IsAssignmentOperator=*/true); 7888 } 7889 } 7890 7891 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7892 /// if any, found in visible type conversion functions found in ArgExpr's type. 7893 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7894 Qualifiers VRQuals; 7895 const RecordType *TyRec; 7896 if (const MemberPointerType *RHSMPType = 7897 ArgExpr->getType()->getAs<MemberPointerType>()) 7898 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7899 else 7900 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7901 if (!TyRec) { 7902 // Just to be safe, assume the worst case. 7903 VRQuals.addVolatile(); 7904 VRQuals.addRestrict(); 7905 return VRQuals; 7906 } 7907 7908 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7909 if (!ClassDecl->hasDefinition()) 7910 return VRQuals; 7911 7912 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7913 if (isa<UsingShadowDecl>(D)) 7914 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7915 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7916 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7917 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7918 CanTy = ResTypeRef->getPointeeType(); 7919 // Need to go down the pointer/mempointer chain and add qualifiers 7920 // as see them. 7921 bool done = false; 7922 while (!done) { 7923 if (CanTy.isRestrictQualified()) 7924 VRQuals.addRestrict(); 7925 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7926 CanTy = ResTypePtr->getPointeeType(); 7927 else if (const MemberPointerType *ResTypeMPtr = 7928 CanTy->getAs<MemberPointerType>()) 7929 CanTy = ResTypeMPtr->getPointeeType(); 7930 else 7931 done = true; 7932 if (CanTy.isVolatileQualified()) 7933 VRQuals.addVolatile(); 7934 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7935 return VRQuals; 7936 } 7937 } 7938 } 7939 return VRQuals; 7940 } 7941 7942 namespace { 7943 7944 /// Helper class to manage the addition of builtin operator overload 7945 /// candidates. It provides shared state and utility methods used throughout 7946 /// the process, as well as a helper method to add each group of builtin 7947 /// operator overloads from the standard to a candidate set. 7948 class BuiltinOperatorOverloadBuilder { 7949 // Common instance state available to all overload candidate addition methods. 7950 Sema &S; 7951 ArrayRef<Expr *> Args; 7952 Qualifiers VisibleTypeConversionsQuals; 7953 bool HasArithmeticOrEnumeralCandidateType; 7954 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7955 OverloadCandidateSet &CandidateSet; 7956 7957 static constexpr int ArithmeticTypesCap = 24; 7958 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7959 7960 // Define some indices used to iterate over the arithmetic types in 7961 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7962 // types are that preserved by promotion (C++ [over.built]p2). 7963 unsigned FirstIntegralType, 7964 LastIntegralType; 7965 unsigned FirstPromotedIntegralType, 7966 LastPromotedIntegralType; 7967 unsigned FirstPromotedArithmeticType, 7968 LastPromotedArithmeticType; 7969 unsigned NumArithmeticTypes; 7970 7971 void InitArithmeticTypes() { 7972 // Start of promoted types. 7973 FirstPromotedArithmeticType = 0; 7974 ArithmeticTypes.push_back(S.Context.FloatTy); 7975 ArithmeticTypes.push_back(S.Context.DoubleTy); 7976 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7977 if (S.Context.getTargetInfo().hasFloat128Type()) 7978 ArithmeticTypes.push_back(S.Context.Float128Ty); 7979 7980 // Start of integral types. 7981 FirstIntegralType = ArithmeticTypes.size(); 7982 FirstPromotedIntegralType = ArithmeticTypes.size(); 7983 ArithmeticTypes.push_back(S.Context.IntTy); 7984 ArithmeticTypes.push_back(S.Context.LongTy); 7985 ArithmeticTypes.push_back(S.Context.LongLongTy); 7986 if (S.Context.getTargetInfo().hasInt128Type()) 7987 ArithmeticTypes.push_back(S.Context.Int128Ty); 7988 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7989 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7990 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7991 if (S.Context.getTargetInfo().hasInt128Type()) 7992 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7993 LastPromotedIntegralType = ArithmeticTypes.size(); 7994 LastPromotedArithmeticType = ArithmeticTypes.size(); 7995 // End of promoted types. 7996 7997 ArithmeticTypes.push_back(S.Context.BoolTy); 7998 ArithmeticTypes.push_back(S.Context.CharTy); 7999 ArithmeticTypes.push_back(S.Context.WCharTy); 8000 if (S.Context.getLangOpts().Char8) 8001 ArithmeticTypes.push_back(S.Context.Char8Ty); 8002 ArithmeticTypes.push_back(S.Context.Char16Ty); 8003 ArithmeticTypes.push_back(S.Context.Char32Ty); 8004 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8005 ArithmeticTypes.push_back(S.Context.ShortTy); 8006 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8007 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8008 LastIntegralType = ArithmeticTypes.size(); 8009 NumArithmeticTypes = ArithmeticTypes.size(); 8010 // End of integral types. 8011 // FIXME: What about complex? What about half? 8012 8013 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8014 "Enough inline storage for all arithmetic types."); 8015 } 8016 8017 /// Helper method to factor out the common pattern of adding overloads 8018 /// for '++' and '--' builtin operators. 8019 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8020 bool HasVolatile, 8021 bool HasRestrict) { 8022 QualType ParamTypes[2] = { 8023 S.Context.getLValueReferenceType(CandidateTy), 8024 S.Context.IntTy 8025 }; 8026 8027 // Non-volatile version. 8028 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8029 8030 // Use a heuristic to reduce number of builtin candidates in the set: 8031 // add volatile version only if there are conversions to a volatile type. 8032 if (HasVolatile) { 8033 ParamTypes[0] = 8034 S.Context.getLValueReferenceType( 8035 S.Context.getVolatileType(CandidateTy)); 8036 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8037 } 8038 8039 // Add restrict version only if there are conversions to a restrict type 8040 // and our candidate type is a non-restrict-qualified pointer. 8041 if (HasRestrict && CandidateTy->isAnyPointerType() && 8042 !CandidateTy.isRestrictQualified()) { 8043 ParamTypes[0] 8044 = S.Context.getLValueReferenceType( 8045 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8046 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8047 8048 if (HasVolatile) { 8049 ParamTypes[0] 8050 = S.Context.getLValueReferenceType( 8051 S.Context.getCVRQualifiedType(CandidateTy, 8052 (Qualifiers::Volatile | 8053 Qualifiers::Restrict))); 8054 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8055 } 8056 } 8057 8058 } 8059 8060 public: 8061 BuiltinOperatorOverloadBuilder( 8062 Sema &S, ArrayRef<Expr *> Args, 8063 Qualifiers VisibleTypeConversionsQuals, 8064 bool HasArithmeticOrEnumeralCandidateType, 8065 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8066 OverloadCandidateSet &CandidateSet) 8067 : S(S), Args(Args), 8068 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8069 HasArithmeticOrEnumeralCandidateType( 8070 HasArithmeticOrEnumeralCandidateType), 8071 CandidateTypes(CandidateTypes), 8072 CandidateSet(CandidateSet) { 8073 8074 InitArithmeticTypes(); 8075 } 8076 8077 // Increment is deprecated for bool since C++17. 8078 // 8079 // C++ [over.built]p3: 8080 // 8081 // For every pair (T, VQ), where T is an arithmetic type other 8082 // than bool, and VQ is either volatile or empty, there exist 8083 // candidate operator functions of the form 8084 // 8085 // VQ T& operator++(VQ T&); 8086 // T operator++(VQ T&, int); 8087 // 8088 // C++ [over.built]p4: 8089 // 8090 // For every pair (T, VQ), where T is an arithmetic type other 8091 // than bool, and VQ is either volatile or empty, there exist 8092 // candidate operator functions of the form 8093 // 8094 // VQ T& operator--(VQ T&); 8095 // T operator--(VQ T&, int); 8096 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8097 if (!HasArithmeticOrEnumeralCandidateType) 8098 return; 8099 8100 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8101 const auto TypeOfT = ArithmeticTypes[Arith]; 8102 if (TypeOfT == S.Context.BoolTy) { 8103 if (Op == OO_MinusMinus) 8104 continue; 8105 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8106 continue; 8107 } 8108 addPlusPlusMinusMinusStyleOverloads( 8109 TypeOfT, 8110 VisibleTypeConversionsQuals.hasVolatile(), 8111 VisibleTypeConversionsQuals.hasRestrict()); 8112 } 8113 } 8114 8115 // C++ [over.built]p5: 8116 // 8117 // For every pair (T, VQ), where T is a cv-qualified or 8118 // cv-unqualified object type, and VQ is either volatile or 8119 // empty, there exist candidate operator functions of the form 8120 // 8121 // T*VQ& operator++(T*VQ&); 8122 // T*VQ& operator--(T*VQ&); 8123 // T* operator++(T*VQ&, int); 8124 // T* operator--(T*VQ&, int); 8125 void addPlusPlusMinusMinusPointerOverloads() { 8126 for (BuiltinCandidateTypeSet::iterator 8127 Ptr = CandidateTypes[0].pointer_begin(), 8128 PtrEnd = CandidateTypes[0].pointer_end(); 8129 Ptr != PtrEnd; ++Ptr) { 8130 // Skip pointer types that aren't pointers to object types. 8131 if (!(*Ptr)->getPointeeType()->isObjectType()) 8132 continue; 8133 8134 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8135 (!(*Ptr).isVolatileQualified() && 8136 VisibleTypeConversionsQuals.hasVolatile()), 8137 (!(*Ptr).isRestrictQualified() && 8138 VisibleTypeConversionsQuals.hasRestrict())); 8139 } 8140 } 8141 8142 // C++ [over.built]p6: 8143 // For every cv-qualified or cv-unqualified object type T, there 8144 // exist candidate operator functions of the form 8145 // 8146 // T& operator*(T*); 8147 // 8148 // C++ [over.built]p7: 8149 // For every function type T that does not have cv-qualifiers or a 8150 // ref-qualifier, there exist candidate operator functions of the form 8151 // T& operator*(T*); 8152 void addUnaryStarPointerOverloads() { 8153 for (BuiltinCandidateTypeSet::iterator 8154 Ptr = CandidateTypes[0].pointer_begin(), 8155 PtrEnd = CandidateTypes[0].pointer_end(); 8156 Ptr != PtrEnd; ++Ptr) { 8157 QualType ParamTy = *Ptr; 8158 QualType PointeeTy = ParamTy->getPointeeType(); 8159 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8160 continue; 8161 8162 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8163 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8164 continue; 8165 8166 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8167 } 8168 } 8169 8170 // C++ [over.built]p9: 8171 // For every promoted arithmetic type T, there exist candidate 8172 // operator functions of the form 8173 // 8174 // T operator+(T); 8175 // T operator-(T); 8176 void addUnaryPlusOrMinusArithmeticOverloads() { 8177 if (!HasArithmeticOrEnumeralCandidateType) 8178 return; 8179 8180 for (unsigned Arith = FirstPromotedArithmeticType; 8181 Arith < LastPromotedArithmeticType; ++Arith) { 8182 QualType ArithTy = ArithmeticTypes[Arith]; 8183 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8184 } 8185 8186 // Extension: We also add these operators for vector types. 8187 for (BuiltinCandidateTypeSet::iterator 8188 Vec = CandidateTypes[0].vector_begin(), 8189 VecEnd = CandidateTypes[0].vector_end(); 8190 Vec != VecEnd; ++Vec) { 8191 QualType VecTy = *Vec; 8192 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8193 } 8194 } 8195 8196 // C++ [over.built]p8: 8197 // For every type T, there exist candidate operator functions of 8198 // the form 8199 // 8200 // T* operator+(T*); 8201 void addUnaryPlusPointerOverloads() { 8202 for (BuiltinCandidateTypeSet::iterator 8203 Ptr = CandidateTypes[0].pointer_begin(), 8204 PtrEnd = CandidateTypes[0].pointer_end(); 8205 Ptr != PtrEnd; ++Ptr) { 8206 QualType ParamTy = *Ptr; 8207 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8208 } 8209 } 8210 8211 // C++ [over.built]p10: 8212 // For every promoted integral type T, there exist candidate 8213 // operator functions of the form 8214 // 8215 // T operator~(T); 8216 void addUnaryTildePromotedIntegralOverloads() { 8217 if (!HasArithmeticOrEnumeralCandidateType) 8218 return; 8219 8220 for (unsigned Int = FirstPromotedIntegralType; 8221 Int < LastPromotedIntegralType; ++Int) { 8222 QualType IntTy = ArithmeticTypes[Int]; 8223 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8224 } 8225 8226 // Extension: We also add this operator for vector types. 8227 for (BuiltinCandidateTypeSet::iterator 8228 Vec = CandidateTypes[0].vector_begin(), 8229 VecEnd = CandidateTypes[0].vector_end(); 8230 Vec != VecEnd; ++Vec) { 8231 QualType VecTy = *Vec; 8232 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8233 } 8234 } 8235 8236 // C++ [over.match.oper]p16: 8237 // For every pointer to member type T or type std::nullptr_t, there 8238 // exist candidate operator functions of the form 8239 // 8240 // bool operator==(T,T); 8241 // bool operator!=(T,T); 8242 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8243 /// Set of (canonical) types that we've already handled. 8244 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8245 8246 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8247 for (BuiltinCandidateTypeSet::iterator 8248 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8249 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8250 MemPtr != MemPtrEnd; 8251 ++MemPtr) { 8252 // Don't add the same builtin candidate twice. 8253 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8254 continue; 8255 8256 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8257 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8258 } 8259 8260 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8261 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8262 if (AddedTypes.insert(NullPtrTy).second) { 8263 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8264 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8265 } 8266 } 8267 } 8268 } 8269 8270 // C++ [over.built]p15: 8271 // 8272 // For every T, where T is an enumeration type or a pointer type, 8273 // there exist candidate operator functions of the form 8274 // 8275 // bool operator<(T, T); 8276 // bool operator>(T, T); 8277 // bool operator<=(T, T); 8278 // bool operator>=(T, T); 8279 // bool operator==(T, T); 8280 // bool operator!=(T, T); 8281 // R operator<=>(T, T) 8282 void addGenericBinaryPointerOrEnumeralOverloads() { 8283 // C++ [over.match.oper]p3: 8284 // [...]the built-in candidates include all of the candidate operator 8285 // functions defined in 13.6 that, compared to the given operator, [...] 8286 // do not have the same parameter-type-list as any non-template non-member 8287 // candidate. 8288 // 8289 // Note that in practice, this only affects enumeration types because there 8290 // aren't any built-in candidates of record type, and a user-defined operator 8291 // must have an operand of record or enumeration type. Also, the only other 8292 // overloaded operator with enumeration arguments, operator=, 8293 // cannot be overloaded for enumeration types, so this is the only place 8294 // where we must suppress candidates like this. 8295 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8296 UserDefinedBinaryOperators; 8297 8298 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8299 if (CandidateTypes[ArgIdx].enumeration_begin() != 8300 CandidateTypes[ArgIdx].enumeration_end()) { 8301 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8302 CEnd = CandidateSet.end(); 8303 C != CEnd; ++C) { 8304 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8305 continue; 8306 8307 if (C->Function->isFunctionTemplateSpecialization()) 8308 continue; 8309 8310 // We interpret "same parameter-type-list" as applying to the 8311 // "synthesized candidate, with the order of the two parameters 8312 // reversed", not to the original function. 8313 bool Reversed = C->RewriteKind & CRK_Reversed; 8314 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8315 ->getType() 8316 .getUnqualifiedType(); 8317 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8318 ->getType() 8319 .getUnqualifiedType(); 8320 8321 // Skip if either parameter isn't of enumeral type. 8322 if (!FirstParamType->isEnumeralType() || 8323 !SecondParamType->isEnumeralType()) 8324 continue; 8325 8326 // Add this operator to the set of known user-defined operators. 8327 UserDefinedBinaryOperators.insert( 8328 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8329 S.Context.getCanonicalType(SecondParamType))); 8330 } 8331 } 8332 } 8333 8334 /// Set of (canonical) types that we've already handled. 8335 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8336 8337 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8338 for (BuiltinCandidateTypeSet::iterator 8339 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8340 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8341 Ptr != PtrEnd; ++Ptr) { 8342 // Don't add the same builtin candidate twice. 8343 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8344 continue; 8345 8346 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8347 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8348 } 8349 for (BuiltinCandidateTypeSet::iterator 8350 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8351 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8352 Enum != EnumEnd; ++Enum) { 8353 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8354 8355 // Don't add the same builtin candidate twice, or if a user defined 8356 // candidate exists. 8357 if (!AddedTypes.insert(CanonType).second || 8358 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8359 CanonType))) 8360 continue; 8361 QualType ParamTypes[2] = { *Enum, *Enum }; 8362 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8363 } 8364 } 8365 } 8366 8367 // C++ [over.built]p13: 8368 // 8369 // For every cv-qualified or cv-unqualified object type T 8370 // there exist candidate operator functions of the form 8371 // 8372 // T* operator+(T*, ptrdiff_t); 8373 // T& operator[](T*, ptrdiff_t); [BELOW] 8374 // T* operator-(T*, ptrdiff_t); 8375 // T* operator+(ptrdiff_t, T*); 8376 // T& operator[](ptrdiff_t, T*); [BELOW] 8377 // 8378 // C++ [over.built]p14: 8379 // 8380 // For every T, where T is a pointer to object type, there 8381 // exist candidate operator functions of the form 8382 // 8383 // ptrdiff_t operator-(T, T); 8384 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8385 /// Set of (canonical) types that we've already handled. 8386 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8387 8388 for (int Arg = 0; Arg < 2; ++Arg) { 8389 QualType AsymmetricParamTypes[2] = { 8390 S.Context.getPointerDiffType(), 8391 S.Context.getPointerDiffType(), 8392 }; 8393 for (BuiltinCandidateTypeSet::iterator 8394 Ptr = CandidateTypes[Arg].pointer_begin(), 8395 PtrEnd = CandidateTypes[Arg].pointer_end(); 8396 Ptr != PtrEnd; ++Ptr) { 8397 QualType PointeeTy = (*Ptr)->getPointeeType(); 8398 if (!PointeeTy->isObjectType()) 8399 continue; 8400 8401 AsymmetricParamTypes[Arg] = *Ptr; 8402 if (Arg == 0 || Op == OO_Plus) { 8403 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8404 // T* operator+(ptrdiff_t, T*); 8405 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8406 } 8407 if (Op == OO_Minus) { 8408 // ptrdiff_t operator-(T, T); 8409 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8410 continue; 8411 8412 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8413 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8414 } 8415 } 8416 } 8417 } 8418 8419 // C++ [over.built]p12: 8420 // 8421 // For every pair of promoted arithmetic types L and R, there 8422 // exist candidate operator functions of the form 8423 // 8424 // LR operator*(L, R); 8425 // LR operator/(L, R); 8426 // LR operator+(L, R); 8427 // LR operator-(L, R); 8428 // bool operator<(L, R); 8429 // bool operator>(L, R); 8430 // bool operator<=(L, R); 8431 // bool operator>=(L, R); 8432 // bool operator==(L, R); 8433 // bool operator!=(L, R); 8434 // 8435 // where LR is the result of the usual arithmetic conversions 8436 // between types L and R. 8437 // 8438 // C++ [over.built]p24: 8439 // 8440 // For every pair of promoted arithmetic types L and R, there exist 8441 // candidate operator functions of the form 8442 // 8443 // LR operator?(bool, L, R); 8444 // 8445 // where LR is the result of the usual arithmetic conversions 8446 // between types L and R. 8447 // Our candidates ignore the first parameter. 8448 void addGenericBinaryArithmeticOverloads() { 8449 if (!HasArithmeticOrEnumeralCandidateType) 8450 return; 8451 8452 for (unsigned Left = FirstPromotedArithmeticType; 8453 Left < LastPromotedArithmeticType; ++Left) { 8454 for (unsigned Right = FirstPromotedArithmeticType; 8455 Right < LastPromotedArithmeticType; ++Right) { 8456 QualType LandR[2] = { ArithmeticTypes[Left], 8457 ArithmeticTypes[Right] }; 8458 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8459 } 8460 } 8461 8462 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8463 // conditional operator for vector types. 8464 for (BuiltinCandidateTypeSet::iterator 8465 Vec1 = CandidateTypes[0].vector_begin(), 8466 Vec1End = CandidateTypes[0].vector_end(); 8467 Vec1 != Vec1End; ++Vec1) { 8468 for (BuiltinCandidateTypeSet::iterator 8469 Vec2 = CandidateTypes[1].vector_begin(), 8470 Vec2End = CandidateTypes[1].vector_end(); 8471 Vec2 != Vec2End; ++Vec2) { 8472 QualType LandR[2] = { *Vec1, *Vec2 }; 8473 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8474 } 8475 } 8476 } 8477 8478 // C++2a [over.built]p14: 8479 // 8480 // For every integral type T there exists a candidate operator function 8481 // of the form 8482 // 8483 // std::strong_ordering operator<=>(T, T) 8484 // 8485 // C++2a [over.built]p15: 8486 // 8487 // For every pair of floating-point types L and R, there exists a candidate 8488 // operator function of the form 8489 // 8490 // std::partial_ordering operator<=>(L, R); 8491 // 8492 // FIXME: The current specification for integral types doesn't play nice with 8493 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8494 // comparisons. Under the current spec this can lead to ambiguity during 8495 // overload resolution. For example: 8496 // 8497 // enum A : int {a}; 8498 // auto x = (a <=> (long)42); 8499 // 8500 // error: call is ambiguous for arguments 'A' and 'long'. 8501 // note: candidate operator<=>(int, int) 8502 // note: candidate operator<=>(long, long) 8503 // 8504 // To avoid this error, this function deviates from the specification and adds 8505 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8506 // arithmetic types (the same as the generic relational overloads). 8507 // 8508 // For now this function acts as a placeholder. 8509 void addThreeWayArithmeticOverloads() { 8510 addGenericBinaryArithmeticOverloads(); 8511 } 8512 8513 // C++ [over.built]p17: 8514 // 8515 // For every pair of promoted integral types L and R, there 8516 // exist candidate operator functions of the form 8517 // 8518 // LR operator%(L, R); 8519 // LR operator&(L, R); 8520 // LR operator^(L, R); 8521 // LR operator|(L, R); 8522 // L operator<<(L, R); 8523 // L operator>>(L, R); 8524 // 8525 // where LR is the result of the usual arithmetic conversions 8526 // between types L and R. 8527 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8528 if (!HasArithmeticOrEnumeralCandidateType) 8529 return; 8530 8531 for (unsigned Left = FirstPromotedIntegralType; 8532 Left < LastPromotedIntegralType; ++Left) { 8533 for (unsigned Right = FirstPromotedIntegralType; 8534 Right < LastPromotedIntegralType; ++Right) { 8535 QualType LandR[2] = { ArithmeticTypes[Left], 8536 ArithmeticTypes[Right] }; 8537 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8538 } 8539 } 8540 } 8541 8542 // C++ [over.built]p20: 8543 // 8544 // For every pair (T, VQ), where T is an enumeration or 8545 // pointer to member type and VQ is either volatile or 8546 // empty, there exist candidate operator functions of the form 8547 // 8548 // VQ T& operator=(VQ T&, T); 8549 void addAssignmentMemberPointerOrEnumeralOverloads() { 8550 /// Set of (canonical) types that we've already handled. 8551 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8552 8553 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8554 for (BuiltinCandidateTypeSet::iterator 8555 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8556 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8557 Enum != EnumEnd; ++Enum) { 8558 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8559 continue; 8560 8561 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8562 } 8563 8564 for (BuiltinCandidateTypeSet::iterator 8565 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8566 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8567 MemPtr != MemPtrEnd; ++MemPtr) { 8568 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8569 continue; 8570 8571 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8572 } 8573 } 8574 } 8575 8576 // C++ [over.built]p19: 8577 // 8578 // For every pair (T, VQ), where T is any type and VQ is either 8579 // volatile or empty, there exist candidate operator functions 8580 // of the form 8581 // 8582 // T*VQ& operator=(T*VQ&, T*); 8583 // 8584 // C++ [over.built]p21: 8585 // 8586 // For every pair (T, VQ), where T is a cv-qualified or 8587 // cv-unqualified object type and VQ is either volatile or 8588 // empty, there exist candidate operator functions of the form 8589 // 8590 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8591 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8592 void addAssignmentPointerOverloads(bool isEqualOp) { 8593 /// Set of (canonical) types that we've already handled. 8594 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8595 8596 for (BuiltinCandidateTypeSet::iterator 8597 Ptr = CandidateTypes[0].pointer_begin(), 8598 PtrEnd = CandidateTypes[0].pointer_end(); 8599 Ptr != PtrEnd; ++Ptr) { 8600 // If this is operator=, keep track of the builtin candidates we added. 8601 if (isEqualOp) 8602 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8603 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8604 continue; 8605 8606 // non-volatile version 8607 QualType ParamTypes[2] = { 8608 S.Context.getLValueReferenceType(*Ptr), 8609 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8610 }; 8611 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8612 /*IsAssignmentOperator=*/ isEqualOp); 8613 8614 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8615 VisibleTypeConversionsQuals.hasVolatile(); 8616 if (NeedVolatile) { 8617 // volatile version 8618 ParamTypes[0] = 8619 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8620 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8621 /*IsAssignmentOperator=*/isEqualOp); 8622 } 8623 8624 if (!(*Ptr).isRestrictQualified() && 8625 VisibleTypeConversionsQuals.hasRestrict()) { 8626 // restrict version 8627 ParamTypes[0] 8628 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8629 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8630 /*IsAssignmentOperator=*/isEqualOp); 8631 8632 if (NeedVolatile) { 8633 // volatile restrict version 8634 ParamTypes[0] 8635 = S.Context.getLValueReferenceType( 8636 S.Context.getCVRQualifiedType(*Ptr, 8637 (Qualifiers::Volatile | 8638 Qualifiers::Restrict))); 8639 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8640 /*IsAssignmentOperator=*/isEqualOp); 8641 } 8642 } 8643 } 8644 8645 if (isEqualOp) { 8646 for (BuiltinCandidateTypeSet::iterator 8647 Ptr = CandidateTypes[1].pointer_begin(), 8648 PtrEnd = CandidateTypes[1].pointer_end(); 8649 Ptr != PtrEnd; ++Ptr) { 8650 // Make sure we don't add the same candidate twice. 8651 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8652 continue; 8653 8654 QualType ParamTypes[2] = { 8655 S.Context.getLValueReferenceType(*Ptr), 8656 *Ptr, 8657 }; 8658 8659 // non-volatile version 8660 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8661 /*IsAssignmentOperator=*/true); 8662 8663 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8664 VisibleTypeConversionsQuals.hasVolatile(); 8665 if (NeedVolatile) { 8666 // volatile version 8667 ParamTypes[0] = 8668 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8669 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8670 /*IsAssignmentOperator=*/true); 8671 } 8672 8673 if (!(*Ptr).isRestrictQualified() && 8674 VisibleTypeConversionsQuals.hasRestrict()) { 8675 // restrict version 8676 ParamTypes[0] 8677 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8678 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8679 /*IsAssignmentOperator=*/true); 8680 8681 if (NeedVolatile) { 8682 // volatile restrict version 8683 ParamTypes[0] 8684 = S.Context.getLValueReferenceType( 8685 S.Context.getCVRQualifiedType(*Ptr, 8686 (Qualifiers::Volatile | 8687 Qualifiers::Restrict))); 8688 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8689 /*IsAssignmentOperator=*/true); 8690 } 8691 } 8692 } 8693 } 8694 } 8695 8696 // C++ [over.built]p18: 8697 // 8698 // For every triple (L, VQ, R), where L is an arithmetic type, 8699 // VQ is either volatile or empty, and R is a promoted 8700 // arithmetic type, there exist candidate operator functions of 8701 // the form 8702 // 8703 // VQ L& operator=(VQ L&, R); 8704 // VQ L& operator*=(VQ L&, R); 8705 // VQ L& operator/=(VQ L&, R); 8706 // VQ L& operator+=(VQ L&, R); 8707 // VQ L& operator-=(VQ L&, R); 8708 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8709 if (!HasArithmeticOrEnumeralCandidateType) 8710 return; 8711 8712 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8713 for (unsigned Right = FirstPromotedArithmeticType; 8714 Right < LastPromotedArithmeticType; ++Right) { 8715 QualType ParamTypes[2]; 8716 ParamTypes[1] = ArithmeticTypes[Right]; 8717 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8718 S, ArithmeticTypes[Left], Args[0]); 8719 // Add this built-in operator as a candidate (VQ is empty). 8720 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8721 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8722 /*IsAssignmentOperator=*/isEqualOp); 8723 8724 // Add this built-in operator as a candidate (VQ is 'volatile'). 8725 if (VisibleTypeConversionsQuals.hasVolatile()) { 8726 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8727 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8728 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8729 /*IsAssignmentOperator=*/isEqualOp); 8730 } 8731 } 8732 } 8733 8734 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8735 for (BuiltinCandidateTypeSet::iterator 8736 Vec1 = CandidateTypes[0].vector_begin(), 8737 Vec1End = CandidateTypes[0].vector_end(); 8738 Vec1 != Vec1End; ++Vec1) { 8739 for (BuiltinCandidateTypeSet::iterator 8740 Vec2 = CandidateTypes[1].vector_begin(), 8741 Vec2End = CandidateTypes[1].vector_end(); 8742 Vec2 != Vec2End; ++Vec2) { 8743 QualType ParamTypes[2]; 8744 ParamTypes[1] = *Vec2; 8745 // Add this built-in operator as a candidate (VQ is empty). 8746 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8747 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8748 /*IsAssignmentOperator=*/isEqualOp); 8749 8750 // Add this built-in operator as a candidate (VQ is 'volatile'). 8751 if (VisibleTypeConversionsQuals.hasVolatile()) { 8752 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8753 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8754 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8755 /*IsAssignmentOperator=*/isEqualOp); 8756 } 8757 } 8758 } 8759 } 8760 8761 // C++ [over.built]p22: 8762 // 8763 // For every triple (L, VQ, R), where L is an integral type, VQ 8764 // is either volatile or empty, and R is a promoted integral 8765 // type, there exist candidate operator functions of the form 8766 // 8767 // VQ L& operator%=(VQ L&, R); 8768 // VQ L& operator<<=(VQ L&, R); 8769 // VQ L& operator>>=(VQ L&, R); 8770 // VQ L& operator&=(VQ L&, R); 8771 // VQ L& operator^=(VQ L&, R); 8772 // VQ L& operator|=(VQ L&, R); 8773 void addAssignmentIntegralOverloads() { 8774 if (!HasArithmeticOrEnumeralCandidateType) 8775 return; 8776 8777 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8778 for (unsigned Right = FirstPromotedIntegralType; 8779 Right < LastPromotedIntegralType; ++Right) { 8780 QualType ParamTypes[2]; 8781 ParamTypes[1] = ArithmeticTypes[Right]; 8782 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8783 S, ArithmeticTypes[Left], Args[0]); 8784 // Add this built-in operator as a candidate (VQ is empty). 8785 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8786 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8787 if (VisibleTypeConversionsQuals.hasVolatile()) { 8788 // Add this built-in operator as a candidate (VQ is 'volatile'). 8789 ParamTypes[0] = LeftBaseTy; 8790 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8791 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8792 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8793 } 8794 } 8795 } 8796 } 8797 8798 // C++ [over.operator]p23: 8799 // 8800 // There also exist candidate operator functions of the form 8801 // 8802 // bool operator!(bool); 8803 // bool operator&&(bool, bool); 8804 // bool operator||(bool, bool); 8805 void addExclaimOverload() { 8806 QualType ParamTy = S.Context.BoolTy; 8807 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8808 /*IsAssignmentOperator=*/false, 8809 /*NumContextualBoolArguments=*/1); 8810 } 8811 void addAmpAmpOrPipePipeOverload() { 8812 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8813 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8814 /*IsAssignmentOperator=*/false, 8815 /*NumContextualBoolArguments=*/2); 8816 } 8817 8818 // C++ [over.built]p13: 8819 // 8820 // For every cv-qualified or cv-unqualified object type T there 8821 // exist candidate operator functions of the form 8822 // 8823 // T* operator+(T*, ptrdiff_t); [ABOVE] 8824 // T& operator[](T*, ptrdiff_t); 8825 // T* operator-(T*, ptrdiff_t); [ABOVE] 8826 // T* operator+(ptrdiff_t, T*); [ABOVE] 8827 // T& operator[](ptrdiff_t, T*); 8828 void addSubscriptOverloads() { 8829 for (BuiltinCandidateTypeSet::iterator 8830 Ptr = CandidateTypes[0].pointer_begin(), 8831 PtrEnd = CandidateTypes[0].pointer_end(); 8832 Ptr != PtrEnd; ++Ptr) { 8833 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8834 QualType PointeeType = (*Ptr)->getPointeeType(); 8835 if (!PointeeType->isObjectType()) 8836 continue; 8837 8838 // T& operator[](T*, ptrdiff_t) 8839 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8840 } 8841 8842 for (BuiltinCandidateTypeSet::iterator 8843 Ptr = CandidateTypes[1].pointer_begin(), 8844 PtrEnd = CandidateTypes[1].pointer_end(); 8845 Ptr != PtrEnd; ++Ptr) { 8846 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8847 QualType PointeeType = (*Ptr)->getPointeeType(); 8848 if (!PointeeType->isObjectType()) 8849 continue; 8850 8851 // T& operator[](ptrdiff_t, T*) 8852 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8853 } 8854 } 8855 8856 // C++ [over.built]p11: 8857 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8858 // C1 is the same type as C2 or is a derived class of C2, T is an object 8859 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8860 // there exist candidate operator functions of the form 8861 // 8862 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8863 // 8864 // where CV12 is the union of CV1 and CV2. 8865 void addArrowStarOverloads() { 8866 for (BuiltinCandidateTypeSet::iterator 8867 Ptr = CandidateTypes[0].pointer_begin(), 8868 PtrEnd = CandidateTypes[0].pointer_end(); 8869 Ptr != PtrEnd; ++Ptr) { 8870 QualType C1Ty = (*Ptr); 8871 QualType C1; 8872 QualifierCollector Q1; 8873 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8874 if (!isa<RecordType>(C1)) 8875 continue; 8876 // heuristic to reduce number of builtin candidates in the set. 8877 // Add volatile/restrict version only if there are conversions to a 8878 // volatile/restrict type. 8879 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8880 continue; 8881 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8882 continue; 8883 for (BuiltinCandidateTypeSet::iterator 8884 MemPtr = CandidateTypes[1].member_pointer_begin(), 8885 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8886 MemPtr != MemPtrEnd; ++MemPtr) { 8887 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8888 QualType C2 = QualType(mptr->getClass(), 0); 8889 C2 = C2.getUnqualifiedType(); 8890 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8891 break; 8892 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8893 // build CV12 T& 8894 QualType T = mptr->getPointeeType(); 8895 if (!VisibleTypeConversionsQuals.hasVolatile() && 8896 T.isVolatileQualified()) 8897 continue; 8898 if (!VisibleTypeConversionsQuals.hasRestrict() && 8899 T.isRestrictQualified()) 8900 continue; 8901 T = Q1.apply(S.Context, T); 8902 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8903 } 8904 } 8905 } 8906 8907 // Note that we don't consider the first argument, since it has been 8908 // contextually converted to bool long ago. The candidates below are 8909 // therefore added as binary. 8910 // 8911 // C++ [over.built]p25: 8912 // For every type T, where T is a pointer, pointer-to-member, or scoped 8913 // enumeration type, there exist candidate operator functions of the form 8914 // 8915 // T operator?(bool, T, T); 8916 // 8917 void addConditionalOperatorOverloads() { 8918 /// Set of (canonical) types that we've already handled. 8919 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8920 8921 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8922 for (BuiltinCandidateTypeSet::iterator 8923 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8924 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8925 Ptr != PtrEnd; ++Ptr) { 8926 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8927 continue; 8928 8929 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8930 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8931 } 8932 8933 for (BuiltinCandidateTypeSet::iterator 8934 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8935 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8936 MemPtr != MemPtrEnd; ++MemPtr) { 8937 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8938 continue; 8939 8940 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8941 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8942 } 8943 8944 if (S.getLangOpts().CPlusPlus11) { 8945 for (BuiltinCandidateTypeSet::iterator 8946 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8947 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8948 Enum != EnumEnd; ++Enum) { 8949 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 8950 continue; 8951 8952 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8953 continue; 8954 8955 QualType ParamTypes[2] = { *Enum, *Enum }; 8956 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8957 } 8958 } 8959 } 8960 } 8961 }; 8962 8963 } // end anonymous namespace 8964 8965 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8966 /// operator overloads to the candidate set (C++ [over.built]), based 8967 /// on the operator @p Op and the arguments given. For example, if the 8968 /// operator is a binary '+', this routine might add "int 8969 /// operator+(int, int)" to cover integer addition. 8970 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8971 SourceLocation OpLoc, 8972 ArrayRef<Expr *> Args, 8973 OverloadCandidateSet &CandidateSet) { 8974 // Find all of the types that the arguments can convert to, but only 8975 // if the operator we're looking at has built-in operator candidates 8976 // that make use of these types. Also record whether we encounter non-record 8977 // candidate types or either arithmetic or enumeral candidate types. 8978 Qualifiers VisibleTypeConversionsQuals; 8979 VisibleTypeConversionsQuals.addConst(); 8980 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8981 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8982 8983 bool HasNonRecordCandidateType = false; 8984 bool HasArithmeticOrEnumeralCandidateType = false; 8985 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8986 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8987 CandidateTypes.emplace_back(*this); 8988 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8989 OpLoc, 8990 true, 8991 (Op == OO_Exclaim || 8992 Op == OO_AmpAmp || 8993 Op == OO_PipePipe), 8994 VisibleTypeConversionsQuals); 8995 HasNonRecordCandidateType = HasNonRecordCandidateType || 8996 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8997 HasArithmeticOrEnumeralCandidateType = 8998 HasArithmeticOrEnumeralCandidateType || 8999 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9000 } 9001 9002 // Exit early when no non-record types have been added to the candidate set 9003 // for any of the arguments to the operator. 9004 // 9005 // We can't exit early for !, ||, or &&, since there we have always have 9006 // 'bool' overloads. 9007 if (!HasNonRecordCandidateType && 9008 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9009 return; 9010 9011 // Setup an object to manage the common state for building overloads. 9012 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9013 VisibleTypeConversionsQuals, 9014 HasArithmeticOrEnumeralCandidateType, 9015 CandidateTypes, CandidateSet); 9016 9017 // Dispatch over the operation to add in only those overloads which apply. 9018 switch (Op) { 9019 case OO_None: 9020 case NUM_OVERLOADED_OPERATORS: 9021 llvm_unreachable("Expected an overloaded operator"); 9022 9023 case OO_New: 9024 case OO_Delete: 9025 case OO_Array_New: 9026 case OO_Array_Delete: 9027 case OO_Call: 9028 llvm_unreachable( 9029 "Special operators don't use AddBuiltinOperatorCandidates"); 9030 9031 case OO_Comma: 9032 case OO_Arrow: 9033 case OO_Coawait: 9034 // C++ [over.match.oper]p3: 9035 // -- For the operator ',', the unary operator '&', the 9036 // operator '->', or the operator 'co_await', the 9037 // built-in candidates set is empty. 9038 break; 9039 9040 case OO_Plus: // '+' is either unary or binary 9041 if (Args.size() == 1) 9042 OpBuilder.addUnaryPlusPointerOverloads(); 9043 LLVM_FALLTHROUGH; 9044 9045 case OO_Minus: // '-' is either unary or binary 9046 if (Args.size() == 1) { 9047 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9048 } else { 9049 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9050 OpBuilder.addGenericBinaryArithmeticOverloads(); 9051 } 9052 break; 9053 9054 case OO_Star: // '*' is either unary or binary 9055 if (Args.size() == 1) 9056 OpBuilder.addUnaryStarPointerOverloads(); 9057 else 9058 OpBuilder.addGenericBinaryArithmeticOverloads(); 9059 break; 9060 9061 case OO_Slash: 9062 OpBuilder.addGenericBinaryArithmeticOverloads(); 9063 break; 9064 9065 case OO_PlusPlus: 9066 case OO_MinusMinus: 9067 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9068 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9069 break; 9070 9071 case OO_EqualEqual: 9072 case OO_ExclaimEqual: 9073 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9074 LLVM_FALLTHROUGH; 9075 9076 case OO_Less: 9077 case OO_Greater: 9078 case OO_LessEqual: 9079 case OO_GreaterEqual: 9080 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9081 OpBuilder.addGenericBinaryArithmeticOverloads(); 9082 break; 9083 9084 case OO_Spaceship: 9085 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9086 OpBuilder.addThreeWayArithmeticOverloads(); 9087 break; 9088 9089 case OO_Percent: 9090 case OO_Caret: 9091 case OO_Pipe: 9092 case OO_LessLess: 9093 case OO_GreaterGreater: 9094 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9095 break; 9096 9097 case OO_Amp: // '&' is either unary or binary 9098 if (Args.size() == 1) 9099 // C++ [over.match.oper]p3: 9100 // -- For the operator ',', the unary operator '&', or the 9101 // operator '->', the built-in candidates set is empty. 9102 break; 9103 9104 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9105 break; 9106 9107 case OO_Tilde: 9108 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9109 break; 9110 9111 case OO_Equal: 9112 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9113 LLVM_FALLTHROUGH; 9114 9115 case OO_PlusEqual: 9116 case OO_MinusEqual: 9117 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9118 LLVM_FALLTHROUGH; 9119 9120 case OO_StarEqual: 9121 case OO_SlashEqual: 9122 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9123 break; 9124 9125 case OO_PercentEqual: 9126 case OO_LessLessEqual: 9127 case OO_GreaterGreaterEqual: 9128 case OO_AmpEqual: 9129 case OO_CaretEqual: 9130 case OO_PipeEqual: 9131 OpBuilder.addAssignmentIntegralOverloads(); 9132 break; 9133 9134 case OO_Exclaim: 9135 OpBuilder.addExclaimOverload(); 9136 break; 9137 9138 case OO_AmpAmp: 9139 case OO_PipePipe: 9140 OpBuilder.addAmpAmpOrPipePipeOverload(); 9141 break; 9142 9143 case OO_Subscript: 9144 OpBuilder.addSubscriptOverloads(); 9145 break; 9146 9147 case OO_ArrowStar: 9148 OpBuilder.addArrowStarOverloads(); 9149 break; 9150 9151 case OO_Conditional: 9152 OpBuilder.addConditionalOperatorOverloads(); 9153 OpBuilder.addGenericBinaryArithmeticOverloads(); 9154 break; 9155 } 9156 } 9157 9158 /// Add function candidates found via argument-dependent lookup 9159 /// to the set of overloading candidates. 9160 /// 9161 /// This routine performs argument-dependent name lookup based on the 9162 /// given function name (which may also be an operator name) and adds 9163 /// all of the overload candidates found by ADL to the overload 9164 /// candidate set (C++ [basic.lookup.argdep]). 9165 void 9166 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9167 SourceLocation Loc, 9168 ArrayRef<Expr *> Args, 9169 TemplateArgumentListInfo *ExplicitTemplateArgs, 9170 OverloadCandidateSet& CandidateSet, 9171 bool PartialOverloading) { 9172 ADLResult Fns; 9173 9174 // FIXME: This approach for uniquing ADL results (and removing 9175 // redundant candidates from the set) relies on pointer-equality, 9176 // which means we need to key off the canonical decl. However, 9177 // always going back to the canonical decl might not get us the 9178 // right set of default arguments. What default arguments are 9179 // we supposed to consider on ADL candidates, anyway? 9180 9181 // FIXME: Pass in the explicit template arguments? 9182 ArgumentDependentLookup(Name, Loc, Args, Fns); 9183 9184 // Erase all of the candidates we already knew about. 9185 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9186 CandEnd = CandidateSet.end(); 9187 Cand != CandEnd; ++Cand) 9188 if (Cand->Function) { 9189 Fns.erase(Cand->Function); 9190 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9191 Fns.erase(FunTmpl); 9192 } 9193 9194 // For each of the ADL candidates we found, add it to the overload 9195 // set. 9196 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9197 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9198 9199 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9200 if (ExplicitTemplateArgs) 9201 continue; 9202 9203 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9204 /*SuppressUserConversions=*/false, PartialOverloading, 9205 /*AllowExplicit*/ true, 9206 /*AllowExplicitConversions*/ false, 9207 ADLCallKind::UsesADL); 9208 } else { 9209 AddTemplateOverloadCandidate( 9210 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9211 CandidateSet, 9212 /*SuppressUserConversions=*/false, PartialOverloading, 9213 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9214 } 9215 } 9216 } 9217 9218 namespace { 9219 enum class Comparison { Equal, Better, Worse }; 9220 } 9221 9222 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9223 /// overload resolution. 9224 /// 9225 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9226 /// Cand1's first N enable_if attributes have precisely the same conditions as 9227 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9228 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9229 /// 9230 /// Note that you can have a pair of candidates such that Cand1's enable_if 9231 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9232 /// worse than Cand1's. 9233 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9234 const FunctionDecl *Cand2) { 9235 // Common case: One (or both) decls don't have enable_if attrs. 9236 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9237 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9238 if (!Cand1Attr || !Cand2Attr) { 9239 if (Cand1Attr == Cand2Attr) 9240 return Comparison::Equal; 9241 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9242 } 9243 9244 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9245 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9246 9247 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9248 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9249 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9250 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9251 9252 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9253 // has fewer enable_if attributes than Cand2, and vice versa. 9254 if (!Cand1A) 9255 return Comparison::Worse; 9256 if (!Cand2A) 9257 return Comparison::Better; 9258 9259 Cand1ID.clear(); 9260 Cand2ID.clear(); 9261 9262 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9263 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9264 if (Cand1ID != Cand2ID) 9265 return Comparison::Worse; 9266 } 9267 9268 return Comparison::Equal; 9269 } 9270 9271 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9272 const OverloadCandidate &Cand2) { 9273 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9274 !Cand2.Function->isMultiVersion()) 9275 return false; 9276 9277 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9278 // is obviously better. 9279 if (Cand1.Function->isInvalidDecl()) return false; 9280 if (Cand2.Function->isInvalidDecl()) return true; 9281 9282 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9283 // cpu_dispatch, else arbitrarily based on the identifiers. 9284 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9285 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9286 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9287 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9288 9289 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9290 return false; 9291 9292 if (Cand1CPUDisp && !Cand2CPUDisp) 9293 return true; 9294 if (Cand2CPUDisp && !Cand1CPUDisp) 9295 return false; 9296 9297 if (Cand1CPUSpec && Cand2CPUSpec) { 9298 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9299 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9300 9301 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9302 FirstDiff = std::mismatch( 9303 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9304 Cand2CPUSpec->cpus_begin(), 9305 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9306 return LHS->getName() == RHS->getName(); 9307 }); 9308 9309 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9310 "Two different cpu-specific versions should not have the same " 9311 "identifier list, otherwise they'd be the same decl!"); 9312 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9313 } 9314 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9315 } 9316 9317 /// isBetterOverloadCandidate - Determines whether the first overload 9318 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9319 bool clang::isBetterOverloadCandidate( 9320 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9321 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9322 // Define viable functions to be better candidates than non-viable 9323 // functions. 9324 if (!Cand2.Viable) 9325 return Cand1.Viable; 9326 else if (!Cand1.Viable) 9327 return false; 9328 9329 // C++ [over.match.best]p1: 9330 // 9331 // -- if F is a static member function, ICS1(F) is defined such 9332 // that ICS1(F) is neither better nor worse than ICS1(G) for 9333 // any function G, and, symmetrically, ICS1(G) is neither 9334 // better nor worse than ICS1(F). 9335 unsigned StartArg = 0; 9336 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9337 StartArg = 1; 9338 9339 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9340 // We don't allow incompatible pointer conversions in C++. 9341 if (!S.getLangOpts().CPlusPlus) 9342 return ICS.isStandard() && 9343 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9344 9345 // The only ill-formed conversion we allow in C++ is the string literal to 9346 // char* conversion, which is only considered ill-formed after C++11. 9347 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9348 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9349 }; 9350 9351 // Define functions that don't require ill-formed conversions for a given 9352 // argument to be better candidates than functions that do. 9353 unsigned NumArgs = Cand1.Conversions.size(); 9354 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9355 bool HasBetterConversion = false; 9356 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9357 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9358 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9359 if (Cand1Bad != Cand2Bad) { 9360 if (Cand1Bad) 9361 return false; 9362 HasBetterConversion = true; 9363 } 9364 } 9365 9366 if (HasBetterConversion) 9367 return true; 9368 9369 // C++ [over.match.best]p1: 9370 // A viable function F1 is defined to be a better function than another 9371 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9372 // conversion sequence than ICSi(F2), and then... 9373 bool HasWorseConversion = false; 9374 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9375 switch (CompareImplicitConversionSequences(S, Loc, 9376 Cand1.Conversions[ArgIdx], 9377 Cand2.Conversions[ArgIdx])) { 9378 case ImplicitConversionSequence::Better: 9379 // Cand1 has a better conversion sequence. 9380 HasBetterConversion = true; 9381 break; 9382 9383 case ImplicitConversionSequence::Worse: 9384 if (Cand1.Function && Cand1.Function == Cand2.Function && 9385 (Cand2.RewriteKind & CRK_Reversed) != 0) { 9386 // Work around large-scale breakage caused by considering reversed 9387 // forms of operator== in C++20: 9388 // 9389 // When comparing a function against its reversed form, if we have a 9390 // better conversion for one argument and a worse conversion for the 9391 // other, we prefer the non-reversed form. 9392 // 9393 // This prevents a conversion function from being considered ambiguous 9394 // with its own reversed form in various where it's only incidentally 9395 // heterogeneous. 9396 // 9397 // We diagnose this as an extension from CreateOverloadedBinOp. 9398 HasWorseConversion = true; 9399 break; 9400 } 9401 9402 // Cand1 can't be better than Cand2. 9403 return false; 9404 9405 case ImplicitConversionSequence::Indistinguishable: 9406 // Do nothing. 9407 break; 9408 } 9409 } 9410 9411 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9412 // ICSj(F2), or, if not that, 9413 if (HasBetterConversion) 9414 return true; 9415 if (HasWorseConversion) 9416 return false; 9417 9418 // -- the context is an initialization by user-defined conversion 9419 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9420 // from the return type of F1 to the destination type (i.e., 9421 // the type of the entity being initialized) is a better 9422 // conversion sequence than the standard conversion sequence 9423 // from the return type of F2 to the destination type. 9424 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9425 Cand1.Function && Cand2.Function && 9426 isa<CXXConversionDecl>(Cand1.Function) && 9427 isa<CXXConversionDecl>(Cand2.Function)) { 9428 // First check whether we prefer one of the conversion functions over the 9429 // other. This only distinguishes the results in non-standard, extension 9430 // cases such as the conversion from a lambda closure type to a function 9431 // pointer or block. 9432 ImplicitConversionSequence::CompareKind Result = 9433 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9434 if (Result == ImplicitConversionSequence::Indistinguishable) 9435 Result = CompareStandardConversionSequences(S, Loc, 9436 Cand1.FinalConversion, 9437 Cand2.FinalConversion); 9438 9439 if (Result != ImplicitConversionSequence::Indistinguishable) 9440 return Result == ImplicitConversionSequence::Better; 9441 9442 // FIXME: Compare kind of reference binding if conversion functions 9443 // convert to a reference type used in direct reference binding, per 9444 // C++14 [over.match.best]p1 section 2 bullet 3. 9445 } 9446 9447 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9448 // as combined with the resolution to CWG issue 243. 9449 // 9450 // When the context is initialization by constructor ([over.match.ctor] or 9451 // either phase of [over.match.list]), a constructor is preferred over 9452 // a conversion function. 9453 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9454 Cand1.Function && Cand2.Function && 9455 isa<CXXConstructorDecl>(Cand1.Function) != 9456 isa<CXXConstructorDecl>(Cand2.Function)) 9457 return isa<CXXConstructorDecl>(Cand1.Function); 9458 9459 // -- F1 is a non-template function and F2 is a function template 9460 // specialization, or, if not that, 9461 bool Cand1IsSpecialization = Cand1.Function && 9462 Cand1.Function->getPrimaryTemplate(); 9463 bool Cand2IsSpecialization = Cand2.Function && 9464 Cand2.Function->getPrimaryTemplate(); 9465 if (Cand1IsSpecialization != Cand2IsSpecialization) 9466 return Cand2IsSpecialization; 9467 9468 // -- F1 and F2 are function template specializations, and the function 9469 // template for F1 is more specialized than the template for F2 9470 // according to the partial ordering rules described in 14.5.5.2, or, 9471 // if not that, 9472 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9473 if (FunctionTemplateDecl *BetterTemplate 9474 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9475 Cand2.Function->getPrimaryTemplate(), 9476 Loc, 9477 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9478 : TPOC_Call, 9479 Cand1.ExplicitCallArguments, 9480 Cand2.ExplicitCallArguments)) 9481 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9482 } 9483 9484 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9485 // class B of D, and for all arguments the corresponding parameters of 9486 // F1 and F2 have the same type. 9487 // FIXME: Implement the "all parameters have the same type" check. 9488 bool Cand1IsInherited = 9489 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9490 bool Cand2IsInherited = 9491 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9492 if (Cand1IsInherited != Cand2IsInherited) 9493 return Cand2IsInherited; 9494 else if (Cand1IsInherited) { 9495 assert(Cand2IsInherited); 9496 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9497 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9498 if (Cand1Class->isDerivedFrom(Cand2Class)) 9499 return true; 9500 if (Cand2Class->isDerivedFrom(Cand1Class)) 9501 return false; 9502 // Inherited from sibling base classes: still ambiguous. 9503 } 9504 9505 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9506 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9507 // with reversed order of parameters and F1 is not 9508 // 9509 // We rank reversed + different operator as worse than just reversed, but 9510 // that comparison can never happen, because we only consider reversing for 9511 // the maximally-rewritten operator (== or <=>). 9512 if (Cand1.RewriteKind != Cand2.RewriteKind) 9513 return Cand1.RewriteKind < Cand2.RewriteKind; 9514 9515 // Check C++17 tie-breakers for deduction guides. 9516 { 9517 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9518 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9519 if (Guide1 && Guide2) { 9520 // -- F1 is generated from a deduction-guide and F2 is not 9521 if (Guide1->isImplicit() != Guide2->isImplicit()) 9522 return Guide2->isImplicit(); 9523 9524 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9525 if (Guide1->isCopyDeductionCandidate()) 9526 return true; 9527 } 9528 } 9529 9530 // Check for enable_if value-based overload resolution. 9531 if (Cand1.Function && Cand2.Function) { 9532 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9533 if (Cmp != Comparison::Equal) 9534 return Cmp == Comparison::Better; 9535 } 9536 9537 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9538 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9539 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9540 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9541 } 9542 9543 bool HasPS1 = Cand1.Function != nullptr && 9544 functionHasPassObjectSizeParams(Cand1.Function); 9545 bool HasPS2 = Cand2.Function != nullptr && 9546 functionHasPassObjectSizeParams(Cand2.Function); 9547 if (HasPS1 != HasPS2 && HasPS1) 9548 return true; 9549 9550 return isBetterMultiversionCandidate(Cand1, Cand2); 9551 } 9552 9553 /// Determine whether two declarations are "equivalent" for the purposes of 9554 /// name lookup and overload resolution. This applies when the same internal/no 9555 /// linkage entity is defined by two modules (probably by textually including 9556 /// the same header). In such a case, we don't consider the declarations to 9557 /// declare the same entity, but we also don't want lookups with both 9558 /// declarations visible to be ambiguous in some cases (this happens when using 9559 /// a modularized libstdc++). 9560 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9561 const NamedDecl *B) { 9562 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9563 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9564 if (!VA || !VB) 9565 return false; 9566 9567 // The declarations must be declaring the same name as an internal linkage 9568 // entity in different modules. 9569 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9570 VB->getDeclContext()->getRedeclContext()) || 9571 getOwningModule(const_cast<ValueDecl *>(VA)) == 9572 getOwningModule(const_cast<ValueDecl *>(VB)) || 9573 VA->isExternallyVisible() || VB->isExternallyVisible()) 9574 return false; 9575 9576 // Check that the declarations appear to be equivalent. 9577 // 9578 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9579 // For constants and functions, we should check the initializer or body is 9580 // the same. For non-constant variables, we shouldn't allow it at all. 9581 if (Context.hasSameType(VA->getType(), VB->getType())) 9582 return true; 9583 9584 // Enum constants within unnamed enumerations will have different types, but 9585 // may still be similar enough to be interchangeable for our purposes. 9586 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9587 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9588 // Only handle anonymous enums. If the enumerations were named and 9589 // equivalent, they would have been merged to the same type. 9590 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9591 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9592 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9593 !Context.hasSameType(EnumA->getIntegerType(), 9594 EnumB->getIntegerType())) 9595 return false; 9596 // Allow this only if the value is the same for both enumerators. 9597 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9598 } 9599 } 9600 9601 // Nothing else is sufficiently similar. 9602 return false; 9603 } 9604 9605 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9606 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9607 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9608 9609 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9610 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9611 << !M << (M ? M->getFullModuleName() : ""); 9612 9613 for (auto *E : Equiv) { 9614 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9615 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9616 << !M << (M ? M->getFullModuleName() : ""); 9617 } 9618 } 9619 9620 /// Computes the best viable function (C++ 13.3.3) 9621 /// within an overload candidate set. 9622 /// 9623 /// \param Loc The location of the function name (or operator symbol) for 9624 /// which overload resolution occurs. 9625 /// 9626 /// \param Best If overload resolution was successful or found a deleted 9627 /// function, \p Best points to the candidate function found. 9628 /// 9629 /// \returns The result of overload resolution. 9630 OverloadingResult 9631 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9632 iterator &Best) { 9633 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9634 std::transform(begin(), end(), std::back_inserter(Candidates), 9635 [](OverloadCandidate &Cand) { return &Cand; }); 9636 9637 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9638 // are accepted by both clang and NVCC. However, during a particular 9639 // compilation mode only one call variant is viable. We need to 9640 // exclude non-viable overload candidates from consideration based 9641 // only on their host/device attributes. Specifically, if one 9642 // candidate call is WrongSide and the other is SameSide, we ignore 9643 // the WrongSide candidate. 9644 if (S.getLangOpts().CUDA) { 9645 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9646 bool ContainsSameSideCandidate = 9647 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9648 // Check viable function only. 9649 return Cand->Viable && Cand->Function && 9650 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9651 Sema::CFP_SameSide; 9652 }); 9653 if (ContainsSameSideCandidate) { 9654 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9655 // Check viable function only to avoid unnecessary data copying/moving. 9656 return Cand->Viable && Cand->Function && 9657 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9658 Sema::CFP_WrongSide; 9659 }; 9660 llvm::erase_if(Candidates, IsWrongSideCandidate); 9661 } 9662 } 9663 9664 // Find the best viable function. 9665 Best = end(); 9666 for (auto *Cand : Candidates) { 9667 Cand->Best = false; 9668 if (Cand->Viable) 9669 if (Best == end() || 9670 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9671 Best = Cand; 9672 } 9673 9674 // If we didn't find any viable functions, abort. 9675 if (Best == end()) 9676 return OR_No_Viable_Function; 9677 9678 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9679 9680 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9681 PendingBest.push_back(&*Best); 9682 Best->Best = true; 9683 9684 // Make sure that this function is better than every other viable 9685 // function. If not, we have an ambiguity. 9686 while (!PendingBest.empty()) { 9687 auto *Curr = PendingBest.pop_back_val(); 9688 for (auto *Cand : Candidates) { 9689 if (Cand->Viable && !Cand->Best && 9690 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9691 PendingBest.push_back(Cand); 9692 Cand->Best = true; 9693 9694 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9695 Curr->Function)) 9696 EquivalentCands.push_back(Cand->Function); 9697 else 9698 Best = end(); 9699 } 9700 } 9701 } 9702 9703 // If we found more than one best candidate, this is ambiguous. 9704 if (Best == end()) 9705 return OR_Ambiguous; 9706 9707 // Best is the best viable function. 9708 if (Best->Function && Best->Function->isDeleted()) 9709 return OR_Deleted; 9710 9711 if (!EquivalentCands.empty()) 9712 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9713 EquivalentCands); 9714 9715 return OR_Success; 9716 } 9717 9718 namespace { 9719 9720 enum OverloadCandidateKind { 9721 oc_function, 9722 oc_method, 9723 oc_reversed_binary_operator, 9724 oc_constructor, 9725 oc_implicit_default_constructor, 9726 oc_implicit_copy_constructor, 9727 oc_implicit_move_constructor, 9728 oc_implicit_copy_assignment, 9729 oc_implicit_move_assignment, 9730 oc_implicit_equality_comparison, 9731 oc_inherited_constructor 9732 }; 9733 9734 enum OverloadCandidateSelect { 9735 ocs_non_template, 9736 ocs_template, 9737 ocs_described_template, 9738 }; 9739 9740 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9741 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9742 OverloadCandidateRewriteKind CRK, 9743 std::string &Description) { 9744 9745 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9746 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9747 isTemplate = true; 9748 Description = S.getTemplateArgumentBindingsText( 9749 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9750 } 9751 9752 OverloadCandidateSelect Select = [&]() { 9753 if (!Description.empty()) 9754 return ocs_described_template; 9755 return isTemplate ? ocs_template : ocs_non_template; 9756 }(); 9757 9758 OverloadCandidateKind Kind = [&]() { 9759 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9760 return oc_implicit_equality_comparison; 9761 9762 if (CRK & CRK_Reversed) 9763 return oc_reversed_binary_operator; 9764 9765 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9766 if (!Ctor->isImplicit()) { 9767 if (isa<ConstructorUsingShadowDecl>(Found)) 9768 return oc_inherited_constructor; 9769 else 9770 return oc_constructor; 9771 } 9772 9773 if (Ctor->isDefaultConstructor()) 9774 return oc_implicit_default_constructor; 9775 9776 if (Ctor->isMoveConstructor()) 9777 return oc_implicit_move_constructor; 9778 9779 assert(Ctor->isCopyConstructor() && 9780 "unexpected sort of implicit constructor"); 9781 return oc_implicit_copy_constructor; 9782 } 9783 9784 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9785 // This actually gets spelled 'candidate function' for now, but 9786 // it doesn't hurt to split it out. 9787 if (!Meth->isImplicit()) 9788 return oc_method; 9789 9790 if (Meth->isMoveAssignmentOperator()) 9791 return oc_implicit_move_assignment; 9792 9793 if (Meth->isCopyAssignmentOperator()) 9794 return oc_implicit_copy_assignment; 9795 9796 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9797 return oc_method; 9798 } 9799 9800 return oc_function; 9801 }(); 9802 9803 return std::make_pair(Kind, Select); 9804 } 9805 9806 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9807 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9808 // set. 9809 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9810 S.Diag(FoundDecl->getLocation(), 9811 diag::note_ovl_candidate_inherited_constructor) 9812 << Shadow->getNominatedBaseClass(); 9813 } 9814 9815 } // end anonymous namespace 9816 9817 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9818 const FunctionDecl *FD) { 9819 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9820 bool AlwaysTrue; 9821 if (EnableIf->getCond()->isValueDependent() || 9822 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9823 return false; 9824 if (!AlwaysTrue) 9825 return false; 9826 } 9827 return true; 9828 } 9829 9830 /// Returns true if we can take the address of the function. 9831 /// 9832 /// \param Complain - If true, we'll emit a diagnostic 9833 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9834 /// we in overload resolution? 9835 /// \param Loc - The location of the statement we're complaining about. Ignored 9836 /// if we're not complaining, or if we're in overload resolution. 9837 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9838 bool Complain, 9839 bool InOverloadResolution, 9840 SourceLocation Loc) { 9841 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9842 if (Complain) { 9843 if (InOverloadResolution) 9844 S.Diag(FD->getBeginLoc(), 9845 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9846 else 9847 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9848 } 9849 return false; 9850 } 9851 9852 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9853 return P->hasAttr<PassObjectSizeAttr>(); 9854 }); 9855 if (I == FD->param_end()) 9856 return true; 9857 9858 if (Complain) { 9859 // Add one to ParamNo because it's user-facing 9860 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9861 if (InOverloadResolution) 9862 S.Diag(FD->getLocation(), 9863 diag::note_ovl_candidate_has_pass_object_size_params) 9864 << ParamNo; 9865 else 9866 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9867 << FD << ParamNo; 9868 } 9869 return false; 9870 } 9871 9872 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9873 const FunctionDecl *FD) { 9874 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9875 /*InOverloadResolution=*/true, 9876 /*Loc=*/SourceLocation()); 9877 } 9878 9879 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9880 bool Complain, 9881 SourceLocation Loc) { 9882 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9883 /*InOverloadResolution=*/false, 9884 Loc); 9885 } 9886 9887 // Notes the location of an overload candidate. 9888 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9889 OverloadCandidateRewriteKind RewriteKind, 9890 QualType DestType, bool TakingAddress) { 9891 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9892 return; 9893 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9894 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9895 return; 9896 9897 std::string FnDesc; 9898 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9899 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 9900 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9901 << (unsigned)KSPair.first << (unsigned)KSPair.second 9902 << Fn << FnDesc; 9903 9904 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9905 Diag(Fn->getLocation(), PD); 9906 MaybeEmitInheritedConstructorNote(*this, Found); 9907 } 9908 9909 // Notes the location of all overload candidates designated through 9910 // OverloadedExpr 9911 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9912 bool TakingAddress) { 9913 assert(OverloadedExpr->getType() == Context.OverloadTy); 9914 9915 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9916 OverloadExpr *OvlExpr = Ovl.Expression; 9917 9918 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9919 IEnd = OvlExpr->decls_end(); 9920 I != IEnd; ++I) { 9921 if (FunctionTemplateDecl *FunTmpl = 9922 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9923 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 9924 TakingAddress); 9925 } else if (FunctionDecl *Fun 9926 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9927 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 9928 } 9929 } 9930 } 9931 9932 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9933 /// "lead" diagnostic; it will be given two arguments, the source and 9934 /// target types of the conversion. 9935 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9936 Sema &S, 9937 SourceLocation CaretLoc, 9938 const PartialDiagnostic &PDiag) const { 9939 S.Diag(CaretLoc, PDiag) 9940 << Ambiguous.getFromType() << Ambiguous.getToType(); 9941 // FIXME: The note limiting machinery is borrowed from 9942 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9943 // refactoring here. 9944 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9945 unsigned CandsShown = 0; 9946 AmbiguousConversionSequence::const_iterator I, E; 9947 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9948 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9949 break; 9950 ++CandsShown; 9951 S.NoteOverloadCandidate(I->first, I->second); 9952 } 9953 if (I != E) 9954 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9955 } 9956 9957 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9958 unsigned I, bool TakingCandidateAddress) { 9959 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9960 assert(Conv.isBad()); 9961 assert(Cand->Function && "for now, candidate must be a function"); 9962 FunctionDecl *Fn = Cand->Function; 9963 9964 // There's a conversion slot for the object argument if this is a 9965 // non-constructor method. Note that 'I' corresponds the 9966 // conversion-slot index. 9967 bool isObjectArgument = false; 9968 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9969 if (I == 0) 9970 isObjectArgument = true; 9971 else 9972 I--; 9973 } 9974 9975 std::string FnDesc; 9976 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9977 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 9978 FnDesc); 9979 9980 Expr *FromExpr = Conv.Bad.FromExpr; 9981 QualType FromTy = Conv.Bad.getFromType(); 9982 QualType ToTy = Conv.Bad.getToType(); 9983 9984 if (FromTy == S.Context.OverloadTy) { 9985 assert(FromExpr && "overload set argument came from implicit argument?"); 9986 Expr *E = FromExpr->IgnoreParens(); 9987 if (isa<UnaryOperator>(E)) 9988 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9989 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9990 9991 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9992 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9993 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9994 << Name << I + 1; 9995 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9996 return; 9997 } 9998 9999 // Do some hand-waving analysis to see if the non-viability is due 10000 // to a qualifier mismatch. 10001 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10002 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10003 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10004 CToTy = RT->getPointeeType(); 10005 else { 10006 // TODO: detect and diagnose the full richness of const mismatches. 10007 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10008 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10009 CFromTy = FromPT->getPointeeType(); 10010 CToTy = ToPT->getPointeeType(); 10011 } 10012 } 10013 10014 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10015 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10016 Qualifiers FromQs = CFromTy.getQualifiers(); 10017 Qualifiers ToQs = CToTy.getQualifiers(); 10018 10019 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10020 if (isObjectArgument) 10021 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10022 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10023 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10024 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10025 else 10026 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10027 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10028 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10029 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10030 << ToTy->isReferenceType() << I + 1; 10031 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10032 return; 10033 } 10034 10035 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10036 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10037 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10038 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10039 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10040 << (unsigned)isObjectArgument << I + 1; 10041 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10042 return; 10043 } 10044 10045 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10046 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10047 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10048 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10049 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10050 << (unsigned)isObjectArgument << I + 1; 10051 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10052 return; 10053 } 10054 10055 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10056 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10057 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10058 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10059 << FromQs.hasUnaligned() << I + 1; 10060 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10061 return; 10062 } 10063 10064 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10065 assert(CVR && "unexpected qualifiers mismatch"); 10066 10067 if (isObjectArgument) { 10068 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10069 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10070 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10071 << (CVR - 1); 10072 } else { 10073 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10074 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10075 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10076 << (CVR - 1) << I + 1; 10077 } 10078 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10079 return; 10080 } 10081 10082 // Special diagnostic for failure to convert an initializer list, since 10083 // telling the user that it has type void is not useful. 10084 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10085 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10086 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10087 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10088 << ToTy << (unsigned)isObjectArgument << I + 1; 10089 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10090 return; 10091 } 10092 10093 // Diagnose references or pointers to incomplete types differently, 10094 // since it's far from impossible that the incompleteness triggered 10095 // the failure. 10096 QualType TempFromTy = FromTy.getNonReferenceType(); 10097 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10098 TempFromTy = PTy->getPointeeType(); 10099 if (TempFromTy->isIncompleteType()) { 10100 // Emit the generic diagnostic and, optionally, add the hints to it. 10101 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10102 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10103 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10104 << ToTy << (unsigned)isObjectArgument << I + 1 10105 << (unsigned)(Cand->Fix.Kind); 10106 10107 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10108 return; 10109 } 10110 10111 // Diagnose base -> derived pointer conversions. 10112 unsigned BaseToDerivedConversion = 0; 10113 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10114 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10115 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10116 FromPtrTy->getPointeeType()) && 10117 !FromPtrTy->getPointeeType()->isIncompleteType() && 10118 !ToPtrTy->getPointeeType()->isIncompleteType() && 10119 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10120 FromPtrTy->getPointeeType())) 10121 BaseToDerivedConversion = 1; 10122 } 10123 } else if (const ObjCObjectPointerType *FromPtrTy 10124 = FromTy->getAs<ObjCObjectPointerType>()) { 10125 if (const ObjCObjectPointerType *ToPtrTy 10126 = ToTy->getAs<ObjCObjectPointerType>()) 10127 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10128 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10129 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10130 FromPtrTy->getPointeeType()) && 10131 FromIface->isSuperClassOf(ToIface)) 10132 BaseToDerivedConversion = 2; 10133 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10134 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10135 !FromTy->isIncompleteType() && 10136 !ToRefTy->getPointeeType()->isIncompleteType() && 10137 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10138 BaseToDerivedConversion = 3; 10139 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10140 ToTy.getNonReferenceType().getCanonicalType() == 10141 FromTy.getNonReferenceType().getCanonicalType()) { 10142 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10143 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10144 << (unsigned)isObjectArgument << I + 1 10145 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10146 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10147 return; 10148 } 10149 } 10150 10151 if (BaseToDerivedConversion) { 10152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10153 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10155 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10156 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10157 return; 10158 } 10159 10160 if (isa<ObjCObjectPointerType>(CFromTy) && 10161 isa<PointerType>(CToTy)) { 10162 Qualifiers FromQs = CFromTy.getQualifiers(); 10163 Qualifiers ToQs = CToTy.getQualifiers(); 10164 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10165 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10166 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10167 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10168 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10169 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10170 return; 10171 } 10172 } 10173 10174 if (TakingCandidateAddress && 10175 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10176 return; 10177 10178 // Emit the generic diagnostic and, optionally, add the hints to it. 10179 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10180 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10181 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10182 << ToTy << (unsigned)isObjectArgument << I + 1 10183 << (unsigned)(Cand->Fix.Kind); 10184 10185 // If we can fix the conversion, suggest the FixIts. 10186 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10187 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10188 FDiag << *HI; 10189 S.Diag(Fn->getLocation(), FDiag); 10190 10191 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10192 } 10193 10194 /// Additional arity mismatch diagnosis specific to a function overload 10195 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10196 /// over a candidate in any candidate set. 10197 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10198 unsigned NumArgs) { 10199 FunctionDecl *Fn = Cand->Function; 10200 unsigned MinParams = Fn->getMinRequiredArguments(); 10201 10202 // With invalid overloaded operators, it's possible that we think we 10203 // have an arity mismatch when in fact it looks like we have the 10204 // right number of arguments, because only overloaded operators have 10205 // the weird behavior of overloading member and non-member functions. 10206 // Just don't report anything. 10207 if (Fn->isInvalidDecl() && 10208 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10209 return true; 10210 10211 if (NumArgs < MinParams) { 10212 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10213 (Cand->FailureKind == ovl_fail_bad_deduction && 10214 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10215 } else { 10216 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10217 (Cand->FailureKind == ovl_fail_bad_deduction && 10218 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10219 } 10220 10221 return false; 10222 } 10223 10224 /// General arity mismatch diagnosis over a candidate in a candidate set. 10225 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10226 unsigned NumFormalArgs) { 10227 assert(isa<FunctionDecl>(D) && 10228 "The templated declaration should at least be a function" 10229 " when diagnosing bad template argument deduction due to too many" 10230 " or too few arguments"); 10231 10232 FunctionDecl *Fn = cast<FunctionDecl>(D); 10233 10234 // TODO: treat calls to a missing default constructor as a special case 10235 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 10236 unsigned MinParams = Fn->getMinRequiredArguments(); 10237 10238 // at least / at most / exactly 10239 unsigned mode, modeCount; 10240 if (NumFormalArgs < MinParams) { 10241 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10242 FnTy->isTemplateVariadic()) 10243 mode = 0; // "at least" 10244 else 10245 mode = 2; // "exactly" 10246 modeCount = MinParams; 10247 } else { 10248 if (MinParams != FnTy->getNumParams()) 10249 mode = 1; // "at most" 10250 else 10251 mode = 2; // "exactly" 10252 modeCount = FnTy->getNumParams(); 10253 } 10254 10255 std::string Description; 10256 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10257 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10258 10259 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10261 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10262 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10263 else 10264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10265 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10266 << Description << mode << modeCount << NumFormalArgs; 10267 10268 MaybeEmitInheritedConstructorNote(S, Found); 10269 } 10270 10271 /// Arity mismatch diagnosis specific to a function overload candidate. 10272 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10273 unsigned NumFormalArgs) { 10274 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10275 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10276 } 10277 10278 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10279 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10280 return TD; 10281 llvm_unreachable("Unsupported: Getting the described template declaration" 10282 " for bad deduction diagnosis"); 10283 } 10284 10285 /// Diagnose a failed template-argument deduction. 10286 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10287 DeductionFailureInfo &DeductionFailure, 10288 unsigned NumArgs, 10289 bool TakingCandidateAddress) { 10290 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10291 NamedDecl *ParamD; 10292 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10293 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10294 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10295 switch (DeductionFailure.Result) { 10296 case Sema::TDK_Success: 10297 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10298 10299 case Sema::TDK_Incomplete: { 10300 assert(ParamD && "no parameter found for incomplete deduction result"); 10301 S.Diag(Templated->getLocation(), 10302 diag::note_ovl_candidate_incomplete_deduction) 10303 << ParamD->getDeclName(); 10304 MaybeEmitInheritedConstructorNote(S, Found); 10305 return; 10306 } 10307 10308 case Sema::TDK_IncompletePack: { 10309 assert(ParamD && "no parameter found for incomplete deduction result"); 10310 S.Diag(Templated->getLocation(), 10311 diag::note_ovl_candidate_incomplete_deduction_pack) 10312 << ParamD->getDeclName() 10313 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10314 << *DeductionFailure.getFirstArg(); 10315 MaybeEmitInheritedConstructorNote(S, Found); 10316 return; 10317 } 10318 10319 case Sema::TDK_Underqualified: { 10320 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10321 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10322 10323 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10324 10325 // Param will have been canonicalized, but it should just be a 10326 // qualified version of ParamD, so move the qualifiers to that. 10327 QualifierCollector Qs; 10328 Qs.strip(Param); 10329 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10330 assert(S.Context.hasSameType(Param, NonCanonParam)); 10331 10332 // Arg has also been canonicalized, but there's nothing we can do 10333 // about that. It also doesn't matter as much, because it won't 10334 // have any template parameters in it (because deduction isn't 10335 // done on dependent types). 10336 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10337 10338 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10339 << ParamD->getDeclName() << Arg << NonCanonParam; 10340 MaybeEmitInheritedConstructorNote(S, Found); 10341 return; 10342 } 10343 10344 case Sema::TDK_Inconsistent: { 10345 assert(ParamD && "no parameter found for inconsistent deduction result"); 10346 int which = 0; 10347 if (isa<TemplateTypeParmDecl>(ParamD)) 10348 which = 0; 10349 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10350 // Deduction might have failed because we deduced arguments of two 10351 // different types for a non-type template parameter. 10352 // FIXME: Use a different TDK value for this. 10353 QualType T1 = 10354 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10355 QualType T2 = 10356 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10357 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10358 S.Diag(Templated->getLocation(), 10359 diag::note_ovl_candidate_inconsistent_deduction_types) 10360 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10361 << *DeductionFailure.getSecondArg() << T2; 10362 MaybeEmitInheritedConstructorNote(S, Found); 10363 return; 10364 } 10365 10366 which = 1; 10367 } else { 10368 which = 2; 10369 } 10370 10371 S.Diag(Templated->getLocation(), 10372 diag::note_ovl_candidate_inconsistent_deduction) 10373 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10374 << *DeductionFailure.getSecondArg(); 10375 MaybeEmitInheritedConstructorNote(S, Found); 10376 return; 10377 } 10378 10379 case Sema::TDK_InvalidExplicitArguments: 10380 assert(ParamD && "no parameter found for invalid explicit arguments"); 10381 if (ParamD->getDeclName()) 10382 S.Diag(Templated->getLocation(), 10383 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10384 << ParamD->getDeclName(); 10385 else { 10386 int index = 0; 10387 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10388 index = TTP->getIndex(); 10389 else if (NonTypeTemplateParmDecl *NTTP 10390 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10391 index = NTTP->getIndex(); 10392 else 10393 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10394 S.Diag(Templated->getLocation(), 10395 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10396 << (index + 1); 10397 } 10398 MaybeEmitInheritedConstructorNote(S, Found); 10399 return; 10400 10401 case Sema::TDK_ConstraintsNotSatisfied: { 10402 // Format the template argument list into the argument string. 10403 SmallString<128> TemplateArgString; 10404 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10405 TemplateArgString = " "; 10406 TemplateArgString += S.getTemplateArgumentBindingsText( 10407 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10408 S.Diag(Templated->getLocation(), 10409 diag::note_ovl_candidate_unsatisfied_constraints) 10410 << TemplateArgString; 10411 10412 S.DiagnoseUnsatisfiedConstraint( 10413 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10414 return; 10415 } 10416 case Sema::TDK_TooManyArguments: 10417 case Sema::TDK_TooFewArguments: 10418 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10419 return; 10420 10421 case Sema::TDK_InstantiationDepth: 10422 S.Diag(Templated->getLocation(), 10423 diag::note_ovl_candidate_instantiation_depth); 10424 MaybeEmitInheritedConstructorNote(S, Found); 10425 return; 10426 10427 case Sema::TDK_SubstitutionFailure: { 10428 // Format the template argument list into the argument string. 10429 SmallString<128> TemplateArgString; 10430 if (TemplateArgumentList *Args = 10431 DeductionFailure.getTemplateArgumentList()) { 10432 TemplateArgString = " "; 10433 TemplateArgString += S.getTemplateArgumentBindingsText( 10434 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10435 } 10436 10437 // If this candidate was disabled by enable_if, say so. 10438 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10439 if (PDiag && PDiag->second.getDiagID() == 10440 diag::err_typename_nested_not_found_enable_if) { 10441 // FIXME: Use the source range of the condition, and the fully-qualified 10442 // name of the enable_if template. These are both present in PDiag. 10443 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10444 << "'enable_if'" << TemplateArgString; 10445 return; 10446 } 10447 10448 // We found a specific requirement that disabled the enable_if. 10449 if (PDiag && PDiag->second.getDiagID() == 10450 diag::err_typename_nested_not_found_requirement) { 10451 S.Diag(Templated->getLocation(), 10452 diag::note_ovl_candidate_disabled_by_requirement) 10453 << PDiag->second.getStringArg(0) << TemplateArgString; 10454 return; 10455 } 10456 10457 // Format the SFINAE diagnostic into the argument string. 10458 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10459 // formatted message in another diagnostic. 10460 SmallString<128> SFINAEArgString; 10461 SourceRange R; 10462 if (PDiag) { 10463 SFINAEArgString = ": "; 10464 R = SourceRange(PDiag->first, PDiag->first); 10465 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10466 } 10467 10468 S.Diag(Templated->getLocation(), 10469 diag::note_ovl_candidate_substitution_failure) 10470 << TemplateArgString << SFINAEArgString << R; 10471 MaybeEmitInheritedConstructorNote(S, Found); 10472 return; 10473 } 10474 10475 case Sema::TDK_DeducedMismatch: 10476 case Sema::TDK_DeducedMismatchNested: { 10477 // Format the template argument list into the argument string. 10478 SmallString<128> TemplateArgString; 10479 if (TemplateArgumentList *Args = 10480 DeductionFailure.getTemplateArgumentList()) { 10481 TemplateArgString = " "; 10482 TemplateArgString += S.getTemplateArgumentBindingsText( 10483 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10484 } 10485 10486 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10487 << (*DeductionFailure.getCallArgIndex() + 1) 10488 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10489 << TemplateArgString 10490 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10491 break; 10492 } 10493 10494 case Sema::TDK_NonDeducedMismatch: { 10495 // FIXME: Provide a source location to indicate what we couldn't match. 10496 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10497 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10498 if (FirstTA.getKind() == TemplateArgument::Template && 10499 SecondTA.getKind() == TemplateArgument::Template) { 10500 TemplateName FirstTN = FirstTA.getAsTemplate(); 10501 TemplateName SecondTN = SecondTA.getAsTemplate(); 10502 if (FirstTN.getKind() == TemplateName::Template && 10503 SecondTN.getKind() == TemplateName::Template) { 10504 if (FirstTN.getAsTemplateDecl()->getName() == 10505 SecondTN.getAsTemplateDecl()->getName()) { 10506 // FIXME: This fixes a bad diagnostic where both templates are named 10507 // the same. This particular case is a bit difficult since: 10508 // 1) It is passed as a string to the diagnostic printer. 10509 // 2) The diagnostic printer only attempts to find a better 10510 // name for types, not decls. 10511 // Ideally, this should folded into the diagnostic printer. 10512 S.Diag(Templated->getLocation(), 10513 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10514 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10515 return; 10516 } 10517 } 10518 } 10519 10520 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10521 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10522 return; 10523 10524 // FIXME: For generic lambda parameters, check if the function is a lambda 10525 // call operator, and if so, emit a prettier and more informative 10526 // diagnostic that mentions 'auto' and lambda in addition to 10527 // (or instead of?) the canonical template type parameters. 10528 S.Diag(Templated->getLocation(), 10529 diag::note_ovl_candidate_non_deduced_mismatch) 10530 << FirstTA << SecondTA; 10531 return; 10532 } 10533 // TODO: diagnose these individually, then kill off 10534 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10535 case Sema::TDK_MiscellaneousDeductionFailure: 10536 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10537 MaybeEmitInheritedConstructorNote(S, Found); 10538 return; 10539 case Sema::TDK_CUDATargetMismatch: 10540 S.Diag(Templated->getLocation(), 10541 diag::note_cuda_ovl_candidate_target_mismatch); 10542 return; 10543 } 10544 } 10545 10546 /// Diagnose a failed template-argument deduction, for function calls. 10547 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10548 unsigned NumArgs, 10549 bool TakingCandidateAddress) { 10550 unsigned TDK = Cand->DeductionFailure.Result; 10551 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10552 if (CheckArityMismatch(S, Cand, NumArgs)) 10553 return; 10554 } 10555 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10556 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10557 } 10558 10559 /// CUDA: diagnose an invalid call across targets. 10560 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10561 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10562 FunctionDecl *Callee = Cand->Function; 10563 10564 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10565 CalleeTarget = S.IdentifyCUDATarget(Callee); 10566 10567 std::string FnDesc; 10568 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10569 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10570 Cand->getRewriteKind(), FnDesc); 10571 10572 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10573 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10574 << FnDesc /* Ignored */ 10575 << CalleeTarget << CallerTarget; 10576 10577 // This could be an implicit constructor for which we could not infer the 10578 // target due to a collsion. Diagnose that case. 10579 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10580 if (Meth != nullptr && Meth->isImplicit()) { 10581 CXXRecordDecl *ParentClass = Meth->getParent(); 10582 Sema::CXXSpecialMember CSM; 10583 10584 switch (FnKindPair.first) { 10585 default: 10586 return; 10587 case oc_implicit_default_constructor: 10588 CSM = Sema::CXXDefaultConstructor; 10589 break; 10590 case oc_implicit_copy_constructor: 10591 CSM = Sema::CXXCopyConstructor; 10592 break; 10593 case oc_implicit_move_constructor: 10594 CSM = Sema::CXXMoveConstructor; 10595 break; 10596 case oc_implicit_copy_assignment: 10597 CSM = Sema::CXXCopyAssignment; 10598 break; 10599 case oc_implicit_move_assignment: 10600 CSM = Sema::CXXMoveAssignment; 10601 break; 10602 }; 10603 10604 bool ConstRHS = false; 10605 if (Meth->getNumParams()) { 10606 if (const ReferenceType *RT = 10607 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10608 ConstRHS = RT->getPointeeType().isConstQualified(); 10609 } 10610 } 10611 10612 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10613 /* ConstRHS */ ConstRHS, 10614 /* Diagnose */ true); 10615 } 10616 } 10617 10618 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10619 FunctionDecl *Callee = Cand->Function; 10620 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10621 10622 S.Diag(Callee->getLocation(), 10623 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10624 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10625 } 10626 10627 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10628 ExplicitSpecifier ES; 10629 const char *DeclName; 10630 switch (Cand->Function->getDeclKind()) { 10631 case Decl::Kind::CXXConstructor: 10632 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); 10633 DeclName = "constructor"; 10634 break; 10635 case Decl::Kind::CXXConversion: 10636 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); 10637 DeclName = "conversion operator"; 10638 break; 10639 case Decl::Kind::CXXDeductionGuide: 10640 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); 10641 DeclName = "deductiong guide"; 10642 break; 10643 default: 10644 llvm_unreachable("invalid Decl"); 10645 } 10646 assert(ES.getExpr() && "null expression should be handled before"); 10647 S.Diag(Cand->Function->getLocation(), 10648 diag::note_ovl_candidate_explicit_forbidden) 10649 << DeclName; 10650 S.Diag(ES.getExpr()->getBeginLoc(), 10651 diag::note_explicit_bool_resolved_to_true); 10652 } 10653 10654 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10655 FunctionDecl *Callee = Cand->Function; 10656 10657 S.Diag(Callee->getLocation(), 10658 diag::note_ovl_candidate_disabled_by_extension) 10659 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10660 } 10661 10662 /// Generates a 'note' diagnostic for an overload candidate. We've 10663 /// already generated a primary error at the call site. 10664 /// 10665 /// It really does need to be a single diagnostic with its caret 10666 /// pointed at the candidate declaration. Yes, this creates some 10667 /// major challenges of technical writing. Yes, this makes pointing 10668 /// out problems with specific arguments quite awkward. It's still 10669 /// better than generating twenty screens of text for every failed 10670 /// overload. 10671 /// 10672 /// It would be great to be able to express per-candidate problems 10673 /// more richly for those diagnostic clients that cared, but we'd 10674 /// still have to be just as careful with the default diagnostics. 10675 /// \param CtorDestAS Addr space of object being constructed (for ctor 10676 /// candidates only). 10677 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10678 unsigned NumArgs, 10679 bool TakingCandidateAddress, 10680 LangAS CtorDestAS = LangAS::Default) { 10681 FunctionDecl *Fn = Cand->Function; 10682 10683 // Note deleted candidates, but only if they're viable. 10684 if (Cand->Viable) { 10685 if (Fn->isDeleted()) { 10686 std::string FnDesc; 10687 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10688 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10689 Cand->getRewriteKind(), FnDesc); 10690 10691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10692 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10693 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10694 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10695 return; 10696 } 10697 10698 // We don't really have anything else to say about viable candidates. 10699 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10700 return; 10701 } 10702 10703 switch (Cand->FailureKind) { 10704 case ovl_fail_too_many_arguments: 10705 case ovl_fail_too_few_arguments: 10706 return DiagnoseArityMismatch(S, Cand, NumArgs); 10707 10708 case ovl_fail_bad_deduction: 10709 return DiagnoseBadDeduction(S, Cand, NumArgs, 10710 TakingCandidateAddress); 10711 10712 case ovl_fail_illegal_constructor: { 10713 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10714 << (Fn->getPrimaryTemplate() ? 1 : 0); 10715 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10716 return; 10717 } 10718 10719 case ovl_fail_object_addrspace_mismatch: { 10720 Qualifiers QualsForPrinting; 10721 QualsForPrinting.setAddressSpace(CtorDestAS); 10722 S.Diag(Fn->getLocation(), 10723 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10724 << QualsForPrinting; 10725 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10726 return; 10727 } 10728 10729 case ovl_fail_trivial_conversion: 10730 case ovl_fail_bad_final_conversion: 10731 case ovl_fail_final_conversion_not_exact: 10732 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10733 10734 case ovl_fail_bad_conversion: { 10735 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10736 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10737 if (Cand->Conversions[I].isBad()) 10738 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10739 10740 // FIXME: this currently happens when we're called from SemaInit 10741 // when user-conversion overload fails. Figure out how to handle 10742 // those conditions and diagnose them well. 10743 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10744 } 10745 10746 case ovl_fail_bad_target: 10747 return DiagnoseBadTarget(S, Cand); 10748 10749 case ovl_fail_enable_if: 10750 return DiagnoseFailedEnableIfAttr(S, Cand); 10751 10752 case ovl_fail_explicit_resolved: 10753 return DiagnoseFailedExplicitSpec(S, Cand); 10754 10755 case ovl_fail_ext_disabled: 10756 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10757 10758 case ovl_fail_inhctor_slice: 10759 // It's generally not interesting to note copy/move constructors here. 10760 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10761 return; 10762 S.Diag(Fn->getLocation(), 10763 diag::note_ovl_candidate_inherited_constructor_slice) 10764 << (Fn->getPrimaryTemplate() ? 1 : 0) 10765 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10766 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10767 return; 10768 10769 case ovl_fail_addr_not_available: { 10770 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10771 (void)Available; 10772 assert(!Available); 10773 break; 10774 } 10775 case ovl_non_default_multiversion_function: 10776 // Do nothing, these should simply be ignored. 10777 break; 10778 } 10779 } 10780 10781 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10782 // Desugar the type of the surrogate down to a function type, 10783 // retaining as many typedefs as possible while still showing 10784 // the function type (and, therefore, its parameter types). 10785 QualType FnType = Cand->Surrogate->getConversionType(); 10786 bool isLValueReference = false; 10787 bool isRValueReference = false; 10788 bool isPointer = false; 10789 if (const LValueReferenceType *FnTypeRef = 10790 FnType->getAs<LValueReferenceType>()) { 10791 FnType = FnTypeRef->getPointeeType(); 10792 isLValueReference = true; 10793 } else if (const RValueReferenceType *FnTypeRef = 10794 FnType->getAs<RValueReferenceType>()) { 10795 FnType = FnTypeRef->getPointeeType(); 10796 isRValueReference = true; 10797 } 10798 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10799 FnType = FnTypePtr->getPointeeType(); 10800 isPointer = true; 10801 } 10802 // Desugar down to a function type. 10803 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10804 // Reconstruct the pointer/reference as appropriate. 10805 if (isPointer) FnType = S.Context.getPointerType(FnType); 10806 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10807 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10808 10809 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10810 << FnType; 10811 } 10812 10813 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10814 SourceLocation OpLoc, 10815 OverloadCandidate *Cand) { 10816 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10817 std::string TypeStr("operator"); 10818 TypeStr += Opc; 10819 TypeStr += "("; 10820 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10821 if (Cand->Conversions.size() == 1) { 10822 TypeStr += ")"; 10823 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10824 } else { 10825 TypeStr += ", "; 10826 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10827 TypeStr += ")"; 10828 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10829 } 10830 } 10831 10832 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10833 OverloadCandidate *Cand) { 10834 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10835 if (ICS.isBad()) break; // all meaningless after first invalid 10836 if (!ICS.isAmbiguous()) continue; 10837 10838 ICS.DiagnoseAmbiguousConversion( 10839 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10840 } 10841 } 10842 10843 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10844 if (Cand->Function) 10845 return Cand->Function->getLocation(); 10846 if (Cand->IsSurrogate) 10847 return Cand->Surrogate->getLocation(); 10848 return SourceLocation(); 10849 } 10850 10851 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10852 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10853 case Sema::TDK_Success: 10854 case Sema::TDK_NonDependentConversionFailure: 10855 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10856 10857 case Sema::TDK_Invalid: 10858 case Sema::TDK_Incomplete: 10859 case Sema::TDK_IncompletePack: 10860 return 1; 10861 10862 case Sema::TDK_Underqualified: 10863 case Sema::TDK_Inconsistent: 10864 return 2; 10865 10866 case Sema::TDK_SubstitutionFailure: 10867 case Sema::TDK_DeducedMismatch: 10868 case Sema::TDK_ConstraintsNotSatisfied: 10869 case Sema::TDK_DeducedMismatchNested: 10870 case Sema::TDK_NonDeducedMismatch: 10871 case Sema::TDK_MiscellaneousDeductionFailure: 10872 case Sema::TDK_CUDATargetMismatch: 10873 return 3; 10874 10875 case Sema::TDK_InstantiationDepth: 10876 return 4; 10877 10878 case Sema::TDK_InvalidExplicitArguments: 10879 return 5; 10880 10881 case Sema::TDK_TooManyArguments: 10882 case Sema::TDK_TooFewArguments: 10883 return 6; 10884 } 10885 llvm_unreachable("Unhandled deduction result"); 10886 } 10887 10888 namespace { 10889 struct CompareOverloadCandidatesForDisplay { 10890 Sema &S; 10891 SourceLocation Loc; 10892 size_t NumArgs; 10893 OverloadCandidateSet::CandidateSetKind CSK; 10894 10895 CompareOverloadCandidatesForDisplay( 10896 Sema &S, SourceLocation Loc, size_t NArgs, 10897 OverloadCandidateSet::CandidateSetKind CSK) 10898 : S(S), NumArgs(NArgs), CSK(CSK) {} 10899 10900 bool operator()(const OverloadCandidate *L, 10901 const OverloadCandidate *R) { 10902 // Fast-path this check. 10903 if (L == R) return false; 10904 10905 // Order first by viability. 10906 if (L->Viable) { 10907 if (!R->Viable) return true; 10908 10909 // TODO: introduce a tri-valued comparison for overload 10910 // candidates. Would be more worthwhile if we had a sort 10911 // that could exploit it. 10912 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10913 return true; 10914 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10915 return false; 10916 } else if (R->Viable) 10917 return false; 10918 10919 assert(L->Viable == R->Viable); 10920 10921 // Criteria by which we can sort non-viable candidates: 10922 if (!L->Viable) { 10923 // 1. Arity mismatches come after other candidates. 10924 if (L->FailureKind == ovl_fail_too_many_arguments || 10925 L->FailureKind == ovl_fail_too_few_arguments) { 10926 if (R->FailureKind == ovl_fail_too_many_arguments || 10927 R->FailureKind == ovl_fail_too_few_arguments) { 10928 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10929 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10930 if (LDist == RDist) { 10931 if (L->FailureKind == R->FailureKind) 10932 // Sort non-surrogates before surrogates. 10933 return !L->IsSurrogate && R->IsSurrogate; 10934 // Sort candidates requiring fewer parameters than there were 10935 // arguments given after candidates requiring more parameters 10936 // than there were arguments given. 10937 return L->FailureKind == ovl_fail_too_many_arguments; 10938 } 10939 return LDist < RDist; 10940 } 10941 return false; 10942 } 10943 if (R->FailureKind == ovl_fail_too_many_arguments || 10944 R->FailureKind == ovl_fail_too_few_arguments) 10945 return true; 10946 10947 // 2. Bad conversions come first and are ordered by the number 10948 // of bad conversions and quality of good conversions. 10949 if (L->FailureKind == ovl_fail_bad_conversion) { 10950 if (R->FailureKind != ovl_fail_bad_conversion) 10951 return true; 10952 10953 // The conversion that can be fixed with a smaller number of changes, 10954 // comes first. 10955 unsigned numLFixes = L->Fix.NumConversionsFixed; 10956 unsigned numRFixes = R->Fix.NumConversionsFixed; 10957 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10958 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10959 if (numLFixes != numRFixes) { 10960 return numLFixes < numRFixes; 10961 } 10962 10963 // If there's any ordering between the defined conversions... 10964 // FIXME: this might not be transitive. 10965 assert(L->Conversions.size() == R->Conversions.size()); 10966 10967 int leftBetter = 0; 10968 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10969 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10970 switch (CompareImplicitConversionSequences(S, Loc, 10971 L->Conversions[I], 10972 R->Conversions[I])) { 10973 case ImplicitConversionSequence::Better: 10974 leftBetter++; 10975 break; 10976 10977 case ImplicitConversionSequence::Worse: 10978 leftBetter--; 10979 break; 10980 10981 case ImplicitConversionSequence::Indistinguishable: 10982 break; 10983 } 10984 } 10985 if (leftBetter > 0) return true; 10986 if (leftBetter < 0) return false; 10987 10988 } else if (R->FailureKind == ovl_fail_bad_conversion) 10989 return false; 10990 10991 if (L->FailureKind == ovl_fail_bad_deduction) { 10992 if (R->FailureKind != ovl_fail_bad_deduction) 10993 return true; 10994 10995 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10996 return RankDeductionFailure(L->DeductionFailure) 10997 < RankDeductionFailure(R->DeductionFailure); 10998 } else if (R->FailureKind == ovl_fail_bad_deduction) 10999 return false; 11000 11001 // TODO: others? 11002 } 11003 11004 // Sort everything else by location. 11005 SourceLocation LLoc = GetLocationForCandidate(L); 11006 SourceLocation RLoc = GetLocationForCandidate(R); 11007 11008 // Put candidates without locations (e.g. builtins) at the end. 11009 if (LLoc.isInvalid()) return false; 11010 if (RLoc.isInvalid()) return true; 11011 11012 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11013 } 11014 }; 11015 } 11016 11017 /// CompleteNonViableCandidate - Normally, overload resolution only 11018 /// computes up to the first bad conversion. Produces the FixIt set if 11019 /// possible. 11020 static void 11021 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11022 ArrayRef<Expr *> Args, 11023 OverloadCandidateSet::CandidateSetKind CSK) { 11024 assert(!Cand->Viable); 11025 11026 // Don't do anything on failures other than bad conversion. 11027 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 11028 11029 // We only want the FixIts if all the arguments can be corrected. 11030 bool Unfixable = false; 11031 // Use a implicit copy initialization to check conversion fixes. 11032 Cand->Fix.setConversionChecker(TryCopyInitialization); 11033 11034 // Attempt to fix the bad conversion. 11035 unsigned ConvCount = Cand->Conversions.size(); 11036 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11037 ++ConvIdx) { 11038 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11039 if (Cand->Conversions[ConvIdx].isInitialized() && 11040 Cand->Conversions[ConvIdx].isBad()) { 11041 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11042 break; 11043 } 11044 } 11045 11046 // FIXME: this should probably be preserved from the overload 11047 // operation somehow. 11048 bool SuppressUserConversions = false; 11049 11050 unsigned ConvIdx = 0; 11051 unsigned ArgIdx = 0; 11052 ArrayRef<QualType> ParamTypes; 11053 bool Reversed = Cand->RewriteKind & CRK_Reversed; 11054 11055 if (Cand->IsSurrogate) { 11056 QualType ConvType 11057 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11058 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11059 ConvType = ConvPtrType->getPointeeType(); 11060 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11061 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11062 ConvIdx = 1; 11063 } else if (Cand->Function) { 11064 ParamTypes = 11065 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11066 if (isa<CXXMethodDecl>(Cand->Function) && 11067 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11068 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11069 ConvIdx = 1; 11070 if (CSK == OverloadCandidateSet::CSK_Operator && 11071 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11072 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11073 ArgIdx = 1; 11074 } 11075 } else { 11076 // Builtin operator. 11077 assert(ConvCount <= 3); 11078 ParamTypes = Cand->BuiltinParamTypes; 11079 } 11080 11081 // Fill in the rest of the conversions. 11082 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11083 ConvIdx != ConvCount; 11084 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11085 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11086 if (Cand->Conversions[ConvIdx].isInitialized()) { 11087 // We've already checked this conversion. 11088 } else if (ParamIdx < ParamTypes.size()) { 11089 if (ParamTypes[ParamIdx]->isDependentType()) 11090 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11091 Args[ArgIdx]->getType()); 11092 else { 11093 Cand->Conversions[ConvIdx] = 11094 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11095 SuppressUserConversions, 11096 /*InOverloadResolution=*/true, 11097 /*AllowObjCWritebackConversion=*/ 11098 S.getLangOpts().ObjCAutoRefCount); 11099 // Store the FixIt in the candidate if it exists. 11100 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11101 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11102 } 11103 } else 11104 Cand->Conversions[ConvIdx].setEllipsis(); 11105 } 11106 } 11107 11108 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11109 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11110 SourceLocation OpLoc, 11111 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11112 // Sort the candidates by viability and position. Sorting directly would 11113 // be prohibitive, so we make a set of pointers and sort those. 11114 SmallVector<OverloadCandidate*, 32> Cands; 11115 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11116 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11117 if (!Filter(*Cand)) 11118 continue; 11119 switch (OCD) { 11120 case OCD_AllCandidates: 11121 if (!Cand->Viable) { 11122 if (!Cand->Function && !Cand->IsSurrogate) { 11123 // This a non-viable builtin candidate. We do not, in general, 11124 // want to list every possible builtin candidate. 11125 continue; 11126 } 11127 CompleteNonViableCandidate(S, Cand, Args, Kind); 11128 } 11129 break; 11130 11131 case OCD_ViableCandidates: 11132 if (!Cand->Viable) 11133 continue; 11134 break; 11135 11136 case OCD_AmbiguousCandidates: 11137 if (!Cand->Best) 11138 continue; 11139 break; 11140 } 11141 11142 Cands.push_back(Cand); 11143 } 11144 11145 llvm::stable_sort( 11146 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11147 11148 return Cands; 11149 } 11150 11151 /// When overload resolution fails, prints diagnostic messages containing the 11152 /// candidates in the candidate set. 11153 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11154 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11155 StringRef Opc, SourceLocation OpLoc, 11156 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11157 11158 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11159 11160 S.Diag(PD.first, PD.second); 11161 11162 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11163 } 11164 11165 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11166 ArrayRef<OverloadCandidate *> Cands, 11167 StringRef Opc, SourceLocation OpLoc) { 11168 bool ReportedAmbiguousConversions = false; 11169 11170 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11171 unsigned CandsShown = 0; 11172 auto I = Cands.begin(), E = Cands.end(); 11173 for (; I != E; ++I) { 11174 OverloadCandidate *Cand = *I; 11175 11176 // Set an arbitrary limit on the number of candidate functions we'll spam 11177 // the user with. FIXME: This limit should depend on details of the 11178 // candidate list. 11179 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11180 break; 11181 } 11182 ++CandsShown; 11183 11184 if (Cand->Function) 11185 NoteFunctionCandidate(S, Cand, Args.size(), 11186 /*TakingCandidateAddress=*/false, DestAS); 11187 else if (Cand->IsSurrogate) 11188 NoteSurrogateCandidate(S, Cand); 11189 else { 11190 assert(Cand->Viable && 11191 "Non-viable built-in candidates are not added to Cands."); 11192 // Generally we only see ambiguities including viable builtin 11193 // operators if overload resolution got screwed up by an 11194 // ambiguous user-defined conversion. 11195 // 11196 // FIXME: It's quite possible for different conversions to see 11197 // different ambiguities, though. 11198 if (!ReportedAmbiguousConversions) { 11199 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11200 ReportedAmbiguousConversions = true; 11201 } 11202 11203 // If this is a viable builtin, print it. 11204 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11205 } 11206 } 11207 11208 if (I != E) 11209 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11210 } 11211 11212 static SourceLocation 11213 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11214 return Cand->Specialization ? Cand->Specialization->getLocation() 11215 : SourceLocation(); 11216 } 11217 11218 namespace { 11219 struct CompareTemplateSpecCandidatesForDisplay { 11220 Sema &S; 11221 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11222 11223 bool operator()(const TemplateSpecCandidate *L, 11224 const TemplateSpecCandidate *R) { 11225 // Fast-path this check. 11226 if (L == R) 11227 return false; 11228 11229 // Assuming that both candidates are not matches... 11230 11231 // Sort by the ranking of deduction failures. 11232 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11233 return RankDeductionFailure(L->DeductionFailure) < 11234 RankDeductionFailure(R->DeductionFailure); 11235 11236 // Sort everything else by location. 11237 SourceLocation LLoc = GetLocationForCandidate(L); 11238 SourceLocation RLoc = GetLocationForCandidate(R); 11239 11240 // Put candidates without locations (e.g. builtins) at the end. 11241 if (LLoc.isInvalid()) 11242 return false; 11243 if (RLoc.isInvalid()) 11244 return true; 11245 11246 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11247 } 11248 }; 11249 } 11250 11251 /// Diagnose a template argument deduction failure. 11252 /// We are treating these failures as overload failures due to bad 11253 /// deductions. 11254 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11255 bool ForTakingAddress) { 11256 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11257 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11258 } 11259 11260 void TemplateSpecCandidateSet::destroyCandidates() { 11261 for (iterator i = begin(), e = end(); i != e; ++i) { 11262 i->DeductionFailure.Destroy(); 11263 } 11264 } 11265 11266 void TemplateSpecCandidateSet::clear() { 11267 destroyCandidates(); 11268 Candidates.clear(); 11269 } 11270 11271 /// NoteCandidates - When no template specialization match is found, prints 11272 /// diagnostic messages containing the non-matching specializations that form 11273 /// the candidate set. 11274 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11275 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11276 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11277 // Sort the candidates by position (assuming no candidate is a match). 11278 // Sorting directly would be prohibitive, so we make a set of pointers 11279 // and sort those. 11280 SmallVector<TemplateSpecCandidate *, 32> Cands; 11281 Cands.reserve(size()); 11282 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11283 if (Cand->Specialization) 11284 Cands.push_back(Cand); 11285 // Otherwise, this is a non-matching builtin candidate. We do not, 11286 // in general, want to list every possible builtin candidate. 11287 } 11288 11289 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11290 11291 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11292 // for generalization purposes (?). 11293 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11294 11295 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11296 unsigned CandsShown = 0; 11297 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11298 TemplateSpecCandidate *Cand = *I; 11299 11300 // Set an arbitrary limit on the number of candidates we'll spam 11301 // the user with. FIXME: This limit should depend on details of the 11302 // candidate list. 11303 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11304 break; 11305 ++CandsShown; 11306 11307 assert(Cand->Specialization && 11308 "Non-matching built-in candidates are not added to Cands."); 11309 Cand->NoteDeductionFailure(S, ForTakingAddress); 11310 } 11311 11312 if (I != E) 11313 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11314 } 11315 11316 // [PossiblyAFunctionType] --> [Return] 11317 // NonFunctionType --> NonFunctionType 11318 // R (A) --> R(A) 11319 // R (*)(A) --> R (A) 11320 // R (&)(A) --> R (A) 11321 // R (S::*)(A) --> R (A) 11322 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11323 QualType Ret = PossiblyAFunctionType; 11324 if (const PointerType *ToTypePtr = 11325 PossiblyAFunctionType->getAs<PointerType>()) 11326 Ret = ToTypePtr->getPointeeType(); 11327 else if (const ReferenceType *ToTypeRef = 11328 PossiblyAFunctionType->getAs<ReferenceType>()) 11329 Ret = ToTypeRef->getPointeeType(); 11330 else if (const MemberPointerType *MemTypePtr = 11331 PossiblyAFunctionType->getAs<MemberPointerType>()) 11332 Ret = MemTypePtr->getPointeeType(); 11333 Ret = 11334 Context.getCanonicalType(Ret).getUnqualifiedType(); 11335 return Ret; 11336 } 11337 11338 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11339 bool Complain = true) { 11340 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11341 S.DeduceReturnType(FD, Loc, Complain)) 11342 return true; 11343 11344 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11345 if (S.getLangOpts().CPlusPlus17 && 11346 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11347 !S.ResolveExceptionSpec(Loc, FPT)) 11348 return true; 11349 11350 return false; 11351 } 11352 11353 namespace { 11354 // A helper class to help with address of function resolution 11355 // - allows us to avoid passing around all those ugly parameters 11356 class AddressOfFunctionResolver { 11357 Sema& S; 11358 Expr* SourceExpr; 11359 const QualType& TargetType; 11360 QualType TargetFunctionType; // Extracted function type from target type 11361 11362 bool Complain; 11363 //DeclAccessPair& ResultFunctionAccessPair; 11364 ASTContext& Context; 11365 11366 bool TargetTypeIsNonStaticMemberFunction; 11367 bool FoundNonTemplateFunction; 11368 bool StaticMemberFunctionFromBoundPointer; 11369 bool HasComplained; 11370 11371 OverloadExpr::FindResult OvlExprInfo; 11372 OverloadExpr *OvlExpr; 11373 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11374 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11375 TemplateSpecCandidateSet FailedCandidates; 11376 11377 public: 11378 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11379 const QualType &TargetType, bool Complain) 11380 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11381 Complain(Complain), Context(S.getASTContext()), 11382 TargetTypeIsNonStaticMemberFunction( 11383 !!TargetType->getAs<MemberPointerType>()), 11384 FoundNonTemplateFunction(false), 11385 StaticMemberFunctionFromBoundPointer(false), 11386 HasComplained(false), 11387 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11388 OvlExpr(OvlExprInfo.Expression), 11389 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11390 ExtractUnqualifiedFunctionTypeFromTargetType(); 11391 11392 if (TargetFunctionType->isFunctionType()) { 11393 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11394 if (!UME->isImplicitAccess() && 11395 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11396 StaticMemberFunctionFromBoundPointer = true; 11397 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11398 DeclAccessPair dap; 11399 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11400 OvlExpr, false, &dap)) { 11401 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11402 if (!Method->isStatic()) { 11403 // If the target type is a non-function type and the function found 11404 // is a non-static member function, pretend as if that was the 11405 // target, it's the only possible type to end up with. 11406 TargetTypeIsNonStaticMemberFunction = true; 11407 11408 // And skip adding the function if its not in the proper form. 11409 // We'll diagnose this due to an empty set of functions. 11410 if (!OvlExprInfo.HasFormOfMemberPointer) 11411 return; 11412 } 11413 11414 Matches.push_back(std::make_pair(dap, Fn)); 11415 } 11416 return; 11417 } 11418 11419 if (OvlExpr->hasExplicitTemplateArgs()) 11420 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11421 11422 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11423 // C++ [over.over]p4: 11424 // If more than one function is selected, [...] 11425 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11426 if (FoundNonTemplateFunction) 11427 EliminateAllTemplateMatches(); 11428 else 11429 EliminateAllExceptMostSpecializedTemplate(); 11430 } 11431 } 11432 11433 if (S.getLangOpts().CUDA && Matches.size() > 1) 11434 EliminateSuboptimalCudaMatches(); 11435 } 11436 11437 bool hasComplained() const { return HasComplained; } 11438 11439 private: 11440 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11441 QualType Discard; 11442 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11443 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11444 } 11445 11446 /// \return true if A is considered a better overload candidate for the 11447 /// desired type than B. 11448 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11449 // If A doesn't have exactly the correct type, we don't want to classify it 11450 // as "better" than anything else. This way, the user is required to 11451 // disambiguate for us if there are multiple candidates and no exact match. 11452 return candidateHasExactlyCorrectType(A) && 11453 (!candidateHasExactlyCorrectType(B) || 11454 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11455 } 11456 11457 /// \return true if we were able to eliminate all but one overload candidate, 11458 /// false otherwise. 11459 bool eliminiateSuboptimalOverloadCandidates() { 11460 // Same algorithm as overload resolution -- one pass to pick the "best", 11461 // another pass to be sure that nothing is better than the best. 11462 auto Best = Matches.begin(); 11463 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11464 if (isBetterCandidate(I->second, Best->second)) 11465 Best = I; 11466 11467 const FunctionDecl *BestFn = Best->second; 11468 auto IsBestOrInferiorToBest = [this, BestFn]( 11469 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11470 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11471 }; 11472 11473 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11474 // option, so we can potentially give the user a better error 11475 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11476 return false; 11477 Matches[0] = *Best; 11478 Matches.resize(1); 11479 return true; 11480 } 11481 11482 bool isTargetTypeAFunction() const { 11483 return TargetFunctionType->isFunctionType(); 11484 } 11485 11486 // [ToType] [Return] 11487 11488 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11489 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11490 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11491 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11492 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11493 } 11494 11495 // return true if any matching specializations were found 11496 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11497 const DeclAccessPair& CurAccessFunPair) { 11498 if (CXXMethodDecl *Method 11499 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11500 // Skip non-static function templates when converting to pointer, and 11501 // static when converting to member pointer. 11502 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11503 return false; 11504 } 11505 else if (TargetTypeIsNonStaticMemberFunction) 11506 return false; 11507 11508 // C++ [over.over]p2: 11509 // If the name is a function template, template argument deduction is 11510 // done (14.8.2.2), and if the argument deduction succeeds, the 11511 // resulting template argument list is used to generate a single 11512 // function template specialization, which is added to the set of 11513 // overloaded functions considered. 11514 FunctionDecl *Specialization = nullptr; 11515 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11516 if (Sema::TemplateDeductionResult Result 11517 = S.DeduceTemplateArguments(FunctionTemplate, 11518 &OvlExplicitTemplateArgs, 11519 TargetFunctionType, Specialization, 11520 Info, /*IsAddressOfFunction*/true)) { 11521 // Make a note of the failed deduction for diagnostics. 11522 FailedCandidates.addCandidate() 11523 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11524 MakeDeductionFailureInfo(Context, Result, Info)); 11525 return false; 11526 } 11527 11528 // Template argument deduction ensures that we have an exact match or 11529 // compatible pointer-to-function arguments that would be adjusted by ICS. 11530 // This function template specicalization works. 11531 assert(S.isSameOrCompatibleFunctionType( 11532 Context.getCanonicalType(Specialization->getType()), 11533 Context.getCanonicalType(TargetFunctionType))); 11534 11535 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11536 return false; 11537 11538 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11539 return true; 11540 } 11541 11542 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11543 const DeclAccessPair& CurAccessFunPair) { 11544 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11545 // Skip non-static functions when converting to pointer, and static 11546 // when converting to member pointer. 11547 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11548 return false; 11549 } 11550 else if (TargetTypeIsNonStaticMemberFunction) 11551 return false; 11552 11553 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11554 if (S.getLangOpts().CUDA) 11555 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11556 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11557 return false; 11558 if (FunDecl->isMultiVersion()) { 11559 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11560 if (TA && !TA->isDefaultVersion()) 11561 return false; 11562 } 11563 11564 // If any candidate has a placeholder return type, trigger its deduction 11565 // now. 11566 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11567 Complain)) { 11568 HasComplained |= Complain; 11569 return false; 11570 } 11571 11572 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11573 return false; 11574 11575 // If we're in C, we need to support types that aren't exactly identical. 11576 if (!S.getLangOpts().CPlusPlus || 11577 candidateHasExactlyCorrectType(FunDecl)) { 11578 Matches.push_back(std::make_pair( 11579 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11580 FoundNonTemplateFunction = true; 11581 return true; 11582 } 11583 } 11584 11585 return false; 11586 } 11587 11588 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11589 bool Ret = false; 11590 11591 // If the overload expression doesn't have the form of a pointer to 11592 // member, don't try to convert it to a pointer-to-member type. 11593 if (IsInvalidFormOfPointerToMemberFunction()) 11594 return false; 11595 11596 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11597 E = OvlExpr->decls_end(); 11598 I != E; ++I) { 11599 // Look through any using declarations to find the underlying function. 11600 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11601 11602 // C++ [over.over]p3: 11603 // Non-member functions and static member functions match 11604 // targets of type "pointer-to-function" or "reference-to-function." 11605 // Nonstatic member functions match targets of 11606 // type "pointer-to-member-function." 11607 // Note that according to DR 247, the containing class does not matter. 11608 if (FunctionTemplateDecl *FunctionTemplate 11609 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11610 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11611 Ret = true; 11612 } 11613 // If we have explicit template arguments supplied, skip non-templates. 11614 else if (!OvlExpr->hasExplicitTemplateArgs() && 11615 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11616 Ret = true; 11617 } 11618 assert(Ret || Matches.empty()); 11619 return Ret; 11620 } 11621 11622 void EliminateAllExceptMostSpecializedTemplate() { 11623 // [...] and any given function template specialization F1 is 11624 // eliminated if the set contains a second function template 11625 // specialization whose function template is more specialized 11626 // than the function template of F1 according to the partial 11627 // ordering rules of 14.5.5.2. 11628 11629 // The algorithm specified above is quadratic. We instead use a 11630 // two-pass algorithm (similar to the one used to identify the 11631 // best viable function in an overload set) that identifies the 11632 // best function template (if it exists). 11633 11634 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11635 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11636 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11637 11638 // TODO: It looks like FailedCandidates does not serve much purpose 11639 // here, since the no_viable diagnostic has index 0. 11640 UnresolvedSetIterator Result = S.getMostSpecialized( 11641 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11642 SourceExpr->getBeginLoc(), S.PDiag(), 11643 S.PDiag(diag::err_addr_ovl_ambiguous) 11644 << Matches[0].second->getDeclName(), 11645 S.PDiag(diag::note_ovl_candidate) 11646 << (unsigned)oc_function << (unsigned)ocs_described_template, 11647 Complain, TargetFunctionType); 11648 11649 if (Result != MatchesCopy.end()) { 11650 // Make it the first and only element 11651 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11652 Matches[0].second = cast<FunctionDecl>(*Result); 11653 Matches.resize(1); 11654 } else 11655 HasComplained |= Complain; 11656 } 11657 11658 void EliminateAllTemplateMatches() { 11659 // [...] any function template specializations in the set are 11660 // eliminated if the set also contains a non-template function, [...] 11661 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11662 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11663 ++I; 11664 else { 11665 Matches[I] = Matches[--N]; 11666 Matches.resize(N); 11667 } 11668 } 11669 } 11670 11671 void EliminateSuboptimalCudaMatches() { 11672 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11673 } 11674 11675 public: 11676 void ComplainNoMatchesFound() const { 11677 assert(Matches.empty()); 11678 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11679 << OvlExpr->getName() << TargetFunctionType 11680 << OvlExpr->getSourceRange(); 11681 if (FailedCandidates.empty()) 11682 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11683 /*TakingAddress=*/true); 11684 else { 11685 // We have some deduction failure messages. Use them to diagnose 11686 // the function templates, and diagnose the non-template candidates 11687 // normally. 11688 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11689 IEnd = OvlExpr->decls_end(); 11690 I != IEnd; ++I) 11691 if (FunctionDecl *Fun = 11692 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11693 if (!functionHasPassObjectSizeParams(Fun)) 11694 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 11695 /*TakingAddress=*/true); 11696 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11697 } 11698 } 11699 11700 bool IsInvalidFormOfPointerToMemberFunction() const { 11701 return TargetTypeIsNonStaticMemberFunction && 11702 !OvlExprInfo.HasFormOfMemberPointer; 11703 } 11704 11705 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11706 // TODO: Should we condition this on whether any functions might 11707 // have matched, or is it more appropriate to do that in callers? 11708 // TODO: a fixit wouldn't hurt. 11709 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11710 << TargetType << OvlExpr->getSourceRange(); 11711 } 11712 11713 bool IsStaticMemberFunctionFromBoundPointer() const { 11714 return StaticMemberFunctionFromBoundPointer; 11715 } 11716 11717 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11718 S.Diag(OvlExpr->getBeginLoc(), 11719 diag::err_invalid_form_pointer_member_function) 11720 << OvlExpr->getSourceRange(); 11721 } 11722 11723 void ComplainOfInvalidConversion() const { 11724 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11725 << OvlExpr->getName() << TargetType; 11726 } 11727 11728 void ComplainMultipleMatchesFound() const { 11729 assert(Matches.size() > 1); 11730 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11731 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11732 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11733 /*TakingAddress=*/true); 11734 } 11735 11736 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11737 11738 int getNumMatches() const { return Matches.size(); } 11739 11740 FunctionDecl* getMatchingFunctionDecl() const { 11741 if (Matches.size() != 1) return nullptr; 11742 return Matches[0].second; 11743 } 11744 11745 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11746 if (Matches.size() != 1) return nullptr; 11747 return &Matches[0].first; 11748 } 11749 }; 11750 } 11751 11752 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11753 /// an overloaded function (C++ [over.over]), where @p From is an 11754 /// expression with overloaded function type and @p ToType is the type 11755 /// we're trying to resolve to. For example: 11756 /// 11757 /// @code 11758 /// int f(double); 11759 /// int f(int); 11760 /// 11761 /// int (*pfd)(double) = f; // selects f(double) 11762 /// @endcode 11763 /// 11764 /// This routine returns the resulting FunctionDecl if it could be 11765 /// resolved, and NULL otherwise. When @p Complain is true, this 11766 /// routine will emit diagnostics if there is an error. 11767 FunctionDecl * 11768 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11769 QualType TargetType, 11770 bool Complain, 11771 DeclAccessPair &FoundResult, 11772 bool *pHadMultipleCandidates) { 11773 assert(AddressOfExpr->getType() == Context.OverloadTy); 11774 11775 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11776 Complain); 11777 int NumMatches = Resolver.getNumMatches(); 11778 FunctionDecl *Fn = nullptr; 11779 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11780 if (NumMatches == 0 && ShouldComplain) { 11781 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11782 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11783 else 11784 Resolver.ComplainNoMatchesFound(); 11785 } 11786 else if (NumMatches > 1 && ShouldComplain) 11787 Resolver.ComplainMultipleMatchesFound(); 11788 else if (NumMatches == 1) { 11789 Fn = Resolver.getMatchingFunctionDecl(); 11790 assert(Fn); 11791 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11792 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11793 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11794 if (Complain) { 11795 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11796 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11797 else 11798 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11799 } 11800 } 11801 11802 if (pHadMultipleCandidates) 11803 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11804 return Fn; 11805 } 11806 11807 /// Given an expression that refers to an overloaded function, try to 11808 /// resolve that function to a single function that can have its address taken. 11809 /// This will modify `Pair` iff it returns non-null. 11810 /// 11811 /// This routine can only realistically succeed if all but one candidates in the 11812 /// overload set for SrcExpr cannot have their addresses taken. 11813 FunctionDecl * 11814 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11815 DeclAccessPair &Pair) { 11816 OverloadExpr::FindResult R = OverloadExpr::find(E); 11817 OverloadExpr *Ovl = R.Expression; 11818 FunctionDecl *Result = nullptr; 11819 DeclAccessPair DAP; 11820 // Don't use the AddressOfResolver because we're specifically looking for 11821 // cases where we have one overload candidate that lacks 11822 // enable_if/pass_object_size/... 11823 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11824 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11825 if (!FD) 11826 return nullptr; 11827 11828 if (!checkAddressOfFunctionIsAvailable(FD)) 11829 continue; 11830 11831 // We have more than one result; quit. 11832 if (Result) 11833 return nullptr; 11834 DAP = I.getPair(); 11835 Result = FD; 11836 } 11837 11838 if (Result) 11839 Pair = DAP; 11840 return Result; 11841 } 11842 11843 /// Given an overloaded function, tries to turn it into a non-overloaded 11844 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11845 /// will perform access checks, diagnose the use of the resultant decl, and, if 11846 /// requested, potentially perform a function-to-pointer decay. 11847 /// 11848 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11849 /// Otherwise, returns true. This may emit diagnostics and return true. 11850 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11851 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11852 Expr *E = SrcExpr.get(); 11853 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11854 11855 DeclAccessPair DAP; 11856 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11857 if (!Found || Found->isCPUDispatchMultiVersion() || 11858 Found->isCPUSpecificMultiVersion()) 11859 return false; 11860 11861 // Emitting multiple diagnostics for a function that is both inaccessible and 11862 // unavailable is consistent with our behavior elsewhere. So, always check 11863 // for both. 11864 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11865 CheckAddressOfMemberAccess(E, DAP); 11866 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11867 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11868 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11869 else 11870 SrcExpr = Fixed; 11871 return true; 11872 } 11873 11874 /// Given an expression that refers to an overloaded function, try to 11875 /// resolve that overloaded function expression down to a single function. 11876 /// 11877 /// This routine can only resolve template-ids that refer to a single function 11878 /// template, where that template-id refers to a single template whose template 11879 /// arguments are either provided by the template-id or have defaults, 11880 /// as described in C++0x [temp.arg.explicit]p3. 11881 /// 11882 /// If no template-ids are found, no diagnostics are emitted and NULL is 11883 /// returned. 11884 FunctionDecl * 11885 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11886 bool Complain, 11887 DeclAccessPair *FoundResult) { 11888 // C++ [over.over]p1: 11889 // [...] [Note: any redundant set of parentheses surrounding the 11890 // overloaded function name is ignored (5.1). ] 11891 // C++ [over.over]p1: 11892 // [...] The overloaded function name can be preceded by the & 11893 // operator. 11894 11895 // If we didn't actually find any template-ids, we're done. 11896 if (!ovl->hasExplicitTemplateArgs()) 11897 return nullptr; 11898 11899 TemplateArgumentListInfo ExplicitTemplateArgs; 11900 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11901 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11902 11903 // Look through all of the overloaded functions, searching for one 11904 // whose type matches exactly. 11905 FunctionDecl *Matched = nullptr; 11906 for (UnresolvedSetIterator I = ovl->decls_begin(), 11907 E = ovl->decls_end(); I != E; ++I) { 11908 // C++0x [temp.arg.explicit]p3: 11909 // [...] In contexts where deduction is done and fails, or in contexts 11910 // where deduction is not done, if a template argument list is 11911 // specified and it, along with any default template arguments, 11912 // identifies a single function template specialization, then the 11913 // template-id is an lvalue for the function template specialization. 11914 FunctionTemplateDecl *FunctionTemplate 11915 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11916 11917 // C++ [over.over]p2: 11918 // If the name is a function template, template argument deduction is 11919 // done (14.8.2.2), and if the argument deduction succeeds, the 11920 // resulting template argument list is used to generate a single 11921 // function template specialization, which is added to the set of 11922 // overloaded functions considered. 11923 FunctionDecl *Specialization = nullptr; 11924 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11925 if (TemplateDeductionResult Result 11926 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11927 Specialization, Info, 11928 /*IsAddressOfFunction*/true)) { 11929 // Make a note of the failed deduction for diagnostics. 11930 // TODO: Actually use the failed-deduction info? 11931 FailedCandidates.addCandidate() 11932 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11933 MakeDeductionFailureInfo(Context, Result, Info)); 11934 continue; 11935 } 11936 11937 assert(Specialization && "no specialization and no error?"); 11938 11939 // Multiple matches; we can't resolve to a single declaration. 11940 if (Matched) { 11941 if (Complain) { 11942 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11943 << ovl->getName(); 11944 NoteAllOverloadCandidates(ovl); 11945 } 11946 return nullptr; 11947 } 11948 11949 Matched = Specialization; 11950 if (FoundResult) *FoundResult = I.getPair(); 11951 } 11952 11953 if (Matched && 11954 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11955 return nullptr; 11956 11957 return Matched; 11958 } 11959 11960 // Resolve and fix an overloaded expression that can be resolved 11961 // because it identifies a single function template specialization. 11962 // 11963 // Last three arguments should only be supplied if Complain = true 11964 // 11965 // Return true if it was logically possible to so resolve the 11966 // expression, regardless of whether or not it succeeded. Always 11967 // returns true if 'complain' is set. 11968 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11969 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11970 bool complain, SourceRange OpRangeForComplaining, 11971 QualType DestTypeForComplaining, 11972 unsigned DiagIDForComplaining) { 11973 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11974 11975 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11976 11977 DeclAccessPair found; 11978 ExprResult SingleFunctionExpression; 11979 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11980 ovl.Expression, /*complain*/ false, &found)) { 11981 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11982 SrcExpr = ExprError(); 11983 return true; 11984 } 11985 11986 // It is only correct to resolve to an instance method if we're 11987 // resolving a form that's permitted to be a pointer to member. 11988 // Otherwise we'll end up making a bound member expression, which 11989 // is illegal in all the contexts we resolve like this. 11990 if (!ovl.HasFormOfMemberPointer && 11991 isa<CXXMethodDecl>(fn) && 11992 cast<CXXMethodDecl>(fn)->isInstance()) { 11993 if (!complain) return false; 11994 11995 Diag(ovl.Expression->getExprLoc(), 11996 diag::err_bound_member_function) 11997 << 0 << ovl.Expression->getSourceRange(); 11998 11999 // TODO: I believe we only end up here if there's a mix of 12000 // static and non-static candidates (otherwise the expression 12001 // would have 'bound member' type, not 'overload' type). 12002 // Ideally we would note which candidate was chosen and why 12003 // the static candidates were rejected. 12004 SrcExpr = ExprError(); 12005 return true; 12006 } 12007 12008 // Fix the expression to refer to 'fn'. 12009 SingleFunctionExpression = 12010 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12011 12012 // If desired, do function-to-pointer decay. 12013 if (doFunctionPointerConverion) { 12014 SingleFunctionExpression = 12015 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12016 if (SingleFunctionExpression.isInvalid()) { 12017 SrcExpr = ExprError(); 12018 return true; 12019 } 12020 } 12021 } 12022 12023 if (!SingleFunctionExpression.isUsable()) { 12024 if (complain) { 12025 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12026 << ovl.Expression->getName() 12027 << DestTypeForComplaining 12028 << OpRangeForComplaining 12029 << ovl.Expression->getQualifierLoc().getSourceRange(); 12030 NoteAllOverloadCandidates(SrcExpr.get()); 12031 12032 SrcExpr = ExprError(); 12033 return true; 12034 } 12035 12036 return false; 12037 } 12038 12039 SrcExpr = SingleFunctionExpression; 12040 return true; 12041 } 12042 12043 /// Add a single candidate to the overload set. 12044 static void AddOverloadedCallCandidate(Sema &S, 12045 DeclAccessPair FoundDecl, 12046 TemplateArgumentListInfo *ExplicitTemplateArgs, 12047 ArrayRef<Expr *> Args, 12048 OverloadCandidateSet &CandidateSet, 12049 bool PartialOverloading, 12050 bool KnownValid) { 12051 NamedDecl *Callee = FoundDecl.getDecl(); 12052 if (isa<UsingShadowDecl>(Callee)) 12053 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12054 12055 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12056 if (ExplicitTemplateArgs) { 12057 assert(!KnownValid && "Explicit template arguments?"); 12058 return; 12059 } 12060 // Prevent ill-formed function decls to be added as overload candidates. 12061 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12062 return; 12063 12064 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12065 /*SuppressUserConversions=*/false, 12066 PartialOverloading); 12067 return; 12068 } 12069 12070 if (FunctionTemplateDecl *FuncTemplate 12071 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12072 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12073 ExplicitTemplateArgs, Args, CandidateSet, 12074 /*SuppressUserConversions=*/false, 12075 PartialOverloading); 12076 return; 12077 } 12078 12079 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12080 } 12081 12082 /// Add the overload candidates named by callee and/or found by argument 12083 /// dependent lookup to the given overload set. 12084 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12085 ArrayRef<Expr *> Args, 12086 OverloadCandidateSet &CandidateSet, 12087 bool PartialOverloading) { 12088 12089 #ifndef NDEBUG 12090 // Verify that ArgumentDependentLookup is consistent with the rules 12091 // in C++0x [basic.lookup.argdep]p3: 12092 // 12093 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12094 // and let Y be the lookup set produced by argument dependent 12095 // lookup (defined as follows). If X contains 12096 // 12097 // -- a declaration of a class member, or 12098 // 12099 // -- a block-scope function declaration that is not a 12100 // using-declaration, or 12101 // 12102 // -- a declaration that is neither a function or a function 12103 // template 12104 // 12105 // then Y is empty. 12106 12107 if (ULE->requiresADL()) { 12108 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12109 E = ULE->decls_end(); I != E; ++I) { 12110 assert(!(*I)->getDeclContext()->isRecord()); 12111 assert(isa<UsingShadowDecl>(*I) || 12112 !(*I)->getDeclContext()->isFunctionOrMethod()); 12113 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12114 } 12115 } 12116 #endif 12117 12118 // It would be nice to avoid this copy. 12119 TemplateArgumentListInfo TABuffer; 12120 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12121 if (ULE->hasExplicitTemplateArgs()) { 12122 ULE->copyTemplateArgumentsInto(TABuffer); 12123 ExplicitTemplateArgs = &TABuffer; 12124 } 12125 12126 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12127 E = ULE->decls_end(); I != E; ++I) 12128 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12129 CandidateSet, PartialOverloading, 12130 /*KnownValid*/ true); 12131 12132 if (ULE->requiresADL()) 12133 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12134 Args, ExplicitTemplateArgs, 12135 CandidateSet, PartialOverloading); 12136 } 12137 12138 /// Determine whether a declaration with the specified name could be moved into 12139 /// a different namespace. 12140 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12141 switch (Name.getCXXOverloadedOperator()) { 12142 case OO_New: case OO_Array_New: 12143 case OO_Delete: case OO_Array_Delete: 12144 return false; 12145 12146 default: 12147 return true; 12148 } 12149 } 12150 12151 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12152 /// template, where the non-dependent name was declared after the template 12153 /// was defined. This is common in code written for a compilers which do not 12154 /// correctly implement two-stage name lookup. 12155 /// 12156 /// Returns true if a viable candidate was found and a diagnostic was issued. 12157 static bool 12158 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12159 const CXXScopeSpec &SS, LookupResult &R, 12160 OverloadCandidateSet::CandidateSetKind CSK, 12161 TemplateArgumentListInfo *ExplicitTemplateArgs, 12162 ArrayRef<Expr *> Args, 12163 bool *DoDiagnoseEmptyLookup = nullptr) { 12164 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12165 return false; 12166 12167 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12168 if (DC->isTransparentContext()) 12169 continue; 12170 12171 SemaRef.LookupQualifiedName(R, DC); 12172 12173 if (!R.empty()) { 12174 R.suppressDiagnostics(); 12175 12176 if (isa<CXXRecordDecl>(DC)) { 12177 // Don't diagnose names we find in classes; we get much better 12178 // diagnostics for these from DiagnoseEmptyLookup. 12179 R.clear(); 12180 if (DoDiagnoseEmptyLookup) 12181 *DoDiagnoseEmptyLookup = true; 12182 return false; 12183 } 12184 12185 OverloadCandidateSet Candidates(FnLoc, CSK); 12186 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12187 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12188 ExplicitTemplateArgs, Args, 12189 Candidates, false, /*KnownValid*/ false); 12190 12191 OverloadCandidateSet::iterator Best; 12192 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12193 // No viable functions. Don't bother the user with notes for functions 12194 // which don't work and shouldn't be found anyway. 12195 R.clear(); 12196 return false; 12197 } 12198 12199 // Find the namespaces where ADL would have looked, and suggest 12200 // declaring the function there instead. 12201 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12202 Sema::AssociatedClassSet AssociatedClasses; 12203 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12204 AssociatedNamespaces, 12205 AssociatedClasses); 12206 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12207 if (canBeDeclaredInNamespace(R.getLookupName())) { 12208 DeclContext *Std = SemaRef.getStdNamespace(); 12209 for (Sema::AssociatedNamespaceSet::iterator 12210 it = AssociatedNamespaces.begin(), 12211 end = AssociatedNamespaces.end(); it != end; ++it) { 12212 // Never suggest declaring a function within namespace 'std'. 12213 if (Std && Std->Encloses(*it)) 12214 continue; 12215 12216 // Never suggest declaring a function within a namespace with a 12217 // reserved name, like __gnu_cxx. 12218 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12219 if (NS && 12220 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12221 continue; 12222 12223 SuggestedNamespaces.insert(*it); 12224 } 12225 } 12226 12227 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12228 << R.getLookupName(); 12229 if (SuggestedNamespaces.empty()) { 12230 SemaRef.Diag(Best->Function->getLocation(), 12231 diag::note_not_found_by_two_phase_lookup) 12232 << R.getLookupName() << 0; 12233 } else if (SuggestedNamespaces.size() == 1) { 12234 SemaRef.Diag(Best->Function->getLocation(), 12235 diag::note_not_found_by_two_phase_lookup) 12236 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12237 } else { 12238 // FIXME: It would be useful to list the associated namespaces here, 12239 // but the diagnostics infrastructure doesn't provide a way to produce 12240 // a localized representation of a list of items. 12241 SemaRef.Diag(Best->Function->getLocation(), 12242 diag::note_not_found_by_two_phase_lookup) 12243 << R.getLookupName() << 2; 12244 } 12245 12246 // Try to recover by calling this function. 12247 return true; 12248 } 12249 12250 R.clear(); 12251 } 12252 12253 return false; 12254 } 12255 12256 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12257 /// template, where the non-dependent operator was declared after the template 12258 /// was defined. 12259 /// 12260 /// Returns true if a viable candidate was found and a diagnostic was issued. 12261 static bool 12262 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12263 SourceLocation OpLoc, 12264 ArrayRef<Expr *> Args) { 12265 DeclarationName OpName = 12266 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12267 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12268 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12269 OverloadCandidateSet::CSK_Operator, 12270 /*ExplicitTemplateArgs=*/nullptr, Args); 12271 } 12272 12273 namespace { 12274 class BuildRecoveryCallExprRAII { 12275 Sema &SemaRef; 12276 public: 12277 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12278 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12279 SemaRef.IsBuildingRecoveryCallExpr = true; 12280 } 12281 12282 ~BuildRecoveryCallExprRAII() { 12283 SemaRef.IsBuildingRecoveryCallExpr = false; 12284 } 12285 }; 12286 12287 } 12288 12289 /// Attempts to recover from a call where no functions were found. 12290 /// 12291 /// Returns true if new candidates were found. 12292 static ExprResult 12293 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12294 UnresolvedLookupExpr *ULE, 12295 SourceLocation LParenLoc, 12296 MutableArrayRef<Expr *> Args, 12297 SourceLocation RParenLoc, 12298 bool EmptyLookup, bool AllowTypoCorrection) { 12299 // Do not try to recover if it is already building a recovery call. 12300 // This stops infinite loops for template instantiations like 12301 // 12302 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12303 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12304 // 12305 if (SemaRef.IsBuildingRecoveryCallExpr) 12306 return ExprError(); 12307 BuildRecoveryCallExprRAII RCE(SemaRef); 12308 12309 CXXScopeSpec SS; 12310 SS.Adopt(ULE->getQualifierLoc()); 12311 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12312 12313 TemplateArgumentListInfo TABuffer; 12314 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12315 if (ULE->hasExplicitTemplateArgs()) { 12316 ULE->copyTemplateArgumentsInto(TABuffer); 12317 ExplicitTemplateArgs = &TABuffer; 12318 } 12319 12320 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12321 Sema::LookupOrdinaryName); 12322 bool DoDiagnoseEmptyLookup = EmptyLookup; 12323 if (!DiagnoseTwoPhaseLookup( 12324 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12325 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12326 NoTypoCorrectionCCC NoTypoValidator{}; 12327 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12328 ExplicitTemplateArgs != nullptr, 12329 dyn_cast<MemberExpr>(Fn)); 12330 CorrectionCandidateCallback &Validator = 12331 AllowTypoCorrection 12332 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12333 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12334 if (!DoDiagnoseEmptyLookup || 12335 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12336 Args)) 12337 return ExprError(); 12338 } 12339 12340 assert(!R.empty() && "lookup results empty despite recovery"); 12341 12342 // If recovery created an ambiguity, just bail out. 12343 if (R.isAmbiguous()) { 12344 R.suppressDiagnostics(); 12345 return ExprError(); 12346 } 12347 12348 // Build an implicit member call if appropriate. Just drop the 12349 // casts and such from the call, we don't really care. 12350 ExprResult NewFn = ExprError(); 12351 if ((*R.begin())->isCXXClassMember()) 12352 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12353 ExplicitTemplateArgs, S); 12354 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12355 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12356 ExplicitTemplateArgs); 12357 else 12358 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12359 12360 if (NewFn.isInvalid()) 12361 return ExprError(); 12362 12363 // This shouldn't cause an infinite loop because we're giving it 12364 // an expression with viable lookup results, which should never 12365 // end up here. 12366 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12367 MultiExprArg(Args.data(), Args.size()), 12368 RParenLoc); 12369 } 12370 12371 /// Constructs and populates an OverloadedCandidateSet from 12372 /// the given function. 12373 /// \returns true when an the ExprResult output parameter has been set. 12374 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12375 UnresolvedLookupExpr *ULE, 12376 MultiExprArg Args, 12377 SourceLocation RParenLoc, 12378 OverloadCandidateSet *CandidateSet, 12379 ExprResult *Result) { 12380 #ifndef NDEBUG 12381 if (ULE->requiresADL()) { 12382 // To do ADL, we must have found an unqualified name. 12383 assert(!ULE->getQualifier() && "qualified name with ADL"); 12384 12385 // We don't perform ADL for implicit declarations of builtins. 12386 // Verify that this was correctly set up. 12387 FunctionDecl *F; 12388 if (ULE->decls_begin() != ULE->decls_end() && 12389 ULE->decls_begin() + 1 == ULE->decls_end() && 12390 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12391 F->getBuiltinID() && F->isImplicit()) 12392 llvm_unreachable("performing ADL for builtin"); 12393 12394 // We don't perform ADL in C. 12395 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12396 } 12397 #endif 12398 12399 UnbridgedCastsSet UnbridgedCasts; 12400 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12401 *Result = ExprError(); 12402 return true; 12403 } 12404 12405 // Add the functions denoted by the callee to the set of candidate 12406 // functions, including those from argument-dependent lookup. 12407 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12408 12409 if (getLangOpts().MSVCCompat && 12410 CurContext->isDependentContext() && !isSFINAEContext() && 12411 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12412 12413 OverloadCandidateSet::iterator Best; 12414 if (CandidateSet->empty() || 12415 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12416 OR_No_Viable_Function) { 12417 // In Microsoft mode, if we are inside a template class member function 12418 // then create a type dependent CallExpr. The goal is to postpone name 12419 // lookup to instantiation time to be able to search into type dependent 12420 // base classes. 12421 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12422 VK_RValue, RParenLoc); 12423 CE->setTypeDependent(true); 12424 CE->setValueDependent(true); 12425 CE->setInstantiationDependent(true); 12426 *Result = CE; 12427 return true; 12428 } 12429 } 12430 12431 if (CandidateSet->empty()) 12432 return false; 12433 12434 UnbridgedCasts.restore(); 12435 return false; 12436 } 12437 12438 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12439 /// the completed call expression. If overload resolution fails, emits 12440 /// diagnostics and returns ExprError() 12441 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12442 UnresolvedLookupExpr *ULE, 12443 SourceLocation LParenLoc, 12444 MultiExprArg Args, 12445 SourceLocation RParenLoc, 12446 Expr *ExecConfig, 12447 OverloadCandidateSet *CandidateSet, 12448 OverloadCandidateSet::iterator *Best, 12449 OverloadingResult OverloadResult, 12450 bool AllowTypoCorrection) { 12451 if (CandidateSet->empty()) 12452 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12453 RParenLoc, /*EmptyLookup=*/true, 12454 AllowTypoCorrection); 12455 12456 switch (OverloadResult) { 12457 case OR_Success: { 12458 FunctionDecl *FDecl = (*Best)->Function; 12459 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12460 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12461 return ExprError(); 12462 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12463 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12464 ExecConfig, /*IsExecConfig=*/false, 12465 (*Best)->IsADLCandidate); 12466 } 12467 12468 case OR_No_Viable_Function: { 12469 // Try to recover by looking for viable functions which the user might 12470 // have meant to call. 12471 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12472 Args, RParenLoc, 12473 /*EmptyLookup=*/false, 12474 AllowTypoCorrection); 12475 if (!Recovery.isInvalid()) 12476 return Recovery; 12477 12478 // If the user passes in a function that we can't take the address of, we 12479 // generally end up emitting really bad error messages. Here, we attempt to 12480 // emit better ones. 12481 for (const Expr *Arg : Args) { 12482 if (!Arg->getType()->isFunctionType()) 12483 continue; 12484 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12485 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12486 if (FD && 12487 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12488 Arg->getExprLoc())) 12489 return ExprError(); 12490 } 12491 } 12492 12493 CandidateSet->NoteCandidates( 12494 PartialDiagnosticAt( 12495 Fn->getBeginLoc(), 12496 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12497 << ULE->getName() << Fn->getSourceRange()), 12498 SemaRef, OCD_AllCandidates, Args); 12499 break; 12500 } 12501 12502 case OR_Ambiguous: 12503 CandidateSet->NoteCandidates( 12504 PartialDiagnosticAt(Fn->getBeginLoc(), 12505 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12506 << ULE->getName() << Fn->getSourceRange()), 12507 SemaRef, OCD_AmbiguousCandidates, Args); 12508 break; 12509 12510 case OR_Deleted: { 12511 CandidateSet->NoteCandidates( 12512 PartialDiagnosticAt(Fn->getBeginLoc(), 12513 SemaRef.PDiag(diag::err_ovl_deleted_call) 12514 << ULE->getName() << Fn->getSourceRange()), 12515 SemaRef, OCD_AllCandidates, Args); 12516 12517 // We emitted an error for the unavailable/deleted function call but keep 12518 // the call in the AST. 12519 FunctionDecl *FDecl = (*Best)->Function; 12520 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12521 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12522 ExecConfig, /*IsExecConfig=*/false, 12523 (*Best)->IsADLCandidate); 12524 } 12525 } 12526 12527 // Overload resolution failed. 12528 return ExprError(); 12529 } 12530 12531 static void markUnaddressableCandidatesUnviable(Sema &S, 12532 OverloadCandidateSet &CS) { 12533 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12534 if (I->Viable && 12535 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12536 I->Viable = false; 12537 I->FailureKind = ovl_fail_addr_not_available; 12538 } 12539 } 12540 } 12541 12542 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12543 /// (which eventually refers to the declaration Func) and the call 12544 /// arguments Args/NumArgs, attempt to resolve the function call down 12545 /// to a specific function. If overload resolution succeeds, returns 12546 /// the call expression produced by overload resolution. 12547 /// Otherwise, emits diagnostics and returns ExprError. 12548 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12549 UnresolvedLookupExpr *ULE, 12550 SourceLocation LParenLoc, 12551 MultiExprArg Args, 12552 SourceLocation RParenLoc, 12553 Expr *ExecConfig, 12554 bool AllowTypoCorrection, 12555 bool CalleesAddressIsTaken) { 12556 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12557 OverloadCandidateSet::CSK_Normal); 12558 ExprResult result; 12559 12560 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12561 &result)) 12562 return result; 12563 12564 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12565 // functions that aren't addressible are considered unviable. 12566 if (CalleesAddressIsTaken) 12567 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12568 12569 OverloadCandidateSet::iterator Best; 12570 OverloadingResult OverloadResult = 12571 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12572 12573 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12574 ExecConfig, &CandidateSet, &Best, 12575 OverloadResult, AllowTypoCorrection); 12576 } 12577 12578 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12579 return Functions.size() > 1 || 12580 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12581 } 12582 12583 /// Create a unary operation that may resolve to an overloaded 12584 /// operator. 12585 /// 12586 /// \param OpLoc The location of the operator itself (e.g., '*'). 12587 /// 12588 /// \param Opc The UnaryOperatorKind that describes this operator. 12589 /// 12590 /// \param Fns The set of non-member functions that will be 12591 /// considered by overload resolution. The caller needs to build this 12592 /// set based on the context using, e.g., 12593 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12594 /// set should not contain any member functions; those will be added 12595 /// by CreateOverloadedUnaryOp(). 12596 /// 12597 /// \param Input The input argument. 12598 ExprResult 12599 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12600 const UnresolvedSetImpl &Fns, 12601 Expr *Input, bool PerformADL) { 12602 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12603 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12604 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12605 // TODO: provide better source location info. 12606 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12607 12608 if (checkPlaceholderForOverload(*this, Input)) 12609 return ExprError(); 12610 12611 Expr *Args[2] = { Input, nullptr }; 12612 unsigned NumArgs = 1; 12613 12614 // For post-increment and post-decrement, add the implicit '0' as 12615 // the second argument, so that we know this is a post-increment or 12616 // post-decrement. 12617 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12618 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12619 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12620 SourceLocation()); 12621 NumArgs = 2; 12622 } 12623 12624 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12625 12626 if (Input->isTypeDependent()) { 12627 if (Fns.empty()) 12628 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12629 VK_RValue, OK_Ordinary, OpLoc, false); 12630 12631 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12632 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12633 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12634 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12635 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12636 Context.DependentTy, VK_RValue, OpLoc, 12637 FPOptions()); 12638 } 12639 12640 // Build an empty overload set. 12641 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12642 12643 // Add the candidates from the given function set. 12644 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 12645 12646 // Add operator candidates that are member functions. 12647 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12648 12649 // Add candidates from ADL. 12650 if (PerformADL) { 12651 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12652 /*ExplicitTemplateArgs*/nullptr, 12653 CandidateSet); 12654 } 12655 12656 // Add builtin operator candidates. 12657 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12658 12659 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12660 12661 // Perform overload resolution. 12662 OverloadCandidateSet::iterator Best; 12663 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12664 case OR_Success: { 12665 // We found a built-in operator or an overloaded operator. 12666 FunctionDecl *FnDecl = Best->Function; 12667 12668 if (FnDecl) { 12669 Expr *Base = nullptr; 12670 // We matched an overloaded operator. Build a call to that 12671 // operator. 12672 12673 // Convert the arguments. 12674 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12675 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12676 12677 ExprResult InputRes = 12678 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12679 Best->FoundDecl, Method); 12680 if (InputRes.isInvalid()) 12681 return ExprError(); 12682 Base = Input = InputRes.get(); 12683 } else { 12684 // Convert the arguments. 12685 ExprResult InputInit 12686 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12687 Context, 12688 FnDecl->getParamDecl(0)), 12689 SourceLocation(), 12690 Input); 12691 if (InputInit.isInvalid()) 12692 return ExprError(); 12693 Input = InputInit.get(); 12694 } 12695 12696 // Build the actual expression node. 12697 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12698 Base, HadMultipleCandidates, 12699 OpLoc); 12700 if (FnExpr.isInvalid()) 12701 return ExprError(); 12702 12703 // Determine the result type. 12704 QualType ResultTy = FnDecl->getReturnType(); 12705 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12706 ResultTy = ResultTy.getNonLValueExprType(Context); 12707 12708 Args[0] = Input; 12709 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12710 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12711 FPOptions(), Best->IsADLCandidate); 12712 12713 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12714 return ExprError(); 12715 12716 if (CheckFunctionCall(FnDecl, TheCall, 12717 FnDecl->getType()->castAs<FunctionProtoType>())) 12718 return ExprError(); 12719 12720 return MaybeBindToTemporary(TheCall); 12721 } else { 12722 // We matched a built-in operator. Convert the arguments, then 12723 // break out so that we will build the appropriate built-in 12724 // operator node. 12725 ExprResult InputRes = PerformImplicitConversion( 12726 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12727 CCK_ForBuiltinOverloadedOp); 12728 if (InputRes.isInvalid()) 12729 return ExprError(); 12730 Input = InputRes.get(); 12731 break; 12732 } 12733 } 12734 12735 case OR_No_Viable_Function: 12736 // This is an erroneous use of an operator which can be overloaded by 12737 // a non-member function. Check for non-member operators which were 12738 // defined too late to be candidates. 12739 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12740 // FIXME: Recover by calling the found function. 12741 return ExprError(); 12742 12743 // No viable function; fall through to handling this as a 12744 // built-in operator, which will produce an error message for us. 12745 break; 12746 12747 case OR_Ambiguous: 12748 CandidateSet.NoteCandidates( 12749 PartialDiagnosticAt(OpLoc, 12750 PDiag(diag::err_ovl_ambiguous_oper_unary) 12751 << UnaryOperator::getOpcodeStr(Opc) 12752 << Input->getType() << Input->getSourceRange()), 12753 *this, OCD_AmbiguousCandidates, ArgsArray, 12754 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12755 return ExprError(); 12756 12757 case OR_Deleted: 12758 CandidateSet.NoteCandidates( 12759 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12760 << UnaryOperator::getOpcodeStr(Opc) 12761 << Input->getSourceRange()), 12762 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 12763 OpLoc); 12764 return ExprError(); 12765 } 12766 12767 // Either we found no viable overloaded operator or we matched a 12768 // built-in operator. In either case, fall through to trying to 12769 // build a built-in operation. 12770 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12771 } 12772 12773 /// Perform lookup for an overloaded binary operator. 12774 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 12775 OverloadedOperatorKind Op, 12776 const UnresolvedSetImpl &Fns, 12777 ArrayRef<Expr *> Args, bool PerformADL) { 12778 SourceLocation OpLoc = CandidateSet.getLocation(); 12779 12780 OverloadedOperatorKind ExtraOp = 12781 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 12782 ? getRewrittenOverloadedOperator(Op) 12783 : OO_None; 12784 12785 // Add the candidates from the given function set. This also adds the 12786 // rewritten candidates using these functions if necessary. 12787 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 12788 12789 // Add operator candidates that are member functions. 12790 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12791 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 12792 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 12793 OverloadCandidateParamOrder::Reversed); 12794 12795 // In C++20, also add any rewritten member candidates. 12796 if (ExtraOp) { 12797 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 12798 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 12799 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 12800 CandidateSet, 12801 OverloadCandidateParamOrder::Reversed); 12802 } 12803 12804 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12805 // performed for an assignment operator (nor for operator[] nor operator->, 12806 // which don't get here). 12807 if (Op != OO_Equal && PerformADL) { 12808 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12809 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12810 /*ExplicitTemplateArgs*/ nullptr, 12811 CandidateSet); 12812 if (ExtraOp) { 12813 DeclarationName ExtraOpName = 12814 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 12815 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 12816 /*ExplicitTemplateArgs*/ nullptr, 12817 CandidateSet); 12818 } 12819 } 12820 12821 // Add builtin operator candidates. 12822 // 12823 // FIXME: We don't add any rewritten candidates here. This is strictly 12824 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 12825 // resulting in our selecting a rewritten builtin candidate. For example: 12826 // 12827 // enum class E { e }; 12828 // bool operator!=(E, E) requires false; 12829 // bool k = E::e != E::e; 12830 // 12831 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 12832 // it seems unreasonable to consider rewritten builtin candidates. A core 12833 // issue has been filed proposing to removed this requirement. 12834 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12835 } 12836 12837 /// Create a binary operation that may resolve to an overloaded 12838 /// operator. 12839 /// 12840 /// \param OpLoc The location of the operator itself (e.g., '+'). 12841 /// 12842 /// \param Opc The BinaryOperatorKind that describes this operator. 12843 /// 12844 /// \param Fns The set of non-member functions that will be 12845 /// considered by overload resolution. The caller needs to build this 12846 /// set based on the context using, e.g., 12847 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12848 /// set should not contain any member functions; those will be added 12849 /// by CreateOverloadedBinOp(). 12850 /// 12851 /// \param LHS Left-hand argument. 12852 /// \param RHS Right-hand argument. 12853 /// \param PerformADL Whether to consider operator candidates found by ADL. 12854 /// \param AllowRewrittenCandidates Whether to consider candidates found by 12855 /// C++20 operator rewrites. 12856 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 12857 /// the function in question. Such a function is never a candidate in 12858 /// our overload resolution. This also enables synthesizing a three-way 12859 /// comparison from < and == as described in C++20 [class.spaceship]p1. 12860 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12861 BinaryOperatorKind Opc, 12862 const UnresolvedSetImpl &Fns, Expr *LHS, 12863 Expr *RHS, bool PerformADL, 12864 bool AllowRewrittenCandidates, 12865 FunctionDecl *DefaultedFn) { 12866 Expr *Args[2] = { LHS, RHS }; 12867 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12868 12869 if (!getLangOpts().CPlusPlus2a) 12870 AllowRewrittenCandidates = false; 12871 12872 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12873 12874 // If either side is type-dependent, create an appropriate dependent 12875 // expression. 12876 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12877 if (Fns.empty()) { 12878 // If there are no functions to store, just build a dependent 12879 // BinaryOperator or CompoundAssignment. 12880 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12881 return new (Context) BinaryOperator( 12882 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12883 OpLoc, FPFeatures); 12884 12885 return new (Context) CompoundAssignOperator( 12886 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12887 Context.DependentTy, Context.DependentTy, OpLoc, 12888 FPFeatures); 12889 } 12890 12891 // FIXME: save results of ADL from here? 12892 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12893 // TODO: provide better source location info in DNLoc component. 12894 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12895 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12896 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12897 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12898 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12899 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12900 Context.DependentTy, VK_RValue, OpLoc, 12901 FPFeatures); 12902 } 12903 12904 // Always do placeholder-like conversions on the RHS. 12905 if (checkPlaceholderForOverload(*this, Args[1])) 12906 return ExprError(); 12907 12908 // Do placeholder-like conversion on the LHS; note that we should 12909 // not get here with a PseudoObject LHS. 12910 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12911 if (checkPlaceholderForOverload(*this, Args[0])) 12912 return ExprError(); 12913 12914 // If this is the assignment operator, we only perform overload resolution 12915 // if the left-hand side is a class or enumeration type. This is actually 12916 // a hack. The standard requires that we do overload resolution between the 12917 // various built-in candidates, but as DR507 points out, this can lead to 12918 // problems. So we do it this way, which pretty much follows what GCC does. 12919 // Note that we go the traditional code path for compound assignment forms. 12920 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12921 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12922 12923 // If this is the .* operator, which is not overloadable, just 12924 // create a built-in binary operator. 12925 if (Opc == BO_PtrMemD) 12926 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12927 12928 // Build the overload set. 12929 OverloadCandidateSet CandidateSet( 12930 OpLoc, OverloadCandidateSet::CSK_Operator, 12931 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 12932 if (DefaultedFn) 12933 CandidateSet.exclude(DefaultedFn); 12934 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 12935 12936 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12937 12938 // Perform overload resolution. 12939 OverloadCandidateSet::iterator Best; 12940 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12941 case OR_Success: { 12942 // We found a built-in operator or an overloaded operator. 12943 FunctionDecl *FnDecl = Best->Function; 12944 12945 bool IsReversed = (Best->RewriteKind & CRK_Reversed); 12946 if (IsReversed) 12947 std::swap(Args[0], Args[1]); 12948 12949 if (FnDecl) { 12950 Expr *Base = nullptr; 12951 // We matched an overloaded operator. Build a call to that 12952 // operator. 12953 12954 OverloadedOperatorKind ChosenOp = 12955 FnDecl->getDeclName().getCXXOverloadedOperator(); 12956 12957 // C++2a [over.match.oper]p9: 12958 // If a rewritten operator== candidate is selected by overload 12959 // resolution for an operator@, its return type shall be cv bool 12960 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 12961 !FnDecl->getReturnType()->isBooleanType()) { 12962 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) 12963 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 12964 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12965 Diag(FnDecl->getLocation(), diag::note_declared_at); 12966 return ExprError(); 12967 } 12968 12969 if (AllowRewrittenCandidates && !IsReversed && 12970 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { 12971 // We could have reversed this operator, but didn't. Check if the 12972 // reversed form was a viable candidate, and if so, if it had a 12973 // better conversion for either parameter. If so, this call is 12974 // formally ambiguous, and allowing it is an extension. 12975 for (OverloadCandidate &Cand : CandidateSet) { 12976 if (Cand.Viable && Cand.Function == FnDecl && 12977 Cand.RewriteKind & CRK_Reversed) { 12978 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 12979 if (CompareImplicitConversionSequences( 12980 *this, OpLoc, Cand.Conversions[ArgIdx], 12981 Best->Conversions[ArgIdx]) == 12982 ImplicitConversionSequence::Better) { 12983 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 12984 << BinaryOperator::getOpcodeStr(Opc) 12985 << Args[0]->getType() << Args[1]->getType() 12986 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12987 Diag(FnDecl->getLocation(), 12988 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 12989 } 12990 } 12991 break; 12992 } 12993 } 12994 } 12995 12996 // Convert the arguments. 12997 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12998 // Best->Access is only meaningful for class members. 12999 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13000 13001 ExprResult Arg1 = 13002 PerformCopyInitialization( 13003 InitializedEntity::InitializeParameter(Context, 13004 FnDecl->getParamDecl(0)), 13005 SourceLocation(), Args[1]); 13006 if (Arg1.isInvalid()) 13007 return ExprError(); 13008 13009 ExprResult Arg0 = 13010 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13011 Best->FoundDecl, Method); 13012 if (Arg0.isInvalid()) 13013 return ExprError(); 13014 Base = Args[0] = Arg0.getAs<Expr>(); 13015 Args[1] = RHS = Arg1.getAs<Expr>(); 13016 } else { 13017 // Convert the arguments. 13018 ExprResult Arg0 = PerformCopyInitialization( 13019 InitializedEntity::InitializeParameter(Context, 13020 FnDecl->getParamDecl(0)), 13021 SourceLocation(), Args[0]); 13022 if (Arg0.isInvalid()) 13023 return ExprError(); 13024 13025 ExprResult Arg1 = 13026 PerformCopyInitialization( 13027 InitializedEntity::InitializeParameter(Context, 13028 FnDecl->getParamDecl(1)), 13029 SourceLocation(), Args[1]); 13030 if (Arg1.isInvalid()) 13031 return ExprError(); 13032 Args[0] = LHS = Arg0.getAs<Expr>(); 13033 Args[1] = RHS = Arg1.getAs<Expr>(); 13034 } 13035 13036 // Build the actual expression node. 13037 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13038 Best->FoundDecl, Base, 13039 HadMultipleCandidates, OpLoc); 13040 if (FnExpr.isInvalid()) 13041 return ExprError(); 13042 13043 // Determine the result type. 13044 QualType ResultTy = FnDecl->getReturnType(); 13045 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13046 ResultTy = ResultTy.getNonLValueExprType(Context); 13047 13048 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13049 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13050 FPFeatures, Best->IsADLCandidate); 13051 13052 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13053 FnDecl)) 13054 return ExprError(); 13055 13056 ArrayRef<const Expr *> ArgsArray(Args, 2); 13057 const Expr *ImplicitThis = nullptr; 13058 // Cut off the implicit 'this'. 13059 if (isa<CXXMethodDecl>(FnDecl)) { 13060 ImplicitThis = ArgsArray[0]; 13061 ArgsArray = ArgsArray.slice(1); 13062 } 13063 13064 // Check for a self move. 13065 if (Op == OO_Equal) 13066 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13067 13068 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13069 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13070 VariadicDoesNotApply); 13071 13072 ExprResult R = MaybeBindToTemporary(TheCall); 13073 if (R.isInvalid()) 13074 return ExprError(); 13075 13076 // For a rewritten candidate, we've already reversed the arguments 13077 // if needed. Perform the rest of the rewrite now. 13078 if ((Best->RewriteKind & CRK_DifferentOperator) || 13079 (Op == OO_Spaceship && IsReversed)) { 13080 if (Op == OO_ExclaimEqual) { 13081 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13082 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13083 } else { 13084 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13085 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13086 Expr *ZeroLiteral = 13087 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13088 13089 Sema::CodeSynthesisContext Ctx; 13090 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13091 Ctx.Entity = FnDecl; 13092 pushCodeSynthesisContext(Ctx); 13093 13094 R = CreateOverloadedBinOp( 13095 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13096 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13097 /*AllowRewrittenCandidates=*/false); 13098 13099 popCodeSynthesisContext(); 13100 } 13101 if (R.isInvalid()) 13102 return ExprError(); 13103 } else { 13104 assert(ChosenOp == Op && "unexpected operator name"); 13105 } 13106 13107 // Make a note in the AST if we did any rewriting. 13108 if (Best->RewriteKind != CRK_None) 13109 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13110 13111 return R; 13112 } else { 13113 // We matched a built-in operator. Convert the arguments, then 13114 // break out so that we will build the appropriate built-in 13115 // operator node. 13116 ExprResult ArgsRes0 = PerformImplicitConversion( 13117 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13118 AA_Passing, CCK_ForBuiltinOverloadedOp); 13119 if (ArgsRes0.isInvalid()) 13120 return ExprError(); 13121 Args[0] = ArgsRes0.get(); 13122 13123 ExprResult ArgsRes1 = PerformImplicitConversion( 13124 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13125 AA_Passing, CCK_ForBuiltinOverloadedOp); 13126 if (ArgsRes1.isInvalid()) 13127 return ExprError(); 13128 Args[1] = ArgsRes1.get(); 13129 break; 13130 } 13131 } 13132 13133 case OR_No_Viable_Function: { 13134 // C++ [over.match.oper]p9: 13135 // If the operator is the operator , [...] and there are no 13136 // viable functions, then the operator is assumed to be the 13137 // built-in operator and interpreted according to clause 5. 13138 if (Opc == BO_Comma) 13139 break; 13140 13141 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13142 // compare result using '==' and '<'. 13143 if (DefaultedFn && Opc == BO_Cmp) { 13144 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13145 Args[1], DefaultedFn); 13146 if (E.isInvalid() || E.isUsable()) 13147 return E; 13148 } 13149 13150 // For class as left operand for assignment or compound assignment 13151 // operator do not fall through to handling in built-in, but report that 13152 // no overloaded assignment operator found 13153 ExprResult Result = ExprError(); 13154 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13155 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13156 Args, OpLoc); 13157 if (Args[0]->getType()->isRecordType() && 13158 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13159 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13160 << BinaryOperator::getOpcodeStr(Opc) 13161 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13162 if (Args[0]->getType()->isIncompleteType()) { 13163 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13164 << Args[0]->getType() 13165 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13166 } 13167 } else { 13168 // This is an erroneous use of an operator which can be overloaded by 13169 // a non-member function. Check for non-member operators which were 13170 // defined too late to be candidates. 13171 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13172 // FIXME: Recover by calling the found function. 13173 return ExprError(); 13174 13175 // No viable function; try to create a built-in operation, which will 13176 // produce an error. Then, show the non-viable candidates. 13177 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13178 } 13179 assert(Result.isInvalid() && 13180 "C++ binary operator overloading is missing candidates!"); 13181 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13182 return Result; 13183 } 13184 13185 case OR_Ambiguous: 13186 CandidateSet.NoteCandidates( 13187 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13188 << BinaryOperator::getOpcodeStr(Opc) 13189 << Args[0]->getType() 13190 << Args[1]->getType() 13191 << Args[0]->getSourceRange() 13192 << Args[1]->getSourceRange()), 13193 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13194 OpLoc); 13195 return ExprError(); 13196 13197 case OR_Deleted: 13198 if (isImplicitlyDeleted(Best->Function)) { 13199 FunctionDecl *DeletedFD = Best->Function; 13200 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13201 if (DFK.isSpecialMember()) { 13202 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13203 << Args[0]->getType() << DFK.asSpecialMember(); 13204 } else { 13205 assert(DFK.isComparison()); 13206 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13207 << Args[0]->getType() << DeletedFD; 13208 } 13209 13210 // The user probably meant to call this special member. Just 13211 // explain why it's deleted. 13212 NoteDeletedFunction(DeletedFD); 13213 return ExprError(); 13214 } 13215 CandidateSet.NoteCandidates( 13216 PartialDiagnosticAt( 13217 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13218 << getOperatorSpelling(Best->Function->getDeclName() 13219 .getCXXOverloadedOperator()) 13220 << Args[0]->getSourceRange() 13221 << Args[1]->getSourceRange()), 13222 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13223 OpLoc); 13224 return ExprError(); 13225 } 13226 13227 // We matched a built-in operator; build it. 13228 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13229 } 13230 13231 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13232 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13233 FunctionDecl *DefaultedFn) { 13234 const ComparisonCategoryInfo *Info = 13235 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13236 // If we're not producing a known comparison category type, we can't 13237 // synthesize a three-way comparison. Let the caller diagnose this. 13238 if (!Info) 13239 return ExprResult((Expr*)nullptr); 13240 13241 // If we ever want to perform this synthesis more generally, we will need to 13242 // apply the temporary materialization conversion to the operands. 13243 assert(LHS->isGLValue() && RHS->isGLValue() && 13244 "cannot use prvalue expressions more than once"); 13245 Expr *OrigLHS = LHS; 13246 Expr *OrigRHS = RHS; 13247 13248 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13249 // each of them multiple times below. 13250 LHS = new (Context) 13251 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13252 LHS->getObjectKind(), LHS); 13253 RHS = new (Context) 13254 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13255 RHS->getObjectKind(), RHS); 13256 13257 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13258 DefaultedFn); 13259 if (Eq.isInvalid()) 13260 return ExprError(); 13261 13262 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13263 true, DefaultedFn); 13264 if (Less.isInvalid()) 13265 return ExprError(); 13266 13267 ExprResult Greater; 13268 if (Info->isPartial()) { 13269 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13270 DefaultedFn); 13271 if (Greater.isInvalid()) 13272 return ExprError(); 13273 } 13274 13275 // Form the list of comparisons we're going to perform. 13276 struct Comparison { 13277 ExprResult Cmp; 13278 ComparisonCategoryResult Result; 13279 } Comparisons[4] = 13280 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13281 : ComparisonCategoryResult::Equivalent}, 13282 {Less, ComparisonCategoryResult::Less}, 13283 {Greater, ComparisonCategoryResult::Greater}, 13284 {ExprResult(), ComparisonCategoryResult::Unordered}, 13285 }; 13286 13287 int I = Info->isPartial() ? 3 : 2; 13288 13289 // Combine the comparisons with suitable conditional expressions. 13290 ExprResult Result; 13291 for (; I >= 0; --I) { 13292 // Build a reference to the comparison category constant. 13293 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13294 // FIXME: Missing a constant for a comparison category. Diagnose this? 13295 if (!VI) 13296 return ExprResult((Expr*)nullptr); 13297 ExprResult ThisResult = 13298 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13299 if (ThisResult.isInvalid()) 13300 return ExprError(); 13301 13302 // Build a conditional unless this is the final case. 13303 if (Result.get()) { 13304 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13305 ThisResult.get(), Result.get()); 13306 if (Result.isInvalid()) 13307 return ExprError(); 13308 } else { 13309 Result = ThisResult; 13310 } 13311 } 13312 13313 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13314 // bind the OpaqueValueExprs before they're (repeatedly) used. 13315 Expr *SyntacticForm = new (Context) 13316 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13317 Result.get()->getValueKind(), 13318 Result.get()->getObjectKind(), OpLoc, FPFeatures); 13319 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13320 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13321 } 13322 13323 ExprResult 13324 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13325 SourceLocation RLoc, 13326 Expr *Base, Expr *Idx) { 13327 Expr *Args[2] = { Base, Idx }; 13328 DeclarationName OpName = 13329 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13330 13331 // If either side is type-dependent, create an appropriate dependent 13332 // expression. 13333 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13334 13335 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13336 // CHECKME: no 'operator' keyword? 13337 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13338 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13339 UnresolvedLookupExpr *Fn 13340 = UnresolvedLookupExpr::Create(Context, NamingClass, 13341 NestedNameSpecifierLoc(), OpNameInfo, 13342 /*ADL*/ true, /*Overloaded*/ false, 13343 UnresolvedSetIterator(), 13344 UnresolvedSetIterator()); 13345 // Can't add any actual overloads yet 13346 13347 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13348 Context.DependentTy, VK_RValue, RLoc, 13349 FPOptions()); 13350 } 13351 13352 // Handle placeholders on both operands. 13353 if (checkPlaceholderForOverload(*this, Args[0])) 13354 return ExprError(); 13355 if (checkPlaceholderForOverload(*this, Args[1])) 13356 return ExprError(); 13357 13358 // Build an empty overload set. 13359 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13360 13361 // Subscript can only be overloaded as a member function. 13362 13363 // Add operator candidates that are member functions. 13364 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13365 13366 // Add builtin operator candidates. 13367 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13368 13369 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13370 13371 // Perform overload resolution. 13372 OverloadCandidateSet::iterator Best; 13373 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13374 case OR_Success: { 13375 // We found a built-in operator or an overloaded operator. 13376 FunctionDecl *FnDecl = Best->Function; 13377 13378 if (FnDecl) { 13379 // We matched an overloaded operator. Build a call to that 13380 // operator. 13381 13382 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13383 13384 // Convert the arguments. 13385 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13386 ExprResult Arg0 = 13387 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13388 Best->FoundDecl, Method); 13389 if (Arg0.isInvalid()) 13390 return ExprError(); 13391 Args[0] = Arg0.get(); 13392 13393 // Convert the arguments. 13394 ExprResult InputInit 13395 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13396 Context, 13397 FnDecl->getParamDecl(0)), 13398 SourceLocation(), 13399 Args[1]); 13400 if (InputInit.isInvalid()) 13401 return ExprError(); 13402 13403 Args[1] = InputInit.getAs<Expr>(); 13404 13405 // Build the actual expression node. 13406 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13407 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13408 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13409 Best->FoundDecl, 13410 Base, 13411 HadMultipleCandidates, 13412 OpLocInfo.getLoc(), 13413 OpLocInfo.getInfo()); 13414 if (FnExpr.isInvalid()) 13415 return ExprError(); 13416 13417 // Determine the result type 13418 QualType ResultTy = FnDecl->getReturnType(); 13419 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13420 ResultTy = ResultTy.getNonLValueExprType(Context); 13421 13422 CXXOperatorCallExpr *TheCall = 13423 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13424 Args, ResultTy, VK, RLoc, FPOptions()); 13425 13426 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13427 return ExprError(); 13428 13429 if (CheckFunctionCall(Method, TheCall, 13430 Method->getType()->castAs<FunctionProtoType>())) 13431 return ExprError(); 13432 13433 return MaybeBindToTemporary(TheCall); 13434 } else { 13435 // We matched a built-in operator. Convert the arguments, then 13436 // break out so that we will build the appropriate built-in 13437 // operator node. 13438 ExprResult ArgsRes0 = PerformImplicitConversion( 13439 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13440 AA_Passing, CCK_ForBuiltinOverloadedOp); 13441 if (ArgsRes0.isInvalid()) 13442 return ExprError(); 13443 Args[0] = ArgsRes0.get(); 13444 13445 ExprResult ArgsRes1 = PerformImplicitConversion( 13446 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13447 AA_Passing, CCK_ForBuiltinOverloadedOp); 13448 if (ArgsRes1.isInvalid()) 13449 return ExprError(); 13450 Args[1] = ArgsRes1.get(); 13451 13452 break; 13453 } 13454 } 13455 13456 case OR_No_Viable_Function: { 13457 PartialDiagnostic PD = CandidateSet.empty() 13458 ? (PDiag(diag::err_ovl_no_oper) 13459 << Args[0]->getType() << /*subscript*/ 0 13460 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13461 : (PDiag(diag::err_ovl_no_viable_subscript) 13462 << Args[0]->getType() << Args[0]->getSourceRange() 13463 << Args[1]->getSourceRange()); 13464 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13465 OCD_AllCandidates, Args, "[]", LLoc); 13466 return ExprError(); 13467 } 13468 13469 case OR_Ambiguous: 13470 CandidateSet.NoteCandidates( 13471 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13472 << "[]" << Args[0]->getType() 13473 << Args[1]->getType() 13474 << Args[0]->getSourceRange() 13475 << Args[1]->getSourceRange()), 13476 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13477 return ExprError(); 13478 13479 case OR_Deleted: 13480 CandidateSet.NoteCandidates( 13481 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13482 << "[]" << Args[0]->getSourceRange() 13483 << Args[1]->getSourceRange()), 13484 *this, OCD_AllCandidates, Args, "[]", LLoc); 13485 return ExprError(); 13486 } 13487 13488 // We matched a built-in operator; build it. 13489 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13490 } 13491 13492 /// BuildCallToMemberFunction - Build a call to a member 13493 /// function. MemExpr is the expression that refers to the member 13494 /// function (and includes the object parameter), Args/NumArgs are the 13495 /// arguments to the function call (not including the object 13496 /// parameter). The caller needs to validate that the member 13497 /// expression refers to a non-static member function or an overloaded 13498 /// member function. 13499 ExprResult 13500 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13501 SourceLocation LParenLoc, 13502 MultiExprArg Args, 13503 SourceLocation RParenLoc) { 13504 assert(MemExprE->getType() == Context.BoundMemberTy || 13505 MemExprE->getType() == Context.OverloadTy); 13506 13507 // Dig out the member expression. This holds both the object 13508 // argument and the member function we're referring to. 13509 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13510 13511 // Determine whether this is a call to a pointer-to-member function. 13512 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13513 assert(op->getType() == Context.BoundMemberTy); 13514 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13515 13516 QualType fnType = 13517 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13518 13519 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13520 QualType resultType = proto->getCallResultType(Context); 13521 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13522 13523 // Check that the object type isn't more qualified than the 13524 // member function we're calling. 13525 Qualifiers funcQuals = proto->getMethodQuals(); 13526 13527 QualType objectType = op->getLHS()->getType(); 13528 if (op->getOpcode() == BO_PtrMemI) 13529 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13530 Qualifiers objectQuals = objectType.getQualifiers(); 13531 13532 Qualifiers difference = objectQuals - funcQuals; 13533 difference.removeObjCGCAttr(); 13534 difference.removeAddressSpace(); 13535 if (difference) { 13536 std::string qualsString = difference.getAsString(); 13537 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13538 << fnType.getUnqualifiedType() 13539 << qualsString 13540 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13541 } 13542 13543 CXXMemberCallExpr *call = 13544 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13545 valueKind, RParenLoc, proto->getNumParams()); 13546 13547 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13548 call, nullptr)) 13549 return ExprError(); 13550 13551 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13552 return ExprError(); 13553 13554 if (CheckOtherCall(call, proto)) 13555 return ExprError(); 13556 13557 return MaybeBindToTemporary(call); 13558 } 13559 13560 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13561 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13562 RParenLoc); 13563 13564 UnbridgedCastsSet UnbridgedCasts; 13565 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13566 return ExprError(); 13567 13568 MemberExpr *MemExpr; 13569 CXXMethodDecl *Method = nullptr; 13570 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13571 NestedNameSpecifier *Qualifier = nullptr; 13572 if (isa<MemberExpr>(NakedMemExpr)) { 13573 MemExpr = cast<MemberExpr>(NakedMemExpr); 13574 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13575 FoundDecl = MemExpr->getFoundDecl(); 13576 Qualifier = MemExpr->getQualifier(); 13577 UnbridgedCasts.restore(); 13578 } else { 13579 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13580 Qualifier = UnresExpr->getQualifier(); 13581 13582 QualType ObjectType = UnresExpr->getBaseType(); 13583 Expr::Classification ObjectClassification 13584 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13585 : UnresExpr->getBase()->Classify(Context); 13586 13587 // Add overload candidates 13588 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13589 OverloadCandidateSet::CSK_Normal); 13590 13591 // FIXME: avoid copy. 13592 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13593 if (UnresExpr->hasExplicitTemplateArgs()) { 13594 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13595 TemplateArgs = &TemplateArgsBuffer; 13596 } 13597 13598 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13599 E = UnresExpr->decls_end(); I != E; ++I) { 13600 13601 NamedDecl *Func = *I; 13602 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13603 if (isa<UsingShadowDecl>(Func)) 13604 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13605 13606 13607 // Microsoft supports direct constructor calls. 13608 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13609 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13610 CandidateSet, 13611 /*SuppressUserConversions*/ false); 13612 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13613 // If explicit template arguments were provided, we can't call a 13614 // non-template member function. 13615 if (TemplateArgs) 13616 continue; 13617 13618 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13619 ObjectClassification, Args, CandidateSet, 13620 /*SuppressUserConversions=*/false); 13621 } else { 13622 AddMethodTemplateCandidate( 13623 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13624 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13625 /*SuppressUserConversions=*/false); 13626 } 13627 } 13628 13629 DeclarationName DeclName = UnresExpr->getMemberName(); 13630 13631 UnbridgedCasts.restore(); 13632 13633 OverloadCandidateSet::iterator Best; 13634 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13635 Best)) { 13636 case OR_Success: 13637 Method = cast<CXXMethodDecl>(Best->Function); 13638 FoundDecl = Best->FoundDecl; 13639 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13640 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13641 return ExprError(); 13642 // If FoundDecl is different from Method (such as if one is a template 13643 // and the other a specialization), make sure DiagnoseUseOfDecl is 13644 // called on both. 13645 // FIXME: This would be more comprehensively addressed by modifying 13646 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13647 // being used. 13648 if (Method != FoundDecl.getDecl() && 13649 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13650 return ExprError(); 13651 break; 13652 13653 case OR_No_Viable_Function: 13654 CandidateSet.NoteCandidates( 13655 PartialDiagnosticAt( 13656 UnresExpr->getMemberLoc(), 13657 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13658 << DeclName << MemExprE->getSourceRange()), 13659 *this, OCD_AllCandidates, Args); 13660 // FIXME: Leaking incoming expressions! 13661 return ExprError(); 13662 13663 case OR_Ambiguous: 13664 CandidateSet.NoteCandidates( 13665 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13666 PDiag(diag::err_ovl_ambiguous_member_call) 13667 << DeclName << MemExprE->getSourceRange()), 13668 *this, OCD_AmbiguousCandidates, Args); 13669 // FIXME: Leaking incoming expressions! 13670 return ExprError(); 13671 13672 case OR_Deleted: 13673 CandidateSet.NoteCandidates( 13674 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13675 PDiag(diag::err_ovl_deleted_member_call) 13676 << DeclName << MemExprE->getSourceRange()), 13677 *this, OCD_AllCandidates, Args); 13678 // FIXME: Leaking incoming expressions! 13679 return ExprError(); 13680 } 13681 13682 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13683 13684 // If overload resolution picked a static member, build a 13685 // non-member call based on that function. 13686 if (Method->isStatic()) { 13687 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13688 RParenLoc); 13689 } 13690 13691 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13692 } 13693 13694 QualType ResultType = Method->getReturnType(); 13695 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13696 ResultType = ResultType.getNonLValueExprType(Context); 13697 13698 assert(Method && "Member call to something that isn't a method?"); 13699 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13700 CXXMemberCallExpr *TheCall = 13701 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13702 RParenLoc, Proto->getNumParams()); 13703 13704 // Check for a valid return type. 13705 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13706 TheCall, Method)) 13707 return ExprError(); 13708 13709 // Convert the object argument (for a non-static member function call). 13710 // We only need to do this if there was actually an overload; otherwise 13711 // it was done at lookup. 13712 if (!Method->isStatic()) { 13713 ExprResult ObjectArg = 13714 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13715 FoundDecl, Method); 13716 if (ObjectArg.isInvalid()) 13717 return ExprError(); 13718 MemExpr->setBase(ObjectArg.get()); 13719 } 13720 13721 // Convert the rest of the arguments 13722 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13723 RParenLoc)) 13724 return ExprError(); 13725 13726 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13727 13728 if (CheckFunctionCall(Method, TheCall, Proto)) 13729 return ExprError(); 13730 13731 // In the case the method to call was not selected by the overloading 13732 // resolution process, we still need to handle the enable_if attribute. Do 13733 // that here, so it will not hide previous -- and more relevant -- errors. 13734 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13735 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13736 Diag(MemE->getMemberLoc(), 13737 diag::err_ovl_no_viable_member_function_in_call) 13738 << Method << Method->getSourceRange(); 13739 Diag(Method->getLocation(), 13740 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13741 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13742 return ExprError(); 13743 } 13744 } 13745 13746 if ((isa<CXXConstructorDecl>(CurContext) || 13747 isa<CXXDestructorDecl>(CurContext)) && 13748 TheCall->getMethodDecl()->isPure()) { 13749 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13750 13751 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13752 MemExpr->performsVirtualDispatch(getLangOpts())) { 13753 Diag(MemExpr->getBeginLoc(), 13754 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13755 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13756 << MD->getParent()->getDeclName(); 13757 13758 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13759 if (getLangOpts().AppleKext) 13760 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13761 << MD->getParent()->getDeclName() << MD->getDeclName(); 13762 } 13763 } 13764 13765 if (CXXDestructorDecl *DD = 13766 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13767 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13768 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13769 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13770 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13771 MemExpr->getMemberLoc()); 13772 } 13773 13774 return MaybeBindToTemporary(TheCall); 13775 } 13776 13777 /// BuildCallToObjectOfClassType - Build a call to an object of class 13778 /// type (C++ [over.call.object]), which can end up invoking an 13779 /// overloaded function call operator (@c operator()) or performing a 13780 /// user-defined conversion on the object argument. 13781 ExprResult 13782 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13783 SourceLocation LParenLoc, 13784 MultiExprArg Args, 13785 SourceLocation RParenLoc) { 13786 if (checkPlaceholderForOverload(*this, Obj)) 13787 return ExprError(); 13788 ExprResult Object = Obj; 13789 13790 UnbridgedCastsSet UnbridgedCasts; 13791 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13792 return ExprError(); 13793 13794 assert(Object.get()->getType()->isRecordType() && 13795 "Requires object type argument"); 13796 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13797 13798 // C++ [over.call.object]p1: 13799 // If the primary-expression E in the function call syntax 13800 // evaluates to a class object of type "cv T", then the set of 13801 // candidate functions includes at least the function call 13802 // operators of T. The function call operators of T are obtained by 13803 // ordinary lookup of the name operator() in the context of 13804 // (E).operator(). 13805 OverloadCandidateSet CandidateSet(LParenLoc, 13806 OverloadCandidateSet::CSK_Operator); 13807 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13808 13809 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13810 diag::err_incomplete_object_call, Object.get())) 13811 return true; 13812 13813 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13814 LookupQualifiedName(R, Record->getDecl()); 13815 R.suppressDiagnostics(); 13816 13817 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13818 Oper != OperEnd; ++Oper) { 13819 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13820 Object.get()->Classify(Context), Args, CandidateSet, 13821 /*SuppressUserConversion=*/false); 13822 } 13823 13824 // C++ [over.call.object]p2: 13825 // In addition, for each (non-explicit in C++0x) conversion function 13826 // declared in T of the form 13827 // 13828 // operator conversion-type-id () cv-qualifier; 13829 // 13830 // where cv-qualifier is the same cv-qualification as, or a 13831 // greater cv-qualification than, cv, and where conversion-type-id 13832 // denotes the type "pointer to function of (P1,...,Pn) returning 13833 // R", or the type "reference to pointer to function of 13834 // (P1,...,Pn) returning R", or the type "reference to function 13835 // of (P1,...,Pn) returning R", a surrogate call function [...] 13836 // is also considered as a candidate function. Similarly, 13837 // surrogate call functions are added to the set of candidate 13838 // functions for each conversion function declared in an 13839 // accessible base class provided the function is not hidden 13840 // within T by another intervening declaration. 13841 const auto &Conversions = 13842 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13843 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13844 NamedDecl *D = *I; 13845 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13846 if (isa<UsingShadowDecl>(D)) 13847 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13848 13849 // Skip over templated conversion functions; they aren't 13850 // surrogates. 13851 if (isa<FunctionTemplateDecl>(D)) 13852 continue; 13853 13854 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13855 if (!Conv->isExplicit()) { 13856 // Strip the reference type (if any) and then the pointer type (if 13857 // any) to get down to what might be a function type. 13858 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13859 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13860 ConvType = ConvPtrType->getPointeeType(); 13861 13862 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13863 { 13864 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13865 Object.get(), Args, CandidateSet); 13866 } 13867 } 13868 } 13869 13870 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13871 13872 // Perform overload resolution. 13873 OverloadCandidateSet::iterator Best; 13874 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13875 Best)) { 13876 case OR_Success: 13877 // Overload resolution succeeded; we'll build the appropriate call 13878 // below. 13879 break; 13880 13881 case OR_No_Viable_Function: { 13882 PartialDiagnostic PD = 13883 CandidateSet.empty() 13884 ? (PDiag(diag::err_ovl_no_oper) 13885 << Object.get()->getType() << /*call*/ 1 13886 << Object.get()->getSourceRange()) 13887 : (PDiag(diag::err_ovl_no_viable_object_call) 13888 << Object.get()->getType() << Object.get()->getSourceRange()); 13889 CandidateSet.NoteCandidates( 13890 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 13891 OCD_AllCandidates, Args); 13892 break; 13893 } 13894 case OR_Ambiguous: 13895 CandidateSet.NoteCandidates( 13896 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13897 PDiag(diag::err_ovl_ambiguous_object_call) 13898 << Object.get()->getType() 13899 << Object.get()->getSourceRange()), 13900 *this, OCD_AmbiguousCandidates, Args); 13901 break; 13902 13903 case OR_Deleted: 13904 CandidateSet.NoteCandidates( 13905 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13906 PDiag(diag::err_ovl_deleted_object_call) 13907 << Object.get()->getType() 13908 << Object.get()->getSourceRange()), 13909 *this, OCD_AllCandidates, Args); 13910 break; 13911 } 13912 13913 if (Best == CandidateSet.end()) 13914 return true; 13915 13916 UnbridgedCasts.restore(); 13917 13918 if (Best->Function == nullptr) { 13919 // Since there is no function declaration, this is one of the 13920 // surrogate candidates. Dig out the conversion function. 13921 CXXConversionDecl *Conv 13922 = cast<CXXConversionDecl>( 13923 Best->Conversions[0].UserDefined.ConversionFunction); 13924 13925 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13926 Best->FoundDecl); 13927 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13928 return ExprError(); 13929 assert(Conv == Best->FoundDecl.getDecl() && 13930 "Found Decl & conversion-to-functionptr should be same, right?!"); 13931 // We selected one of the surrogate functions that converts the 13932 // object parameter to a function pointer. Perform the conversion 13933 // on the object argument, then let BuildCallExpr finish the job. 13934 13935 // Create an implicit member expr to refer to the conversion operator. 13936 // and then call it. 13937 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13938 Conv, HadMultipleCandidates); 13939 if (Call.isInvalid()) 13940 return ExprError(); 13941 // Record usage of conversion in an implicit cast. 13942 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13943 CK_UserDefinedConversion, Call.get(), 13944 nullptr, VK_RValue); 13945 13946 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13947 } 13948 13949 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13950 13951 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13952 // that calls this method, using Object for the implicit object 13953 // parameter and passing along the remaining arguments. 13954 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13955 13956 // An error diagnostic has already been printed when parsing the declaration. 13957 if (Method->isInvalidDecl()) 13958 return ExprError(); 13959 13960 const FunctionProtoType *Proto = 13961 Method->getType()->getAs<FunctionProtoType>(); 13962 13963 unsigned NumParams = Proto->getNumParams(); 13964 13965 DeclarationNameInfo OpLocInfo( 13966 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13967 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13968 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13969 Obj, HadMultipleCandidates, 13970 OpLocInfo.getLoc(), 13971 OpLocInfo.getInfo()); 13972 if (NewFn.isInvalid()) 13973 return true; 13974 13975 // The number of argument slots to allocate in the call. If we have default 13976 // arguments we need to allocate space for them as well. We additionally 13977 // need one more slot for the object parameter. 13978 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13979 13980 // Build the full argument list for the method call (the implicit object 13981 // parameter is placed at the beginning of the list). 13982 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13983 13984 bool IsError = false; 13985 13986 // Initialize the implicit object parameter. 13987 ExprResult ObjRes = 13988 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13989 Best->FoundDecl, Method); 13990 if (ObjRes.isInvalid()) 13991 IsError = true; 13992 else 13993 Object = ObjRes; 13994 MethodArgs[0] = Object.get(); 13995 13996 // Check the argument types. 13997 for (unsigned i = 0; i != NumParams; i++) { 13998 Expr *Arg; 13999 if (i < Args.size()) { 14000 Arg = Args[i]; 14001 14002 // Pass the argument. 14003 14004 ExprResult InputInit 14005 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14006 Context, 14007 Method->getParamDecl(i)), 14008 SourceLocation(), Arg); 14009 14010 IsError |= InputInit.isInvalid(); 14011 Arg = InputInit.getAs<Expr>(); 14012 } else { 14013 ExprResult DefArg 14014 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14015 if (DefArg.isInvalid()) { 14016 IsError = true; 14017 break; 14018 } 14019 14020 Arg = DefArg.getAs<Expr>(); 14021 } 14022 14023 MethodArgs[i + 1] = Arg; 14024 } 14025 14026 // If this is a variadic call, handle args passed through "...". 14027 if (Proto->isVariadic()) { 14028 // Promote the arguments (C99 6.5.2.2p7). 14029 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14030 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14031 nullptr); 14032 IsError |= Arg.isInvalid(); 14033 MethodArgs[i + 1] = Arg.get(); 14034 } 14035 } 14036 14037 if (IsError) 14038 return true; 14039 14040 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14041 14042 // Once we've built TheCall, all of the expressions are properly owned. 14043 QualType ResultTy = Method->getReturnType(); 14044 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14045 ResultTy = ResultTy.getNonLValueExprType(Context); 14046 14047 CXXOperatorCallExpr *TheCall = 14048 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14049 ResultTy, VK, RParenLoc, FPOptions()); 14050 14051 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14052 return true; 14053 14054 if (CheckFunctionCall(Method, TheCall, Proto)) 14055 return true; 14056 14057 return MaybeBindToTemporary(TheCall); 14058 } 14059 14060 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14061 /// (if one exists), where @c Base is an expression of class type and 14062 /// @c Member is the name of the member we're trying to find. 14063 ExprResult 14064 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14065 bool *NoArrowOperatorFound) { 14066 assert(Base->getType()->isRecordType() && 14067 "left-hand side must have class type"); 14068 14069 if (checkPlaceholderForOverload(*this, Base)) 14070 return ExprError(); 14071 14072 SourceLocation Loc = Base->getExprLoc(); 14073 14074 // C++ [over.ref]p1: 14075 // 14076 // [...] An expression x->m is interpreted as (x.operator->())->m 14077 // for a class object x of type T if T::operator->() exists and if 14078 // the operator is selected as the best match function by the 14079 // overload resolution mechanism (13.3). 14080 DeclarationName OpName = 14081 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14082 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14083 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 14084 14085 if (RequireCompleteType(Loc, Base->getType(), 14086 diag::err_typecheck_incomplete_tag, Base)) 14087 return ExprError(); 14088 14089 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14090 LookupQualifiedName(R, BaseRecord->getDecl()); 14091 R.suppressDiagnostics(); 14092 14093 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14094 Oper != OperEnd; ++Oper) { 14095 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14096 None, CandidateSet, /*SuppressUserConversion=*/false); 14097 } 14098 14099 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14100 14101 // Perform overload resolution. 14102 OverloadCandidateSet::iterator Best; 14103 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14104 case OR_Success: 14105 // Overload resolution succeeded; we'll build the call below. 14106 break; 14107 14108 case OR_No_Viable_Function: { 14109 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14110 if (CandidateSet.empty()) { 14111 QualType BaseType = Base->getType(); 14112 if (NoArrowOperatorFound) { 14113 // Report this specific error to the caller instead of emitting a 14114 // diagnostic, as requested. 14115 *NoArrowOperatorFound = true; 14116 return ExprError(); 14117 } 14118 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14119 << BaseType << Base->getSourceRange(); 14120 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14121 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14122 << FixItHint::CreateReplacement(OpLoc, "."); 14123 } 14124 } else 14125 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14126 << "operator->" << Base->getSourceRange(); 14127 CandidateSet.NoteCandidates(*this, Base, Cands); 14128 return ExprError(); 14129 } 14130 case OR_Ambiguous: 14131 CandidateSet.NoteCandidates( 14132 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14133 << "->" << Base->getType() 14134 << Base->getSourceRange()), 14135 *this, OCD_AmbiguousCandidates, Base); 14136 return ExprError(); 14137 14138 case OR_Deleted: 14139 CandidateSet.NoteCandidates( 14140 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14141 << "->" << Base->getSourceRange()), 14142 *this, OCD_AllCandidates, Base); 14143 return ExprError(); 14144 } 14145 14146 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14147 14148 // Convert the object parameter. 14149 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14150 ExprResult BaseResult = 14151 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14152 Best->FoundDecl, Method); 14153 if (BaseResult.isInvalid()) 14154 return ExprError(); 14155 Base = BaseResult.get(); 14156 14157 // Build the operator call. 14158 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14159 Base, HadMultipleCandidates, OpLoc); 14160 if (FnExpr.isInvalid()) 14161 return ExprError(); 14162 14163 QualType ResultTy = Method->getReturnType(); 14164 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14165 ResultTy = ResultTy.getNonLValueExprType(Context); 14166 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14167 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 14168 14169 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14170 return ExprError(); 14171 14172 if (CheckFunctionCall(Method, TheCall, 14173 Method->getType()->castAs<FunctionProtoType>())) 14174 return ExprError(); 14175 14176 return MaybeBindToTemporary(TheCall); 14177 } 14178 14179 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14180 /// a literal operator described by the provided lookup results. 14181 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14182 DeclarationNameInfo &SuffixInfo, 14183 ArrayRef<Expr*> Args, 14184 SourceLocation LitEndLoc, 14185 TemplateArgumentListInfo *TemplateArgs) { 14186 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14187 14188 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14189 OverloadCandidateSet::CSK_Normal); 14190 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14191 TemplateArgs); 14192 14193 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14194 14195 // Perform overload resolution. This will usually be trivial, but might need 14196 // to perform substitutions for a literal operator template. 14197 OverloadCandidateSet::iterator Best; 14198 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14199 case OR_Success: 14200 case OR_Deleted: 14201 break; 14202 14203 case OR_No_Viable_Function: 14204 CandidateSet.NoteCandidates( 14205 PartialDiagnosticAt(UDSuffixLoc, 14206 PDiag(diag::err_ovl_no_viable_function_in_call) 14207 << R.getLookupName()), 14208 *this, OCD_AllCandidates, Args); 14209 return ExprError(); 14210 14211 case OR_Ambiguous: 14212 CandidateSet.NoteCandidates( 14213 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14214 << R.getLookupName()), 14215 *this, OCD_AmbiguousCandidates, Args); 14216 return ExprError(); 14217 } 14218 14219 FunctionDecl *FD = Best->Function; 14220 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14221 nullptr, HadMultipleCandidates, 14222 SuffixInfo.getLoc(), 14223 SuffixInfo.getInfo()); 14224 if (Fn.isInvalid()) 14225 return true; 14226 14227 // Check the argument types. This should almost always be a no-op, except 14228 // that array-to-pointer decay is applied to string literals. 14229 Expr *ConvArgs[2]; 14230 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14231 ExprResult InputInit = PerformCopyInitialization( 14232 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14233 SourceLocation(), Args[ArgIdx]); 14234 if (InputInit.isInvalid()) 14235 return true; 14236 ConvArgs[ArgIdx] = InputInit.get(); 14237 } 14238 14239 QualType ResultTy = FD->getReturnType(); 14240 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14241 ResultTy = ResultTy.getNonLValueExprType(Context); 14242 14243 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14244 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14245 VK, LitEndLoc, UDSuffixLoc); 14246 14247 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14248 return ExprError(); 14249 14250 if (CheckFunctionCall(FD, UDL, nullptr)) 14251 return ExprError(); 14252 14253 return MaybeBindToTemporary(UDL); 14254 } 14255 14256 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14257 /// given LookupResult is non-empty, it is assumed to describe a member which 14258 /// will be invoked. Otherwise, the function will be found via argument 14259 /// dependent lookup. 14260 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14261 /// otherwise CallExpr is set to ExprError() and some non-success value 14262 /// is returned. 14263 Sema::ForRangeStatus 14264 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14265 SourceLocation RangeLoc, 14266 const DeclarationNameInfo &NameInfo, 14267 LookupResult &MemberLookup, 14268 OverloadCandidateSet *CandidateSet, 14269 Expr *Range, ExprResult *CallExpr) { 14270 Scope *S = nullptr; 14271 14272 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14273 if (!MemberLookup.empty()) { 14274 ExprResult MemberRef = 14275 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14276 /*IsPtr=*/false, CXXScopeSpec(), 14277 /*TemplateKWLoc=*/SourceLocation(), 14278 /*FirstQualifierInScope=*/nullptr, 14279 MemberLookup, 14280 /*TemplateArgs=*/nullptr, S); 14281 if (MemberRef.isInvalid()) { 14282 *CallExpr = ExprError(); 14283 return FRS_DiagnosticIssued; 14284 } 14285 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14286 if (CallExpr->isInvalid()) { 14287 *CallExpr = ExprError(); 14288 return FRS_DiagnosticIssued; 14289 } 14290 } else { 14291 UnresolvedSet<0> FoundNames; 14292 UnresolvedLookupExpr *Fn = 14293 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14294 NestedNameSpecifierLoc(), NameInfo, 14295 /*NeedsADL=*/true, /*Overloaded=*/false, 14296 FoundNames.begin(), FoundNames.end()); 14297 14298 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14299 CandidateSet, CallExpr); 14300 if (CandidateSet->empty() || CandidateSetError) { 14301 *CallExpr = ExprError(); 14302 return FRS_NoViableFunction; 14303 } 14304 OverloadCandidateSet::iterator Best; 14305 OverloadingResult OverloadResult = 14306 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14307 14308 if (OverloadResult == OR_No_Viable_Function) { 14309 *CallExpr = ExprError(); 14310 return FRS_NoViableFunction; 14311 } 14312 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14313 Loc, nullptr, CandidateSet, &Best, 14314 OverloadResult, 14315 /*AllowTypoCorrection=*/false); 14316 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14317 *CallExpr = ExprError(); 14318 return FRS_DiagnosticIssued; 14319 } 14320 } 14321 return FRS_Success; 14322 } 14323 14324 14325 /// FixOverloadedFunctionReference - E is an expression that refers to 14326 /// a C++ overloaded function (possibly with some parentheses and 14327 /// perhaps a '&' around it). We have resolved the overloaded function 14328 /// to the function declaration Fn, so patch up the expression E to 14329 /// refer (possibly indirectly) to Fn. Returns the new expr. 14330 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14331 FunctionDecl *Fn) { 14332 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14333 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14334 Found, Fn); 14335 if (SubExpr == PE->getSubExpr()) 14336 return PE; 14337 14338 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14339 } 14340 14341 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14342 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14343 Found, Fn); 14344 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14345 SubExpr->getType()) && 14346 "Implicit cast type cannot be determined from overload"); 14347 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14348 if (SubExpr == ICE->getSubExpr()) 14349 return ICE; 14350 14351 return ImplicitCastExpr::Create(Context, ICE->getType(), 14352 ICE->getCastKind(), 14353 SubExpr, nullptr, 14354 ICE->getValueKind()); 14355 } 14356 14357 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14358 if (!GSE->isResultDependent()) { 14359 Expr *SubExpr = 14360 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14361 if (SubExpr == GSE->getResultExpr()) 14362 return GSE; 14363 14364 // Replace the resulting type information before rebuilding the generic 14365 // selection expression. 14366 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14367 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14368 unsigned ResultIdx = GSE->getResultIndex(); 14369 AssocExprs[ResultIdx] = SubExpr; 14370 14371 return GenericSelectionExpr::Create( 14372 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14373 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14374 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14375 ResultIdx); 14376 } 14377 // Rather than fall through to the unreachable, return the original generic 14378 // selection expression. 14379 return GSE; 14380 } 14381 14382 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14383 assert(UnOp->getOpcode() == UO_AddrOf && 14384 "Can only take the address of an overloaded function"); 14385 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14386 if (Method->isStatic()) { 14387 // Do nothing: static member functions aren't any different 14388 // from non-member functions. 14389 } else { 14390 // Fix the subexpression, which really has to be an 14391 // UnresolvedLookupExpr holding an overloaded member function 14392 // or template. 14393 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14394 Found, Fn); 14395 if (SubExpr == UnOp->getSubExpr()) 14396 return UnOp; 14397 14398 assert(isa<DeclRefExpr>(SubExpr) 14399 && "fixed to something other than a decl ref"); 14400 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14401 && "fixed to a member ref with no nested name qualifier"); 14402 14403 // We have taken the address of a pointer to member 14404 // function. Perform the computation here so that we get the 14405 // appropriate pointer to member type. 14406 QualType ClassType 14407 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14408 QualType MemPtrType 14409 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14410 // Under the MS ABI, lock down the inheritance model now. 14411 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14412 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14413 14414 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 14415 VK_RValue, OK_Ordinary, 14416 UnOp->getOperatorLoc(), false); 14417 } 14418 } 14419 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14420 Found, Fn); 14421 if (SubExpr == UnOp->getSubExpr()) 14422 return UnOp; 14423 14424 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 14425 Context.getPointerType(SubExpr->getType()), 14426 VK_RValue, OK_Ordinary, 14427 UnOp->getOperatorLoc(), false); 14428 } 14429 14430 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14431 // FIXME: avoid copy. 14432 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14433 if (ULE->hasExplicitTemplateArgs()) { 14434 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14435 TemplateArgs = &TemplateArgsBuffer; 14436 } 14437 14438 DeclRefExpr *DRE = 14439 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14440 ULE->getQualifierLoc(), Found.getDecl(), 14441 ULE->getTemplateKeywordLoc(), TemplateArgs); 14442 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14443 return DRE; 14444 } 14445 14446 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14447 // FIXME: avoid copy. 14448 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14449 if (MemExpr->hasExplicitTemplateArgs()) { 14450 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14451 TemplateArgs = &TemplateArgsBuffer; 14452 } 14453 14454 Expr *Base; 14455 14456 // If we're filling in a static method where we used to have an 14457 // implicit member access, rewrite to a simple decl ref. 14458 if (MemExpr->isImplicitAccess()) { 14459 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14460 DeclRefExpr *DRE = BuildDeclRefExpr( 14461 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14462 MemExpr->getQualifierLoc(), Found.getDecl(), 14463 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14464 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14465 return DRE; 14466 } else { 14467 SourceLocation Loc = MemExpr->getMemberLoc(); 14468 if (MemExpr->getQualifier()) 14469 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14470 Base = 14471 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14472 } 14473 } else 14474 Base = MemExpr->getBase(); 14475 14476 ExprValueKind valueKind; 14477 QualType type; 14478 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14479 valueKind = VK_LValue; 14480 type = Fn->getType(); 14481 } else { 14482 valueKind = VK_RValue; 14483 type = Context.BoundMemberTy; 14484 } 14485 14486 return BuildMemberExpr( 14487 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14488 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14489 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14490 type, valueKind, OK_Ordinary, TemplateArgs); 14491 } 14492 14493 llvm_unreachable("Invalid reference to overloaded function"); 14494 } 14495 14496 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14497 DeclAccessPair Found, 14498 FunctionDecl *Fn) { 14499 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14500 } 14501