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 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 64 S.ResolveExceptionSpec(Loc, FPT); 65 DeclRefExpr *DRE = new (S.Context) 66 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE, Base); 71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 72 CK_FunctionToPointerDecay); 73 } 74 75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 76 bool InOverloadResolution, 77 StandardConversionSequence &SCS, 78 bool CStyle, 79 bool AllowObjCWritebackConversion); 80 81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 82 QualType &ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle); 86 static OverloadingResult 87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 88 UserDefinedConversionSequence& User, 89 OverloadCandidateSet& Conversions, 90 bool AllowExplicit, 91 bool AllowObjCConversionOnExplicit); 92 93 94 static ImplicitConversionSequence::CompareKind 95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareQualificationConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 /// GetConversionRank - Retrieve the implicit conversion rank 110 /// corresponding to the given implicit conversion kind. 111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 112 static const ImplicitConversionRank 113 Rank[(int)ICK_Num_Conversion_Kinds] = { 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Promotion, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_OCL_Scalar_Widening, 134 ICR_Complex_Real_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Writeback_Conversion, 138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 139 // it was omitted by the patch that added 140 // ICK_Zero_Event_Conversion 141 ICR_C_Conversion, 142 ICR_C_Conversion_Extension 143 }; 144 return Rank[(int)Kind]; 145 } 146 147 /// GetImplicitConversionName - Return the name of this kind of 148 /// implicit conversion. 149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 151 "No conversion", 152 "Lvalue-to-rvalue", 153 "Array-to-pointer", 154 "Function-to-pointer", 155 "Function pointer conversion", 156 "Qualification", 157 "Integral promotion", 158 "Floating point promotion", 159 "Complex promotion", 160 "Integral conversion", 161 "Floating conversion", 162 "Complex conversion", 163 "Floating-integral conversion", 164 "Pointer conversion", 165 "Pointer-to-member conversion", 166 "Boolean conversion", 167 "Compatible-types conversion", 168 "Derived-to-base conversion", 169 "Vector conversion", 170 "Vector splat", 171 "Complex-real conversion", 172 "Block Pointer conversion", 173 "Transparent Union Conversion", 174 "Writeback conversion", 175 "OpenCL Zero Event Conversion", 176 "C specific type conversion", 177 "Incompatible pointer conversion" 178 }; 179 return Name[Kind]; 180 } 181 182 /// StandardConversionSequence - Set the standard conversion 183 /// sequence to the identity conversion. 184 void StandardConversionSequence::setAsIdentityConversion() { 185 First = ICK_Identity; 186 Second = ICK_Identity; 187 Third = ICK_Identity; 188 DeprecatedStringLiteralToCharPtr = false; 189 QualificationIncludesObjCLifetime = false; 190 ReferenceBinding = false; 191 DirectBinding = false; 192 IsLvalueReference = true; 193 BindsToFunctionLvalue = false; 194 BindsToRvalue = false; 195 BindsImplicitObjectArgumentWithoutRefQualifier = false; 196 ObjCLifetimeConversionBinding = false; 197 CopyConstructor = nullptr; 198 } 199 200 /// getRank - Retrieve the rank of this standard conversion sequence 201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 202 /// implicit conversions. 203 ImplicitConversionRank StandardConversionSequence::getRank() const { 204 ImplicitConversionRank Rank = ICR_Exact_Match; 205 if (GetConversionRank(First) > Rank) 206 Rank = GetConversionRank(First); 207 if (GetConversionRank(Second) > Rank) 208 Rank = GetConversionRank(Second); 209 if (GetConversionRank(Third) > Rank) 210 Rank = GetConversionRank(Third); 211 return Rank; 212 } 213 214 /// isPointerConversionToBool - Determines whether this conversion is 215 /// a conversion of a pointer or pointer-to-member to bool. This is 216 /// used as part of the ranking of standard conversion sequences 217 /// (C++ 13.3.3.2p4). 218 bool StandardConversionSequence::isPointerConversionToBool() const { 219 // Note that FromType has not necessarily been transformed by the 220 // array-to-pointer or function-to-pointer implicit conversions, so 221 // check for their presence as well as checking whether FromType is 222 // a pointer. 223 if (getToType(1)->isBooleanType() && 224 (getFromType()->isPointerType() || 225 getFromType()->isMemberPointerType() || 226 getFromType()->isObjCObjectPointerType() || 227 getFromType()->isBlockPointerType() || 228 getFromType()->isNullPtrType() || 229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 230 return true; 231 232 return false; 233 } 234 235 /// isPointerConversionToVoidPointer - Determines whether this 236 /// conversion is a conversion of a pointer to a void pointer. This is 237 /// used as part of the ranking of standard conversion sequences (C++ 238 /// 13.3.3.2p4). 239 bool 240 StandardConversionSequence:: 241 isPointerConversionToVoidPointer(ASTContext& Context) const { 242 QualType FromType = getFromType(); 243 QualType ToType = getToType(1); 244 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer implicit conversion, so check for its presence 247 // and redo the conversion to get a pointer. 248 if (First == ICK_Array_To_Pointer) 249 FromType = Context.getArrayDecayedType(FromType); 250 251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 253 return ToPtrType->getPointeeType()->isVoidType(); 254 255 return false; 256 } 257 258 /// Skip any implicit casts which could be either part of a narrowing conversion 259 /// or after one in an implicit conversion. 260 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 261 const Expr *Converted) { 262 // We can have cleanups wrapping the converted expression; these need to be 263 // preserved so that destructors run if necessary. 264 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 265 Expr *Inner = 266 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 267 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 268 EWC->getObjects()); 269 } 270 271 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 272 switch (ICE->getCastKind()) { 273 case CK_NoOp: 274 case CK_IntegralCast: 275 case CK_IntegralToBoolean: 276 case CK_IntegralToFloating: 277 case CK_BooleanToSignedIntegral: 278 case CK_FloatingToIntegral: 279 case CK_FloatingToBoolean: 280 case CK_FloatingCast: 281 Converted = ICE->getSubExpr(); 282 continue; 283 284 default: 285 return Converted; 286 } 287 } 288 289 return Converted; 290 } 291 292 /// Check if this standard conversion sequence represents a narrowing 293 /// conversion, according to C++11 [dcl.init.list]p7. 294 /// 295 /// \param Ctx The AST context. 296 /// \param Converted The result of applying this standard conversion sequence. 297 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 298 /// value of the expression prior to the narrowing conversion. 299 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 300 /// type of the expression prior to the narrowing conversion. 301 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 302 /// from floating point types to integral types should be ignored. 303 NarrowingKind StandardConversionSequence::getNarrowingKind( 304 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 305 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 306 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 307 308 // C++11 [dcl.init.list]p7: 309 // A narrowing conversion is an implicit conversion ... 310 QualType FromType = getToType(0); 311 QualType ToType = getToType(1); 312 313 // A conversion to an enumeration type is narrowing if the conversion to 314 // the underlying type is narrowing. This only arises for expressions of 315 // the form 'Enum{init}'. 316 if (auto *ET = ToType->getAs<EnumType>()) 317 ToType = ET->getDecl()->getIntegerType(); 318 319 switch (Second) { 320 // 'bool' is an integral type; dispatch to the right place to handle it. 321 case ICK_Boolean_Conversion: 322 if (FromType->isRealFloatingType()) 323 goto FloatingIntegralConversion; 324 if (FromType->isIntegralOrUnscopedEnumerationType()) 325 goto IntegralConversion; 326 // Boolean conversions can be from pointers and pointers to members 327 // [conv.bool], and those aren't considered narrowing conversions. 328 return NK_Not_Narrowing; 329 330 // -- from a floating-point type to an integer type, or 331 // 332 // -- from an integer type or unscoped enumeration type to a floating-point 333 // type, except where the source is a constant expression and the actual 334 // value after conversion will fit into the target type and will produce 335 // the original value when converted back to the original type, or 336 case ICK_Floating_Integral: 337 FloatingIntegralConversion: 338 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 339 return NK_Type_Narrowing; 340 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 341 ToType->isRealFloatingType()) { 342 if (IgnoreFloatToIntegralConversion) 343 return NK_Not_Narrowing; 344 llvm::APSInt IntConstantValue; 345 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 346 assert(Initializer && "Unknown conversion expression"); 347 348 // If it's value-dependent, we can't tell whether it's narrowing. 349 if (Initializer->isValueDependent()) 350 return NK_Dependent_Narrowing; 351 352 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 353 // Convert the integer to the floating type. 354 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 355 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 356 llvm::APFloat::rmNearestTiesToEven); 357 // And back. 358 llvm::APSInt ConvertedValue = IntConstantValue; 359 bool ignored; 360 Result.convertToInteger(ConvertedValue, 361 llvm::APFloat::rmTowardZero, &ignored); 362 // If the resulting value is different, this was a narrowing conversion. 363 if (IntConstantValue != ConvertedValue) { 364 ConstantValue = APValue(IntConstantValue); 365 ConstantType = Initializer->getType(); 366 return NK_Constant_Narrowing; 367 } 368 } else { 369 // Variables are always narrowings. 370 return NK_Variable_Narrowing; 371 } 372 } 373 return NK_Not_Narrowing; 374 375 // -- from long double to double or float, or from double to float, except 376 // where the source is a constant expression and the actual value after 377 // conversion is within the range of values that can be represented (even 378 // if it cannot be represented exactly), or 379 case ICK_Floating_Conversion: 380 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 381 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 382 // FromType is larger than ToType. 383 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 384 385 // If it's value-dependent, we can't tell whether it's narrowing. 386 if (Initializer->isValueDependent()) 387 return NK_Dependent_Narrowing; 388 389 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 390 // Constant! 391 assert(ConstantValue.isFloat()); 392 llvm::APFloat FloatVal = ConstantValue.getFloat(); 393 // Convert the source value into the target type. 394 bool ignored; 395 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 396 Ctx.getFloatTypeSemantics(ToType), 397 llvm::APFloat::rmNearestTiesToEven, &ignored); 398 // If there was no overflow, the source value is within the range of 399 // values that can be represented. 400 if (ConvertStatus & llvm::APFloat::opOverflow) { 401 ConstantType = Initializer->getType(); 402 return NK_Constant_Narrowing; 403 } 404 } else { 405 return NK_Variable_Narrowing; 406 } 407 } 408 return NK_Not_Narrowing; 409 410 // -- from an integer type or unscoped enumeration type to an integer type 411 // that cannot represent all the values of the original type, except where 412 // the source is a constant expression and the actual value after 413 // conversion will fit into the target type and will produce the original 414 // value when converted back to the original type. 415 case ICK_Integral_Conversion: 416 IntegralConversion: { 417 assert(FromType->isIntegralOrUnscopedEnumerationType()); 418 assert(ToType->isIntegralOrUnscopedEnumerationType()); 419 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 420 const unsigned FromWidth = Ctx.getIntWidth(FromType); 421 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 422 const unsigned ToWidth = Ctx.getIntWidth(ToType); 423 424 if (FromWidth > ToWidth || 425 (FromWidth == ToWidth && FromSigned != ToSigned) || 426 (FromSigned && !ToSigned)) { 427 // Not all values of FromType can be represented in ToType. 428 llvm::APSInt InitializerValue; 429 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 430 431 // If it's value-dependent, we can't tell whether it's narrowing. 432 if (Initializer->isValueDependent()) 433 return NK_Dependent_Narrowing; 434 435 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 436 // Such conversions on variables are always narrowing. 437 return NK_Variable_Narrowing; 438 } 439 bool Narrowing = false; 440 if (FromWidth < ToWidth) { 441 // Negative -> unsigned is narrowing. Otherwise, more bits is never 442 // narrowing. 443 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 444 Narrowing = true; 445 } else { 446 // Add a bit to the InitializerValue so we don't have to worry about 447 // signed vs. unsigned comparisons. 448 InitializerValue = InitializerValue.extend( 449 InitializerValue.getBitWidth() + 1); 450 // Convert the initializer to and from the target width and signed-ness. 451 llvm::APSInt ConvertedValue = InitializerValue; 452 ConvertedValue = ConvertedValue.trunc(ToWidth); 453 ConvertedValue.setIsSigned(ToSigned); 454 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 455 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 456 // If the result is different, this was a narrowing conversion. 457 if (ConvertedValue != InitializerValue) 458 Narrowing = true; 459 } 460 if (Narrowing) { 461 ConstantType = Initializer->getType(); 462 ConstantValue = APValue(InitializerValue); 463 return NK_Constant_Narrowing; 464 } 465 } 466 return NK_Not_Narrowing; 467 } 468 469 default: 470 // Other kinds of conversions are not narrowings. 471 return NK_Not_Narrowing; 472 } 473 } 474 475 /// dump - Print this standard conversion sequence to standard 476 /// error. Useful for debugging overloading issues. 477 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 478 raw_ostream &OS = llvm::errs(); 479 bool PrintedSomething = false; 480 if (First != ICK_Identity) { 481 OS << GetImplicitConversionName(First); 482 PrintedSomething = true; 483 } 484 485 if (Second != ICK_Identity) { 486 if (PrintedSomething) { 487 OS << " -> "; 488 } 489 OS << GetImplicitConversionName(Second); 490 491 if (CopyConstructor) { 492 OS << " (by copy constructor)"; 493 } else if (DirectBinding) { 494 OS << " (direct reference binding)"; 495 } else if (ReferenceBinding) { 496 OS << " (reference binding)"; 497 } 498 PrintedSomething = true; 499 } 500 501 if (Third != ICK_Identity) { 502 if (PrintedSomething) { 503 OS << " -> "; 504 } 505 OS << GetImplicitConversionName(Third); 506 PrintedSomething = true; 507 } 508 509 if (!PrintedSomething) { 510 OS << "No conversions required"; 511 } 512 } 513 514 /// dump - Print this user-defined conversion sequence to standard 515 /// error. Useful for debugging overloading issues. 516 void UserDefinedConversionSequence::dump() const { 517 raw_ostream &OS = llvm::errs(); 518 if (Before.First || Before.Second || Before.Third) { 519 Before.dump(); 520 OS << " -> "; 521 } 522 if (ConversionFunction) 523 OS << '\'' << *ConversionFunction << '\''; 524 else 525 OS << "aggregate initialization"; 526 if (After.First || After.Second || After.Third) { 527 OS << " -> "; 528 After.dump(); 529 } 530 } 531 532 /// dump - Print this implicit conversion sequence to standard 533 /// error. Useful for debugging overloading issues. 534 void ImplicitConversionSequence::dump() const { 535 raw_ostream &OS = llvm::errs(); 536 if (isStdInitializerListElement()) 537 OS << "Worst std::initializer_list element conversion: "; 538 switch (ConversionKind) { 539 case StandardConversion: 540 OS << "Standard conversion: "; 541 Standard.dump(); 542 break; 543 case UserDefinedConversion: 544 OS << "User-defined conversion: "; 545 UserDefined.dump(); 546 break; 547 case EllipsisConversion: 548 OS << "Ellipsis conversion"; 549 break; 550 case AmbiguousConversion: 551 OS << "Ambiguous conversion"; 552 break; 553 case BadConversion: 554 OS << "Bad conversion"; 555 break; 556 } 557 558 OS << "\n"; 559 } 560 561 void AmbiguousConversionSequence::construct() { 562 new (&conversions()) ConversionSet(); 563 } 564 565 void AmbiguousConversionSequence::destruct() { 566 conversions().~ConversionSet(); 567 } 568 569 void 570 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 571 FromTypePtr = O.FromTypePtr; 572 ToTypePtr = O.ToTypePtr; 573 new (&conversions()) ConversionSet(O.conversions()); 574 } 575 576 namespace { 577 // Structure used by DeductionFailureInfo to store 578 // template argument information. 579 struct DFIArguments { 580 TemplateArgument FirstArg; 581 TemplateArgument SecondArg; 582 }; 583 // Structure used by DeductionFailureInfo to store 584 // template parameter and template argument information. 585 struct DFIParamWithArguments : DFIArguments { 586 TemplateParameter Param; 587 }; 588 // Structure used by DeductionFailureInfo to store template argument 589 // information and the index of the problematic call argument. 590 struct DFIDeducedMismatchArgs : DFIArguments { 591 TemplateArgumentList *TemplateArgs; 592 unsigned CallArgIndex; 593 }; 594 } 595 596 /// Convert from Sema's representation of template deduction information 597 /// to the form used in overload-candidate information. 598 DeductionFailureInfo 599 clang::MakeDeductionFailureInfo(ASTContext &Context, 600 Sema::TemplateDeductionResult TDK, 601 TemplateDeductionInfo &Info) { 602 DeductionFailureInfo Result; 603 Result.Result = static_cast<unsigned>(TDK); 604 Result.HasDiagnostic = false; 605 switch (TDK) { 606 case Sema::TDK_Invalid: 607 case Sema::TDK_InstantiationDepth: 608 case Sema::TDK_TooManyArguments: 609 case Sema::TDK_TooFewArguments: 610 case Sema::TDK_MiscellaneousDeductionFailure: 611 case Sema::TDK_CUDATargetMismatch: 612 Result.Data = nullptr; 613 break; 614 615 case Sema::TDK_Incomplete: 616 case Sema::TDK_InvalidExplicitArguments: 617 Result.Data = Info.Param.getOpaqueValue(); 618 break; 619 620 case Sema::TDK_DeducedMismatch: 621 case Sema::TDK_DeducedMismatchNested: { 622 // FIXME: Should allocate from normal heap so that we can free this later. 623 auto *Saved = new (Context) DFIDeducedMismatchArgs; 624 Saved->FirstArg = Info.FirstArg; 625 Saved->SecondArg = Info.SecondArg; 626 Saved->TemplateArgs = Info.take(); 627 Saved->CallArgIndex = Info.CallArgIndex; 628 Result.Data = Saved; 629 break; 630 } 631 632 case Sema::TDK_NonDeducedMismatch: { 633 // FIXME: Should allocate from normal heap so that we can free this later. 634 DFIArguments *Saved = new (Context) DFIArguments; 635 Saved->FirstArg = Info.FirstArg; 636 Saved->SecondArg = Info.SecondArg; 637 Result.Data = Saved; 638 break; 639 } 640 641 case Sema::TDK_IncompletePack: 642 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 643 case Sema::TDK_Inconsistent: 644 case Sema::TDK_Underqualified: { 645 // FIXME: Should allocate from normal heap so that we can free this later. 646 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 647 Saved->Param = Info.Param; 648 Saved->FirstArg = Info.FirstArg; 649 Saved->SecondArg = Info.SecondArg; 650 Result.Data = Saved; 651 break; 652 } 653 654 case Sema::TDK_SubstitutionFailure: 655 Result.Data = Info.take(); 656 if (Info.hasSFINAEDiagnostic()) { 657 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 658 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 659 Info.takeSFINAEDiagnostic(*Diag); 660 Result.HasDiagnostic = true; 661 } 662 break; 663 664 case Sema::TDK_Success: 665 case Sema::TDK_NonDependentConversionFailure: 666 llvm_unreachable("not a deduction failure"); 667 } 668 669 return Result; 670 } 671 672 void DeductionFailureInfo::Destroy() { 673 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 674 case Sema::TDK_Success: 675 case Sema::TDK_Invalid: 676 case Sema::TDK_InstantiationDepth: 677 case Sema::TDK_Incomplete: 678 case Sema::TDK_TooManyArguments: 679 case Sema::TDK_TooFewArguments: 680 case Sema::TDK_InvalidExplicitArguments: 681 case Sema::TDK_CUDATargetMismatch: 682 case Sema::TDK_NonDependentConversionFailure: 683 break; 684 685 case Sema::TDK_IncompletePack: 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 case Sema::TDK_DeducedMismatch: 689 case Sema::TDK_DeducedMismatchNested: 690 case Sema::TDK_NonDeducedMismatch: 691 // FIXME: Destroy the data? 692 Data = nullptr; 693 break; 694 695 case Sema::TDK_SubstitutionFailure: 696 // FIXME: Destroy the template argument list? 697 Data = nullptr; 698 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 699 Diag->~PartialDiagnosticAt(); 700 HasDiagnostic = false; 701 } 702 break; 703 704 // Unhandled 705 case Sema::TDK_MiscellaneousDeductionFailure: 706 break; 707 } 708 } 709 710 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 711 if (HasDiagnostic) 712 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 713 return nullptr; 714 } 715 716 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 717 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 718 case Sema::TDK_Success: 719 case Sema::TDK_Invalid: 720 case Sema::TDK_InstantiationDepth: 721 case Sema::TDK_TooManyArguments: 722 case Sema::TDK_TooFewArguments: 723 case Sema::TDK_SubstitutionFailure: 724 case Sema::TDK_DeducedMismatch: 725 case Sema::TDK_DeducedMismatchNested: 726 case Sema::TDK_NonDeducedMismatch: 727 case Sema::TDK_CUDATargetMismatch: 728 case Sema::TDK_NonDependentConversionFailure: 729 return TemplateParameter(); 730 731 case Sema::TDK_Incomplete: 732 case Sema::TDK_InvalidExplicitArguments: 733 return TemplateParameter::getFromOpaqueValue(Data); 734 735 case Sema::TDK_IncompletePack: 736 case Sema::TDK_Inconsistent: 737 case Sema::TDK_Underqualified: 738 return static_cast<DFIParamWithArguments*>(Data)->Param; 739 740 // Unhandled 741 case Sema::TDK_MiscellaneousDeductionFailure: 742 break; 743 } 744 745 return TemplateParameter(); 746 } 747 748 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 749 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 750 case Sema::TDK_Success: 751 case Sema::TDK_Invalid: 752 case Sema::TDK_InstantiationDepth: 753 case Sema::TDK_TooManyArguments: 754 case Sema::TDK_TooFewArguments: 755 case Sema::TDK_Incomplete: 756 case Sema::TDK_IncompletePack: 757 case Sema::TDK_InvalidExplicitArguments: 758 case Sema::TDK_Inconsistent: 759 case Sema::TDK_Underqualified: 760 case Sema::TDK_NonDeducedMismatch: 761 case Sema::TDK_CUDATargetMismatch: 762 case Sema::TDK_NonDependentConversionFailure: 763 return nullptr; 764 765 case Sema::TDK_DeducedMismatch: 766 case Sema::TDK_DeducedMismatchNested: 767 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 768 769 case Sema::TDK_SubstitutionFailure: 770 return static_cast<TemplateArgumentList*>(Data); 771 772 // Unhandled 773 case Sema::TDK_MiscellaneousDeductionFailure: 774 break; 775 } 776 777 return nullptr; 778 } 779 780 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 782 case Sema::TDK_Success: 783 case Sema::TDK_Invalid: 784 case Sema::TDK_InstantiationDepth: 785 case Sema::TDK_Incomplete: 786 case Sema::TDK_TooManyArguments: 787 case Sema::TDK_TooFewArguments: 788 case Sema::TDK_InvalidExplicitArguments: 789 case Sema::TDK_SubstitutionFailure: 790 case Sema::TDK_CUDATargetMismatch: 791 case Sema::TDK_NonDependentConversionFailure: 792 return nullptr; 793 794 case Sema::TDK_IncompletePack: 795 case Sema::TDK_Inconsistent: 796 case Sema::TDK_Underqualified: 797 case Sema::TDK_DeducedMismatch: 798 case Sema::TDK_DeducedMismatchNested: 799 case Sema::TDK_NonDeducedMismatch: 800 return &static_cast<DFIArguments*>(Data)->FirstArg; 801 802 // Unhandled 803 case Sema::TDK_MiscellaneousDeductionFailure: 804 break; 805 } 806 807 return nullptr; 808 } 809 810 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 811 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 812 case Sema::TDK_Success: 813 case Sema::TDK_Invalid: 814 case Sema::TDK_InstantiationDepth: 815 case Sema::TDK_Incomplete: 816 case Sema::TDK_IncompletePack: 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 return nullptr; 824 825 case Sema::TDK_Inconsistent: 826 case Sema::TDK_Underqualified: 827 case Sema::TDK_DeducedMismatch: 828 case Sema::TDK_DeducedMismatchNested: 829 case Sema::TDK_NonDeducedMismatch: 830 return &static_cast<DFIArguments*>(Data)->SecondArg; 831 832 // Unhandled 833 case Sema::TDK_MiscellaneousDeductionFailure: 834 break; 835 } 836 837 return nullptr; 838 } 839 840 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 841 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 842 case Sema::TDK_DeducedMismatch: 843 case Sema::TDK_DeducedMismatchNested: 844 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 845 846 default: 847 return llvm::None; 848 } 849 } 850 851 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 852 OverloadedOperatorKind Op) { 853 if (!AllowRewrittenCandidates) 854 return false; 855 return Op == OO_EqualEqual || Op == OO_Spaceship; 856 } 857 858 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 859 ASTContext &Ctx, const FunctionDecl *FD) { 860 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 861 return false; 862 // Don't bother adding a reversed candidate that can never be a better 863 // match than the non-reversed version. 864 return FD->getNumParams() != 2 || 865 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 866 FD->getParamDecl(1)->getType()) || 867 FD->hasAttr<EnableIfAttr>(); 868 } 869 870 void OverloadCandidateSet::destroyCandidates() { 871 for (iterator i = begin(), e = end(); i != e; ++i) { 872 for (auto &C : i->Conversions) 873 C.~ImplicitConversionSequence(); 874 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 875 i->DeductionFailure.Destroy(); 876 } 877 } 878 879 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 880 destroyCandidates(); 881 SlabAllocator.Reset(); 882 NumInlineBytesUsed = 0; 883 Candidates.clear(); 884 Functions.clear(); 885 Kind = CSK; 886 } 887 888 namespace { 889 class UnbridgedCastsSet { 890 struct Entry { 891 Expr **Addr; 892 Expr *Saved; 893 }; 894 SmallVector<Entry, 2> Entries; 895 896 public: 897 void save(Sema &S, Expr *&E) { 898 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 899 Entry entry = { &E, E }; 900 Entries.push_back(entry); 901 E = S.stripARCUnbridgedCast(E); 902 } 903 904 void restore() { 905 for (SmallVectorImpl<Entry>::iterator 906 i = Entries.begin(), e = Entries.end(); i != e; ++i) 907 *i->Addr = i->Saved; 908 } 909 }; 910 } 911 912 /// checkPlaceholderForOverload - Do any interesting placeholder-like 913 /// preprocessing on the given expression. 914 /// 915 /// \param unbridgedCasts a collection to which to add unbridged casts; 916 /// without this, they will be immediately diagnosed as errors 917 /// 918 /// Return true on unrecoverable error. 919 static bool 920 checkPlaceholderForOverload(Sema &S, Expr *&E, 921 UnbridgedCastsSet *unbridgedCasts = nullptr) { 922 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 923 // We can't handle overloaded expressions here because overload 924 // resolution might reasonably tweak them. 925 if (placeholder->getKind() == BuiltinType::Overload) return false; 926 927 // If the context potentially accepts unbridged ARC casts, strip 928 // the unbridged cast and add it to the collection for later restoration. 929 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 930 unbridgedCasts) { 931 unbridgedCasts->save(S, E); 932 return false; 933 } 934 935 // Go ahead and check everything else. 936 ExprResult result = S.CheckPlaceholderExpr(E); 937 if (result.isInvalid()) 938 return true; 939 940 E = result.get(); 941 return false; 942 } 943 944 // Nothing to do. 945 return false; 946 } 947 948 /// checkArgPlaceholdersForOverload - Check a set of call operands for 949 /// placeholders. 950 static bool checkArgPlaceholdersForOverload(Sema &S, 951 MultiExprArg Args, 952 UnbridgedCastsSet &unbridged) { 953 for (unsigned i = 0, e = Args.size(); i != e; ++i) 954 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 955 return true; 956 957 return false; 958 } 959 960 /// Determine whether the given New declaration is an overload of the 961 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 962 /// New and Old cannot be overloaded, e.g., if New has the same signature as 963 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 964 /// functions (or function templates) at all. When it does return Ovl_Match or 965 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 966 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 967 /// declaration. 968 /// 969 /// Example: Given the following input: 970 /// 971 /// void f(int, float); // #1 972 /// void f(int, int); // #2 973 /// int f(int, int); // #3 974 /// 975 /// When we process #1, there is no previous declaration of "f", so IsOverload 976 /// will not be used. 977 /// 978 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 979 /// the parameter types, we see that #1 and #2 are overloaded (since they have 980 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 981 /// unchanged. 982 /// 983 /// When we process #3, Old is an overload set containing #1 and #2. We compare 984 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 985 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 986 /// functions are not part of the signature), IsOverload returns Ovl_Match and 987 /// MatchedDecl will be set to point to the FunctionDecl for #2. 988 /// 989 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 990 /// by a using declaration. The rules for whether to hide shadow declarations 991 /// ignore some properties which otherwise figure into a function template's 992 /// signature. 993 Sema::OverloadKind 994 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 995 NamedDecl *&Match, bool NewIsUsingDecl) { 996 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 997 I != E; ++I) { 998 NamedDecl *OldD = *I; 999 1000 bool OldIsUsingDecl = false; 1001 if (isa<UsingShadowDecl>(OldD)) { 1002 OldIsUsingDecl = true; 1003 1004 // We can always introduce two using declarations into the same 1005 // context, even if they have identical signatures. 1006 if (NewIsUsingDecl) continue; 1007 1008 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1009 } 1010 1011 // A using-declaration does not conflict with another declaration 1012 // if one of them is hidden. 1013 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1014 continue; 1015 1016 // If either declaration was introduced by a using declaration, 1017 // we'll need to use slightly different rules for matching. 1018 // Essentially, these rules are the normal rules, except that 1019 // function templates hide function templates with different 1020 // return types or template parameter lists. 1021 bool UseMemberUsingDeclRules = 1022 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1023 !New->getFriendObjectKind(); 1024 1025 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1026 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1027 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1028 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1029 continue; 1030 } 1031 1032 if (!isa<FunctionTemplateDecl>(OldD) && 1033 !shouldLinkPossiblyHiddenDecl(*I, New)) 1034 continue; 1035 1036 Match = *I; 1037 return Ovl_Match; 1038 } 1039 1040 // Builtins that have custom typechecking or have a reference should 1041 // not be overloadable or redeclarable. 1042 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1043 Match = *I; 1044 return Ovl_NonFunction; 1045 } 1046 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1047 // We can overload with these, which can show up when doing 1048 // redeclaration checks for UsingDecls. 1049 assert(Old.getLookupKind() == LookupUsingDeclName); 1050 } else if (isa<TagDecl>(OldD)) { 1051 // We can always overload with tags by hiding them. 1052 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1053 // Optimistically assume that an unresolved using decl will 1054 // overload; if it doesn't, we'll have to diagnose during 1055 // template instantiation. 1056 // 1057 // Exception: if the scope is dependent and this is not a class 1058 // member, the using declaration can only introduce an enumerator. 1059 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1060 Match = *I; 1061 return Ovl_NonFunction; 1062 } 1063 } else { 1064 // (C++ 13p1): 1065 // Only function declarations can be overloaded; object and type 1066 // declarations cannot be overloaded. 1067 Match = *I; 1068 return Ovl_NonFunction; 1069 } 1070 } 1071 1072 // C++ [temp.friend]p1: 1073 // For a friend function declaration that is not a template declaration: 1074 // -- if the name of the friend is a qualified or unqualified template-id, 1075 // [...], otherwise 1076 // -- if the name of the friend is a qualified-id and a matching 1077 // non-template function is found in the specified class or namespace, 1078 // the friend declaration refers to that function, otherwise, 1079 // -- if the name of the friend is a qualified-id and a matching function 1080 // template is found in the specified class or namespace, the friend 1081 // declaration refers to the deduced specialization of that function 1082 // template, otherwise 1083 // -- the name shall be an unqualified-id [...] 1084 // If we get here for a qualified friend declaration, we've just reached the 1085 // third bullet. If the type of the friend is dependent, skip this lookup 1086 // until instantiation. 1087 if (New->getFriendObjectKind() && New->getQualifier() && 1088 !New->getDescribedFunctionTemplate() && 1089 !New->getDependentSpecializationInfo() && 1090 !New->getType()->isDependentType()) { 1091 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1092 TemplateSpecResult.addAllDecls(Old); 1093 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1094 /*QualifiedFriend*/true)) { 1095 New->setInvalidDecl(); 1096 return Ovl_Overload; 1097 } 1098 1099 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1100 return Ovl_Match; 1101 } 1102 1103 return Ovl_Overload; 1104 } 1105 1106 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1107 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1108 // C++ [basic.start.main]p2: This function shall not be overloaded. 1109 if (New->isMain()) 1110 return false; 1111 1112 // MSVCRT user defined entry points cannot be overloaded. 1113 if (New->isMSVCRTEntryPoint()) 1114 return false; 1115 1116 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1117 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1118 1119 // C++ [temp.fct]p2: 1120 // A function template can be overloaded with other function templates 1121 // and with normal (non-template) functions. 1122 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1123 return true; 1124 1125 // Is the function New an overload of the function Old? 1126 QualType OldQType = Context.getCanonicalType(Old->getType()); 1127 QualType NewQType = Context.getCanonicalType(New->getType()); 1128 1129 // Compare the signatures (C++ 1.3.10) of the two functions to 1130 // determine whether they are overloads. If we find any mismatch 1131 // in the signature, they are overloads. 1132 1133 // If either of these functions is a K&R-style function (no 1134 // prototype), then we consider them to have matching signatures. 1135 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1136 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1137 return false; 1138 1139 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1140 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1141 1142 // The signature of a function includes the types of its 1143 // parameters (C++ 1.3.10), which includes the presence or absence 1144 // of the ellipsis; see C++ DR 357). 1145 if (OldQType != NewQType && 1146 (OldType->getNumParams() != NewType->getNumParams() || 1147 OldType->isVariadic() != NewType->isVariadic() || 1148 !FunctionParamTypesAreEqual(OldType, NewType))) 1149 return true; 1150 1151 // C++ [temp.over.link]p4: 1152 // The signature of a function template consists of its function 1153 // signature, its return type and its template parameter list. The names 1154 // of the template parameters are significant only for establishing the 1155 // relationship between the template parameters and the rest of the 1156 // signature. 1157 // 1158 // We check the return type and template parameter lists for function 1159 // templates first; the remaining checks follow. 1160 // 1161 // However, we don't consider either of these when deciding whether 1162 // a member introduced by a shadow declaration is hidden. 1163 if (!UseMemberUsingDeclRules && NewTemplate && 1164 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1165 OldTemplate->getTemplateParameters(), 1166 false, TPL_TemplateMatch) || 1167 !Context.hasSameType(Old->getDeclaredReturnType(), 1168 New->getDeclaredReturnType()))) 1169 return true; 1170 1171 // If the function is a class member, its signature includes the 1172 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1173 // 1174 // As part of this, also check whether one of the member functions 1175 // is static, in which case they are not overloads (C++ 1176 // 13.1p2). While not part of the definition of the signature, 1177 // this check is important to determine whether these functions 1178 // can be overloaded. 1179 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1180 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1181 if (OldMethod && NewMethod && 1182 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1183 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1184 if (!UseMemberUsingDeclRules && 1185 (OldMethod->getRefQualifier() == RQ_None || 1186 NewMethod->getRefQualifier() == RQ_None)) { 1187 // C++0x [over.load]p2: 1188 // - Member function declarations with the same name and the same 1189 // parameter-type-list as well as member function template 1190 // declarations with the same name, the same parameter-type-list, and 1191 // the same template parameter lists cannot be overloaded if any of 1192 // them, but not all, have a ref-qualifier (8.3.5). 1193 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1194 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1195 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1196 } 1197 return true; 1198 } 1199 1200 // We may not have applied the implicit const for a constexpr member 1201 // function yet (because we haven't yet resolved whether this is a static 1202 // or non-static member function). Add it now, on the assumption that this 1203 // is a redeclaration of OldMethod. 1204 auto OldQuals = OldMethod->getMethodQualifiers(); 1205 auto NewQuals = NewMethod->getMethodQualifiers(); 1206 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1207 !isa<CXXConstructorDecl>(NewMethod)) 1208 NewQuals.addConst(); 1209 // We do not allow overloading based off of '__restrict'. 1210 OldQuals.removeRestrict(); 1211 NewQuals.removeRestrict(); 1212 if (OldQuals != NewQuals) 1213 return true; 1214 } 1215 1216 // Though pass_object_size is placed on parameters and takes an argument, we 1217 // consider it to be a function-level modifier for the sake of function 1218 // identity. Either the function has one or more parameters with 1219 // pass_object_size or it doesn't. 1220 if (functionHasPassObjectSizeParams(New) != 1221 functionHasPassObjectSizeParams(Old)) 1222 return true; 1223 1224 // enable_if attributes are an order-sensitive part of the signature. 1225 for (specific_attr_iterator<EnableIfAttr> 1226 NewI = New->specific_attr_begin<EnableIfAttr>(), 1227 NewE = New->specific_attr_end<EnableIfAttr>(), 1228 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1229 OldE = Old->specific_attr_end<EnableIfAttr>(); 1230 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1231 if (NewI == NewE || OldI == OldE) 1232 return true; 1233 llvm::FoldingSetNodeID NewID, OldID; 1234 NewI->getCond()->Profile(NewID, Context, true); 1235 OldI->getCond()->Profile(OldID, Context, true); 1236 if (NewID != OldID) 1237 return true; 1238 } 1239 1240 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1241 // Don't allow overloading of destructors. (In theory we could, but it 1242 // would be a giant change to clang.) 1243 if (isa<CXXDestructorDecl>(New)) 1244 return false; 1245 1246 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1247 OldTarget = IdentifyCUDATarget(Old); 1248 if (NewTarget == CFT_InvalidTarget) 1249 return false; 1250 1251 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1252 1253 // Allow overloading of functions with same signature and different CUDA 1254 // target attributes. 1255 return NewTarget != OldTarget; 1256 } 1257 1258 // The signatures match; this is not an overload. 1259 return false; 1260 } 1261 1262 /// Tries a user-defined conversion from From to ToType. 1263 /// 1264 /// Produces an implicit conversion sequence for when a standard conversion 1265 /// is not an option. See TryImplicitConversion for more information. 1266 static ImplicitConversionSequence 1267 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1268 bool SuppressUserConversions, 1269 bool AllowExplicit, 1270 bool InOverloadResolution, 1271 bool CStyle, 1272 bool AllowObjCWritebackConversion, 1273 bool AllowObjCConversionOnExplicit) { 1274 ImplicitConversionSequence ICS; 1275 1276 if (SuppressUserConversions) { 1277 // We're not in the case above, so there is no conversion that 1278 // we can perform. 1279 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1280 return ICS; 1281 } 1282 1283 // Attempt user-defined conversion. 1284 OverloadCandidateSet Conversions(From->getExprLoc(), 1285 OverloadCandidateSet::CSK_Normal); 1286 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1287 Conversions, AllowExplicit, 1288 AllowObjCConversionOnExplicit)) { 1289 case OR_Success: 1290 case OR_Deleted: 1291 ICS.setUserDefined(); 1292 // C++ [over.ics.user]p4: 1293 // A conversion of an expression of class type to the same class 1294 // type is given Exact Match rank, and a conversion of an 1295 // expression of class type to a base class of that type is 1296 // given Conversion rank, in spite of the fact that a copy 1297 // constructor (i.e., a user-defined conversion function) is 1298 // called for those cases. 1299 if (CXXConstructorDecl *Constructor 1300 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1301 QualType FromCanon 1302 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1303 QualType ToCanon 1304 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1305 if (Constructor->isCopyConstructor() && 1306 (FromCanon == ToCanon || 1307 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1308 // Turn this into a "standard" conversion sequence, so that it 1309 // gets ranked with standard conversion sequences. 1310 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1311 ICS.setStandard(); 1312 ICS.Standard.setAsIdentityConversion(); 1313 ICS.Standard.setFromType(From->getType()); 1314 ICS.Standard.setAllToTypes(ToType); 1315 ICS.Standard.CopyConstructor = Constructor; 1316 ICS.Standard.FoundCopyConstructor = Found; 1317 if (ToCanon != FromCanon) 1318 ICS.Standard.Second = ICK_Derived_To_Base; 1319 } 1320 } 1321 break; 1322 1323 case OR_Ambiguous: 1324 ICS.setAmbiguous(); 1325 ICS.Ambiguous.setFromType(From->getType()); 1326 ICS.Ambiguous.setToType(ToType); 1327 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1328 Cand != Conversions.end(); ++Cand) 1329 if (Cand->Viable) 1330 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1331 break; 1332 1333 // Fall through. 1334 case OR_No_Viable_Function: 1335 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1336 break; 1337 } 1338 1339 return ICS; 1340 } 1341 1342 /// TryImplicitConversion - Attempt to perform an implicit conversion 1343 /// from the given expression (Expr) to the given type (ToType). This 1344 /// function returns an implicit conversion sequence that can be used 1345 /// to perform the initialization. Given 1346 /// 1347 /// void f(float f); 1348 /// void g(int i) { f(i); } 1349 /// 1350 /// this routine would produce an implicit conversion sequence to 1351 /// describe the initialization of f from i, which will be a standard 1352 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1353 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1354 // 1355 /// Note that this routine only determines how the conversion can be 1356 /// performed; it does not actually perform the conversion. As such, 1357 /// it will not produce any diagnostics if no conversion is available, 1358 /// but will instead return an implicit conversion sequence of kind 1359 /// "BadConversion". 1360 /// 1361 /// If @p SuppressUserConversions, then user-defined conversions are 1362 /// not permitted. 1363 /// If @p AllowExplicit, then explicit user-defined conversions are 1364 /// permitted. 1365 /// 1366 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1367 /// writeback conversion, which allows __autoreleasing id* parameters to 1368 /// be initialized with __strong id* or __weak id* arguments. 1369 static ImplicitConversionSequence 1370 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1371 bool SuppressUserConversions, 1372 bool AllowExplicit, 1373 bool InOverloadResolution, 1374 bool CStyle, 1375 bool AllowObjCWritebackConversion, 1376 bool AllowObjCConversionOnExplicit) { 1377 ImplicitConversionSequence ICS; 1378 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1379 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1380 ICS.setStandard(); 1381 return ICS; 1382 } 1383 1384 if (!S.getLangOpts().CPlusPlus) { 1385 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1386 return ICS; 1387 } 1388 1389 // C++ [over.ics.user]p4: 1390 // A conversion of an expression of class type to the same class 1391 // type is given Exact Match rank, and a conversion of an 1392 // expression of class type to a base class of that type is 1393 // given Conversion rank, in spite of the fact that a copy/move 1394 // constructor (i.e., a user-defined conversion function) is 1395 // called for those cases. 1396 QualType FromType = From->getType(); 1397 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1398 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1399 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1400 ICS.setStandard(); 1401 ICS.Standard.setAsIdentityConversion(); 1402 ICS.Standard.setFromType(FromType); 1403 ICS.Standard.setAllToTypes(ToType); 1404 1405 // We don't actually check at this point whether there is a valid 1406 // copy/move constructor, since overloading just assumes that it 1407 // exists. When we actually perform initialization, we'll find the 1408 // appropriate constructor to copy the returned object, if needed. 1409 ICS.Standard.CopyConstructor = nullptr; 1410 1411 // Determine whether this is considered a derived-to-base conversion. 1412 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1413 ICS.Standard.Second = ICK_Derived_To_Base; 1414 1415 return ICS; 1416 } 1417 1418 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1419 AllowExplicit, InOverloadResolution, CStyle, 1420 AllowObjCWritebackConversion, 1421 AllowObjCConversionOnExplicit); 1422 } 1423 1424 ImplicitConversionSequence 1425 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1426 bool SuppressUserConversions, 1427 bool AllowExplicit, 1428 bool InOverloadResolution, 1429 bool CStyle, 1430 bool AllowObjCWritebackConversion) { 1431 return ::TryImplicitConversion(*this, From, ToType, 1432 SuppressUserConversions, AllowExplicit, 1433 InOverloadResolution, CStyle, 1434 AllowObjCWritebackConversion, 1435 /*AllowObjCConversionOnExplicit=*/false); 1436 } 1437 1438 /// PerformImplicitConversion - Perform an implicit conversion of the 1439 /// expression From to the type ToType. Returns the 1440 /// converted expression. Flavor is the kind of conversion we're 1441 /// performing, used in the error message. If @p AllowExplicit, 1442 /// explicit user-defined conversions are permitted. 1443 ExprResult 1444 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1445 AssignmentAction Action, bool AllowExplicit) { 1446 ImplicitConversionSequence ICS; 1447 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1448 } 1449 1450 ExprResult 1451 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1452 AssignmentAction Action, bool AllowExplicit, 1453 ImplicitConversionSequence& ICS) { 1454 if (checkPlaceholderForOverload(*this, From)) 1455 return ExprError(); 1456 1457 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1458 bool AllowObjCWritebackConversion 1459 = getLangOpts().ObjCAutoRefCount && 1460 (Action == AA_Passing || Action == AA_Sending); 1461 if (getLangOpts().ObjC) 1462 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1463 From->getType(), From); 1464 ICS = ::TryImplicitConversion(*this, From, ToType, 1465 /*SuppressUserConversions=*/false, 1466 AllowExplicit, 1467 /*InOverloadResolution=*/false, 1468 /*CStyle=*/false, 1469 AllowObjCWritebackConversion, 1470 /*AllowObjCConversionOnExplicit=*/false); 1471 return PerformImplicitConversion(From, ToType, ICS, Action); 1472 } 1473 1474 /// Determine whether the conversion from FromType to ToType is a valid 1475 /// conversion that strips "noexcept" or "noreturn" off the nested function 1476 /// type. 1477 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1478 QualType &ResultTy) { 1479 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1480 return false; 1481 1482 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1483 // or F(t noexcept) -> F(t) 1484 // where F adds one of the following at most once: 1485 // - a pointer 1486 // - a member pointer 1487 // - a block pointer 1488 // Changes here need matching changes in FindCompositePointerType. 1489 CanQualType CanTo = Context.getCanonicalType(ToType); 1490 CanQualType CanFrom = Context.getCanonicalType(FromType); 1491 Type::TypeClass TyClass = CanTo->getTypeClass(); 1492 if (TyClass != CanFrom->getTypeClass()) return false; 1493 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1494 if (TyClass == Type::Pointer) { 1495 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1496 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1497 } else if (TyClass == Type::BlockPointer) { 1498 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1499 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1500 } else if (TyClass == Type::MemberPointer) { 1501 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1502 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1503 // A function pointer conversion cannot change the class of the function. 1504 if (ToMPT->getClass() != FromMPT->getClass()) 1505 return false; 1506 CanTo = ToMPT->getPointeeType(); 1507 CanFrom = FromMPT->getPointeeType(); 1508 } else { 1509 return false; 1510 } 1511 1512 TyClass = CanTo->getTypeClass(); 1513 if (TyClass != CanFrom->getTypeClass()) return false; 1514 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1515 return false; 1516 } 1517 1518 const auto *FromFn = cast<FunctionType>(CanFrom); 1519 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1520 1521 const auto *ToFn = cast<FunctionType>(CanTo); 1522 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1523 1524 bool Changed = false; 1525 1526 // Drop 'noreturn' if not present in target type. 1527 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1528 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1529 Changed = true; 1530 } 1531 1532 // Drop 'noexcept' if not present in target type. 1533 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1534 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1535 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1536 FromFn = cast<FunctionType>( 1537 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1538 EST_None) 1539 .getTypePtr()); 1540 Changed = true; 1541 } 1542 1543 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1544 // only if the ExtParameterInfo lists of the two function prototypes can be 1545 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1546 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1547 bool CanUseToFPT, CanUseFromFPT; 1548 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1549 CanUseFromFPT, NewParamInfos) && 1550 CanUseToFPT && !CanUseFromFPT) { 1551 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1552 ExtInfo.ExtParameterInfos = 1553 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1554 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1555 FromFPT->getParamTypes(), ExtInfo); 1556 FromFn = QT->getAs<FunctionType>(); 1557 Changed = true; 1558 } 1559 } 1560 1561 if (!Changed) 1562 return false; 1563 1564 assert(QualType(FromFn, 0).isCanonical()); 1565 if (QualType(FromFn, 0) != CanTo) return false; 1566 1567 ResultTy = ToType; 1568 return true; 1569 } 1570 1571 /// Determine whether the conversion from FromType to ToType is a valid 1572 /// vector conversion. 1573 /// 1574 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1575 /// conversion. 1576 static bool IsVectorConversion(Sema &S, QualType FromType, 1577 QualType ToType, ImplicitConversionKind &ICK) { 1578 // We need at least one of these types to be a vector type to have a vector 1579 // conversion. 1580 if (!ToType->isVectorType() && !FromType->isVectorType()) 1581 return false; 1582 1583 // Identical types require no conversions. 1584 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1585 return false; 1586 1587 // There are no conversions between extended vector types, only identity. 1588 if (ToType->isExtVectorType()) { 1589 // There are no conversions between extended vector types other than the 1590 // identity conversion. 1591 if (FromType->isExtVectorType()) 1592 return false; 1593 1594 // Vector splat from any arithmetic type to a vector. 1595 if (FromType->isArithmeticType()) { 1596 ICK = ICK_Vector_Splat; 1597 return true; 1598 } 1599 } 1600 1601 // We can perform the conversion between vector types in the following cases: 1602 // 1)vector types are equivalent AltiVec and GCC vector types 1603 // 2)lax vector conversions are permitted and the vector types are of the 1604 // same size 1605 if (ToType->isVectorType() && FromType->isVectorType()) { 1606 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1607 S.isLaxVectorConversion(FromType, ToType)) { 1608 ICK = ICK_Vector_Conversion; 1609 return true; 1610 } 1611 } 1612 1613 return false; 1614 } 1615 1616 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1617 bool InOverloadResolution, 1618 StandardConversionSequence &SCS, 1619 bool CStyle); 1620 1621 /// IsStandardConversion - Determines whether there is a standard 1622 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1623 /// expression From to the type ToType. Standard conversion sequences 1624 /// only consider non-class types; for conversions that involve class 1625 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1626 /// contain the standard conversion sequence required to perform this 1627 /// conversion and this routine will return true. Otherwise, this 1628 /// routine will return false and the value of SCS is unspecified. 1629 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1630 bool InOverloadResolution, 1631 StandardConversionSequence &SCS, 1632 bool CStyle, 1633 bool AllowObjCWritebackConversion) { 1634 QualType FromType = From->getType(); 1635 1636 // Standard conversions (C++ [conv]) 1637 SCS.setAsIdentityConversion(); 1638 SCS.IncompatibleObjC = false; 1639 SCS.setFromType(FromType); 1640 SCS.CopyConstructor = nullptr; 1641 1642 // There are no standard conversions for class types in C++, so 1643 // abort early. When overloading in C, however, we do permit them. 1644 if (S.getLangOpts().CPlusPlus && 1645 (FromType->isRecordType() || ToType->isRecordType())) 1646 return false; 1647 1648 // The first conversion can be an lvalue-to-rvalue conversion, 1649 // array-to-pointer conversion, or function-to-pointer conversion 1650 // (C++ 4p1). 1651 1652 if (FromType == S.Context.OverloadTy) { 1653 DeclAccessPair AccessPair; 1654 if (FunctionDecl *Fn 1655 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1656 AccessPair)) { 1657 // We were able to resolve the address of the overloaded function, 1658 // so we can convert to the type of that function. 1659 FromType = Fn->getType(); 1660 SCS.setFromType(FromType); 1661 1662 // we can sometimes resolve &foo<int> regardless of ToType, so check 1663 // if the type matches (identity) or we are converting to bool 1664 if (!S.Context.hasSameUnqualifiedType( 1665 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1666 QualType resultTy; 1667 // if the function type matches except for [[noreturn]], it's ok 1668 if (!S.IsFunctionConversion(FromType, 1669 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1670 // otherwise, only a boolean conversion is standard 1671 if (!ToType->isBooleanType()) 1672 return false; 1673 } 1674 1675 // Check if the "from" expression is taking the address of an overloaded 1676 // function and recompute the FromType accordingly. Take advantage of the 1677 // fact that non-static member functions *must* have such an address-of 1678 // expression. 1679 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1680 if (Method && !Method->isStatic()) { 1681 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1682 "Non-unary operator on non-static member address"); 1683 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1684 == UO_AddrOf && 1685 "Non-address-of operator on non-static member address"); 1686 const Type *ClassType 1687 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1688 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1689 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1690 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1691 UO_AddrOf && 1692 "Non-address-of operator for overloaded function expression"); 1693 FromType = S.Context.getPointerType(FromType); 1694 } 1695 1696 // Check that we've computed the proper type after overload resolution. 1697 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1698 // be calling it from within an NDEBUG block. 1699 assert(S.Context.hasSameType( 1700 FromType, 1701 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1702 } else { 1703 return false; 1704 } 1705 } 1706 // Lvalue-to-rvalue conversion (C++11 4.1): 1707 // A glvalue (3.10) of a non-function, non-array type T can 1708 // be converted to a prvalue. 1709 bool argIsLValue = From->isGLValue(); 1710 if (argIsLValue && 1711 !FromType->isFunctionType() && !FromType->isArrayType() && 1712 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1713 SCS.First = ICK_Lvalue_To_Rvalue; 1714 1715 // C11 6.3.2.1p2: 1716 // ... if the lvalue has atomic type, the value has the non-atomic version 1717 // of the type of the lvalue ... 1718 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1719 FromType = Atomic->getValueType(); 1720 1721 // If T is a non-class type, the type of the rvalue is the 1722 // cv-unqualified version of T. Otherwise, the type of the rvalue 1723 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1724 // just strip the qualifiers because they don't matter. 1725 FromType = FromType.getUnqualifiedType(); 1726 } else if (FromType->isArrayType()) { 1727 // Array-to-pointer conversion (C++ 4.2) 1728 SCS.First = ICK_Array_To_Pointer; 1729 1730 // An lvalue or rvalue of type "array of N T" or "array of unknown 1731 // bound of T" can be converted to an rvalue of type "pointer to 1732 // T" (C++ 4.2p1). 1733 FromType = S.Context.getArrayDecayedType(FromType); 1734 1735 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1736 // This conversion is deprecated in C++03 (D.4) 1737 SCS.DeprecatedStringLiteralToCharPtr = true; 1738 1739 // For the purpose of ranking in overload resolution 1740 // (13.3.3.1.1), this conversion is considered an 1741 // array-to-pointer conversion followed by a qualification 1742 // conversion (4.4). (C++ 4.2p2) 1743 SCS.Second = ICK_Identity; 1744 SCS.Third = ICK_Qualification; 1745 SCS.QualificationIncludesObjCLifetime = false; 1746 SCS.setAllToTypes(FromType); 1747 return true; 1748 } 1749 } else if (FromType->isFunctionType() && argIsLValue) { 1750 // Function-to-pointer conversion (C++ 4.3). 1751 SCS.First = ICK_Function_To_Pointer; 1752 1753 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1754 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1755 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1756 return false; 1757 1758 // An lvalue of function type T can be converted to an rvalue of 1759 // type "pointer to T." The result is a pointer to the 1760 // function. (C++ 4.3p1). 1761 FromType = S.Context.getPointerType(FromType); 1762 } else { 1763 // We don't require any conversions for the first step. 1764 SCS.First = ICK_Identity; 1765 } 1766 SCS.setToType(0, FromType); 1767 1768 // The second conversion can be an integral promotion, floating 1769 // point promotion, integral conversion, floating point conversion, 1770 // floating-integral conversion, pointer conversion, 1771 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1772 // For overloading in C, this can also be a "compatible-type" 1773 // conversion. 1774 bool IncompatibleObjC = false; 1775 ImplicitConversionKind SecondICK = ICK_Identity; 1776 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1777 // The unqualified versions of the types are the same: there's no 1778 // conversion to do. 1779 SCS.Second = ICK_Identity; 1780 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1781 // Integral promotion (C++ 4.5). 1782 SCS.Second = ICK_Integral_Promotion; 1783 FromType = ToType.getUnqualifiedType(); 1784 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1785 // Floating point promotion (C++ 4.6). 1786 SCS.Second = ICK_Floating_Promotion; 1787 FromType = ToType.getUnqualifiedType(); 1788 } else if (S.IsComplexPromotion(FromType, ToType)) { 1789 // Complex promotion (Clang extension) 1790 SCS.Second = ICK_Complex_Promotion; 1791 FromType = ToType.getUnqualifiedType(); 1792 } else if (ToType->isBooleanType() && 1793 (FromType->isArithmeticType() || 1794 FromType->isAnyPointerType() || 1795 FromType->isBlockPointerType() || 1796 FromType->isMemberPointerType() || 1797 FromType->isNullPtrType())) { 1798 // Boolean conversions (C++ 4.12). 1799 SCS.Second = ICK_Boolean_Conversion; 1800 FromType = S.Context.BoolTy; 1801 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1802 ToType->isIntegralType(S.Context)) { 1803 // Integral conversions (C++ 4.7). 1804 SCS.Second = ICK_Integral_Conversion; 1805 FromType = ToType.getUnqualifiedType(); 1806 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1807 // Complex conversions (C99 6.3.1.6) 1808 SCS.Second = ICK_Complex_Conversion; 1809 FromType = ToType.getUnqualifiedType(); 1810 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1811 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1812 // Complex-real conversions (C99 6.3.1.7) 1813 SCS.Second = ICK_Complex_Real; 1814 FromType = ToType.getUnqualifiedType(); 1815 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1816 // FIXME: disable conversions between long double and __float128 if 1817 // their representation is different until there is back end support 1818 // We of course allow this conversion if long double is really double. 1819 if (&S.Context.getFloatTypeSemantics(FromType) != 1820 &S.Context.getFloatTypeSemantics(ToType)) { 1821 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1822 ToType == S.Context.LongDoubleTy) || 1823 (FromType == S.Context.LongDoubleTy && 1824 ToType == S.Context.Float128Ty)); 1825 if (Float128AndLongDouble && 1826 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1827 &llvm::APFloat::PPCDoubleDouble())) 1828 return false; 1829 } 1830 // Floating point conversions (C++ 4.8). 1831 SCS.Second = ICK_Floating_Conversion; 1832 FromType = ToType.getUnqualifiedType(); 1833 } else if ((FromType->isRealFloatingType() && 1834 ToType->isIntegralType(S.Context)) || 1835 (FromType->isIntegralOrUnscopedEnumerationType() && 1836 ToType->isRealFloatingType())) { 1837 // Floating-integral conversions (C++ 4.9). 1838 SCS.Second = ICK_Floating_Integral; 1839 FromType = ToType.getUnqualifiedType(); 1840 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1841 SCS.Second = ICK_Block_Pointer_Conversion; 1842 } else if (AllowObjCWritebackConversion && 1843 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1844 SCS.Second = ICK_Writeback_Conversion; 1845 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1846 FromType, IncompatibleObjC)) { 1847 // Pointer conversions (C++ 4.10). 1848 SCS.Second = ICK_Pointer_Conversion; 1849 SCS.IncompatibleObjC = IncompatibleObjC; 1850 FromType = FromType.getUnqualifiedType(); 1851 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1852 InOverloadResolution, FromType)) { 1853 // Pointer to member conversions (4.11). 1854 SCS.Second = ICK_Pointer_Member; 1855 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1856 SCS.Second = SecondICK; 1857 FromType = ToType.getUnqualifiedType(); 1858 } else if (!S.getLangOpts().CPlusPlus && 1859 S.Context.typesAreCompatible(ToType, FromType)) { 1860 // Compatible conversions (Clang extension for C function overloading) 1861 SCS.Second = ICK_Compatible_Conversion; 1862 FromType = ToType.getUnqualifiedType(); 1863 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1864 InOverloadResolution, 1865 SCS, CStyle)) { 1866 SCS.Second = ICK_TransparentUnionConversion; 1867 FromType = ToType; 1868 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1869 CStyle)) { 1870 // tryAtomicConversion has updated the standard conversion sequence 1871 // appropriately. 1872 return true; 1873 } else if (ToType->isEventT() && 1874 From->isIntegerConstantExpr(S.getASTContext()) && 1875 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1876 SCS.Second = ICK_Zero_Event_Conversion; 1877 FromType = ToType; 1878 } else if (ToType->isQueueT() && 1879 From->isIntegerConstantExpr(S.getASTContext()) && 1880 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1881 SCS.Second = ICK_Zero_Queue_Conversion; 1882 FromType = ToType; 1883 } else if (ToType->isSamplerT() && 1884 From->isIntegerConstantExpr(S.getASTContext())) { 1885 SCS.Second = ICK_Compatible_Conversion; 1886 FromType = ToType; 1887 } else { 1888 // No second conversion required. 1889 SCS.Second = ICK_Identity; 1890 } 1891 SCS.setToType(1, FromType); 1892 1893 // The third conversion can be a function pointer conversion or a 1894 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1895 bool ObjCLifetimeConversion; 1896 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1897 // Function pointer conversions (removing 'noexcept') including removal of 1898 // 'noreturn' (Clang extension). 1899 SCS.Third = ICK_Function_Conversion; 1900 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1901 ObjCLifetimeConversion)) { 1902 SCS.Third = ICK_Qualification; 1903 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1904 FromType = ToType; 1905 } else { 1906 // No conversion required 1907 SCS.Third = ICK_Identity; 1908 } 1909 1910 // C++ [over.best.ics]p6: 1911 // [...] Any difference in top-level cv-qualification is 1912 // subsumed by the initialization itself and does not constitute 1913 // a conversion. [...] 1914 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1915 QualType CanonTo = S.Context.getCanonicalType(ToType); 1916 if (CanonFrom.getLocalUnqualifiedType() 1917 == CanonTo.getLocalUnqualifiedType() && 1918 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1919 FromType = ToType; 1920 CanonFrom = CanonTo; 1921 } 1922 1923 SCS.setToType(2, FromType); 1924 1925 if (CanonFrom == CanonTo) 1926 return true; 1927 1928 // If we have not converted the argument type to the parameter type, 1929 // this is a bad conversion sequence, unless we're resolving an overload in C. 1930 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1931 return false; 1932 1933 ExprResult ER = ExprResult{From}; 1934 Sema::AssignConvertType Conv = 1935 S.CheckSingleAssignmentConstraints(ToType, ER, 1936 /*Diagnose=*/false, 1937 /*DiagnoseCFAudited=*/false, 1938 /*ConvertRHS=*/false); 1939 ImplicitConversionKind SecondConv; 1940 switch (Conv) { 1941 case Sema::Compatible: 1942 SecondConv = ICK_C_Only_Conversion; 1943 break; 1944 // For our purposes, discarding qualifiers is just as bad as using an 1945 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1946 // qualifiers, as well. 1947 case Sema::CompatiblePointerDiscardsQualifiers: 1948 case Sema::IncompatiblePointer: 1949 case Sema::IncompatiblePointerSign: 1950 SecondConv = ICK_Incompatible_Pointer_Conversion; 1951 break; 1952 default: 1953 return false; 1954 } 1955 1956 // First can only be an lvalue conversion, so we pretend that this was the 1957 // second conversion. First should already be valid from earlier in the 1958 // function. 1959 SCS.Second = SecondConv; 1960 SCS.setToType(1, ToType); 1961 1962 // Third is Identity, because Second should rank us worse than any other 1963 // conversion. This could also be ICK_Qualification, but it's simpler to just 1964 // lump everything in with the second conversion, and we don't gain anything 1965 // from making this ICK_Qualification. 1966 SCS.Third = ICK_Identity; 1967 SCS.setToType(2, ToType); 1968 return true; 1969 } 1970 1971 static bool 1972 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1973 QualType &ToType, 1974 bool InOverloadResolution, 1975 StandardConversionSequence &SCS, 1976 bool CStyle) { 1977 1978 const RecordType *UT = ToType->getAsUnionType(); 1979 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1980 return false; 1981 // The field to initialize within the transparent union. 1982 RecordDecl *UD = UT->getDecl(); 1983 // It's compatible if the expression matches any of the fields. 1984 for (const auto *it : UD->fields()) { 1985 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1986 CStyle, /*AllowObjCWritebackConversion=*/false)) { 1987 ToType = it->getType(); 1988 return true; 1989 } 1990 } 1991 return false; 1992 } 1993 1994 /// IsIntegralPromotion - Determines whether the conversion from the 1995 /// expression From (whose potentially-adjusted type is FromType) to 1996 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1997 /// sets PromotedType to the promoted type. 1998 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1999 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2000 // All integers are built-in. 2001 if (!To) { 2002 return false; 2003 } 2004 2005 // An rvalue of type char, signed char, unsigned char, short int, or 2006 // unsigned short int can be converted to an rvalue of type int if 2007 // int can represent all the values of the source type; otherwise, 2008 // the source rvalue can be converted to an rvalue of type unsigned 2009 // int (C++ 4.5p1). 2010 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2011 !FromType->isEnumeralType()) { 2012 if (// We can promote any signed, promotable integer type to an int 2013 (FromType->isSignedIntegerType() || 2014 // We can promote any unsigned integer type whose size is 2015 // less than int to an int. 2016 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2017 return To->getKind() == BuiltinType::Int; 2018 } 2019 2020 return To->getKind() == BuiltinType::UInt; 2021 } 2022 2023 // C++11 [conv.prom]p3: 2024 // A prvalue of an unscoped enumeration type whose underlying type is not 2025 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2026 // following types that can represent all the values of the enumeration 2027 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2028 // unsigned int, long int, unsigned long int, long long int, or unsigned 2029 // long long int. If none of the types in that list can represent all the 2030 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2031 // type can be converted to an rvalue a prvalue of the extended integer type 2032 // with lowest integer conversion rank (4.13) greater than the rank of long 2033 // long in which all the values of the enumeration can be represented. If 2034 // there are two such extended types, the signed one is chosen. 2035 // C++11 [conv.prom]p4: 2036 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2037 // can be converted to a prvalue of its underlying type. Moreover, if 2038 // integral promotion can be applied to its underlying type, a prvalue of an 2039 // unscoped enumeration type whose underlying type is fixed can also be 2040 // converted to a prvalue of the promoted underlying type. 2041 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2042 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2043 // provided for a scoped enumeration. 2044 if (FromEnumType->getDecl()->isScoped()) 2045 return false; 2046 2047 // We can perform an integral promotion to the underlying type of the enum, 2048 // even if that's not the promoted type. Note that the check for promoting 2049 // the underlying type is based on the type alone, and does not consider 2050 // the bitfield-ness of the actual source expression. 2051 if (FromEnumType->getDecl()->isFixed()) { 2052 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2053 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2054 IsIntegralPromotion(nullptr, Underlying, ToType); 2055 } 2056 2057 // We have already pre-calculated the promotion type, so this is trivial. 2058 if (ToType->isIntegerType() && 2059 isCompleteType(From->getBeginLoc(), FromType)) 2060 return Context.hasSameUnqualifiedType( 2061 ToType, FromEnumType->getDecl()->getPromotionType()); 2062 2063 // C++ [conv.prom]p5: 2064 // If the bit-field has an enumerated type, it is treated as any other 2065 // value of that type for promotion purposes. 2066 // 2067 // ... so do not fall through into the bit-field checks below in C++. 2068 if (getLangOpts().CPlusPlus) 2069 return false; 2070 } 2071 2072 // C++0x [conv.prom]p2: 2073 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2074 // to an rvalue a prvalue of the first of the following types that can 2075 // represent all the values of its underlying type: int, unsigned int, 2076 // long int, unsigned long int, long long int, or unsigned long long int. 2077 // If none of the types in that list can represent all the values of its 2078 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2079 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2080 // type. 2081 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2082 ToType->isIntegerType()) { 2083 // Determine whether the type we're converting from is signed or 2084 // unsigned. 2085 bool FromIsSigned = FromType->isSignedIntegerType(); 2086 uint64_t FromSize = Context.getTypeSize(FromType); 2087 2088 // The types we'll try to promote to, in the appropriate 2089 // order. Try each of these types. 2090 QualType PromoteTypes[6] = { 2091 Context.IntTy, Context.UnsignedIntTy, 2092 Context.LongTy, Context.UnsignedLongTy , 2093 Context.LongLongTy, Context.UnsignedLongLongTy 2094 }; 2095 for (int Idx = 0; Idx < 6; ++Idx) { 2096 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2097 if (FromSize < ToSize || 2098 (FromSize == ToSize && 2099 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2100 // We found the type that we can promote to. If this is the 2101 // type we wanted, we have a promotion. Otherwise, no 2102 // promotion. 2103 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2104 } 2105 } 2106 } 2107 2108 // An rvalue for an integral bit-field (9.6) can be converted to an 2109 // rvalue of type int if int can represent all the values of the 2110 // bit-field; otherwise, it can be converted to unsigned int if 2111 // unsigned int can represent all the values of the bit-field. If 2112 // the bit-field is larger yet, no integral promotion applies to 2113 // it. If the bit-field has an enumerated type, it is treated as any 2114 // other value of that type for promotion purposes (C++ 4.5p3). 2115 // FIXME: We should delay checking of bit-fields until we actually perform the 2116 // conversion. 2117 // 2118 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2119 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2120 // bit-fields and those whose underlying type is larger than int) for GCC 2121 // compatibility. 2122 if (From) { 2123 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2124 llvm::APSInt BitWidth; 2125 if (FromType->isIntegralType(Context) && 2126 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2127 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2128 ToSize = Context.getTypeSize(ToType); 2129 2130 // Are we promoting to an int from a bitfield that fits in an int? 2131 if (BitWidth < ToSize || 2132 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2133 return To->getKind() == BuiltinType::Int; 2134 } 2135 2136 // Are we promoting to an unsigned int from an unsigned bitfield 2137 // that fits into an unsigned int? 2138 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2139 return To->getKind() == BuiltinType::UInt; 2140 } 2141 2142 return false; 2143 } 2144 } 2145 } 2146 2147 // An rvalue of type bool can be converted to an rvalue of type int, 2148 // with false becoming zero and true becoming one (C++ 4.5p4). 2149 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2150 return true; 2151 } 2152 2153 return false; 2154 } 2155 2156 /// IsFloatingPointPromotion - Determines whether the conversion from 2157 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2158 /// returns true and sets PromotedType to the promoted type. 2159 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2160 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2161 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2162 /// An rvalue of type float can be converted to an rvalue of type 2163 /// double. (C++ 4.6p1). 2164 if (FromBuiltin->getKind() == BuiltinType::Float && 2165 ToBuiltin->getKind() == BuiltinType::Double) 2166 return true; 2167 2168 // C99 6.3.1.5p1: 2169 // When a float is promoted to double or long double, or a 2170 // double is promoted to long double [...]. 2171 if (!getLangOpts().CPlusPlus && 2172 (FromBuiltin->getKind() == BuiltinType::Float || 2173 FromBuiltin->getKind() == BuiltinType::Double) && 2174 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2175 ToBuiltin->getKind() == BuiltinType::Float128)) 2176 return true; 2177 2178 // Half can be promoted to float. 2179 if (!getLangOpts().NativeHalfType && 2180 FromBuiltin->getKind() == BuiltinType::Half && 2181 ToBuiltin->getKind() == BuiltinType::Float) 2182 return true; 2183 } 2184 2185 return false; 2186 } 2187 2188 /// Determine if a conversion is a complex promotion. 2189 /// 2190 /// A complex promotion is defined as a complex -> complex conversion 2191 /// where the conversion between the underlying real types is a 2192 /// floating-point or integral promotion. 2193 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2194 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2195 if (!FromComplex) 2196 return false; 2197 2198 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2199 if (!ToComplex) 2200 return false; 2201 2202 return IsFloatingPointPromotion(FromComplex->getElementType(), 2203 ToComplex->getElementType()) || 2204 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2205 ToComplex->getElementType()); 2206 } 2207 2208 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2209 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2210 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2211 /// if non-empty, will be a pointer to ToType that may or may not have 2212 /// the right set of qualifiers on its pointee. 2213 /// 2214 static QualType 2215 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2216 QualType ToPointee, QualType ToType, 2217 ASTContext &Context, 2218 bool StripObjCLifetime = false) { 2219 assert((FromPtr->getTypeClass() == Type::Pointer || 2220 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2221 "Invalid similarly-qualified pointer type"); 2222 2223 /// Conversions to 'id' subsume cv-qualifier conversions. 2224 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2225 return ToType.getUnqualifiedType(); 2226 2227 QualType CanonFromPointee 2228 = Context.getCanonicalType(FromPtr->getPointeeType()); 2229 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2230 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2231 2232 if (StripObjCLifetime) 2233 Quals.removeObjCLifetime(); 2234 2235 // Exact qualifier match -> return the pointer type we're converting to. 2236 if (CanonToPointee.getLocalQualifiers() == Quals) { 2237 // ToType is exactly what we need. Return it. 2238 if (!ToType.isNull()) 2239 return ToType.getUnqualifiedType(); 2240 2241 // Build a pointer to ToPointee. It has the right qualifiers 2242 // already. 2243 if (isa<ObjCObjectPointerType>(ToType)) 2244 return Context.getObjCObjectPointerType(ToPointee); 2245 return Context.getPointerType(ToPointee); 2246 } 2247 2248 // Just build a canonical type that has the right qualifiers. 2249 QualType QualifiedCanonToPointee 2250 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2251 2252 if (isa<ObjCObjectPointerType>(ToType)) 2253 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2254 return Context.getPointerType(QualifiedCanonToPointee); 2255 } 2256 2257 static bool isNullPointerConstantForConversion(Expr *Expr, 2258 bool InOverloadResolution, 2259 ASTContext &Context) { 2260 // Handle value-dependent integral null pointer constants correctly. 2261 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2262 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2263 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2264 return !InOverloadResolution; 2265 2266 return Expr->isNullPointerConstant(Context, 2267 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2268 : Expr::NPC_ValueDependentIsNull); 2269 } 2270 2271 /// IsPointerConversion - Determines whether the conversion of the 2272 /// expression From, which has the (possibly adjusted) type FromType, 2273 /// can be converted to the type ToType via a pointer conversion (C++ 2274 /// 4.10). If so, returns true and places the converted type (that 2275 /// might differ from ToType in its cv-qualifiers at some level) into 2276 /// ConvertedType. 2277 /// 2278 /// This routine also supports conversions to and from block pointers 2279 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2280 /// pointers to interfaces. FIXME: Once we've determined the 2281 /// appropriate overloading rules for Objective-C, we may want to 2282 /// split the Objective-C checks into a different routine; however, 2283 /// GCC seems to consider all of these conversions to be pointer 2284 /// conversions, so for now they live here. IncompatibleObjC will be 2285 /// set if the conversion is an allowed Objective-C conversion that 2286 /// should result in a warning. 2287 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2288 bool InOverloadResolution, 2289 QualType& ConvertedType, 2290 bool &IncompatibleObjC) { 2291 IncompatibleObjC = false; 2292 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2293 IncompatibleObjC)) 2294 return true; 2295 2296 // Conversion from a null pointer constant to any Objective-C pointer type. 2297 if (ToType->isObjCObjectPointerType() && 2298 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2299 ConvertedType = ToType; 2300 return true; 2301 } 2302 2303 // Blocks: Block pointers can be converted to void*. 2304 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2305 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2306 ConvertedType = ToType; 2307 return true; 2308 } 2309 // Blocks: A null pointer constant can be converted to a block 2310 // pointer type. 2311 if (ToType->isBlockPointerType() && 2312 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2313 ConvertedType = ToType; 2314 return true; 2315 } 2316 2317 // If the left-hand-side is nullptr_t, the right side can be a null 2318 // pointer constant. 2319 if (ToType->isNullPtrType() && 2320 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2321 ConvertedType = ToType; 2322 return true; 2323 } 2324 2325 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2326 if (!ToTypePtr) 2327 return false; 2328 2329 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2330 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2331 ConvertedType = ToType; 2332 return true; 2333 } 2334 2335 // Beyond this point, both types need to be pointers 2336 // , including objective-c pointers. 2337 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2338 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2339 !getLangOpts().ObjCAutoRefCount) { 2340 ConvertedType = BuildSimilarlyQualifiedPointerType( 2341 FromType->getAs<ObjCObjectPointerType>(), 2342 ToPointeeType, 2343 ToType, Context); 2344 return true; 2345 } 2346 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2347 if (!FromTypePtr) 2348 return false; 2349 2350 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2351 2352 // If the unqualified pointee types are the same, this can't be a 2353 // pointer conversion, so don't do all of the work below. 2354 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2355 return false; 2356 2357 // An rvalue of type "pointer to cv T," where T is an object type, 2358 // can be converted to an rvalue of type "pointer to cv void" (C++ 2359 // 4.10p2). 2360 if (FromPointeeType->isIncompleteOrObjectType() && 2361 ToPointeeType->isVoidType()) { 2362 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2363 ToPointeeType, 2364 ToType, Context, 2365 /*StripObjCLifetime=*/true); 2366 return true; 2367 } 2368 2369 // MSVC allows implicit function to void* type conversion. 2370 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2371 ToPointeeType->isVoidType()) { 2372 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2373 ToPointeeType, 2374 ToType, Context); 2375 return true; 2376 } 2377 2378 // When we're overloading in C, we allow a special kind of pointer 2379 // conversion for compatible-but-not-identical pointee types. 2380 if (!getLangOpts().CPlusPlus && 2381 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2382 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2383 ToPointeeType, 2384 ToType, Context); 2385 return true; 2386 } 2387 2388 // C++ [conv.ptr]p3: 2389 // 2390 // An rvalue of type "pointer to cv D," where D is a class type, 2391 // can be converted to an rvalue of type "pointer to cv B," where 2392 // B is a base class (clause 10) of D. If B is an inaccessible 2393 // (clause 11) or ambiguous (10.2) base class of D, a program that 2394 // necessitates this conversion is ill-formed. The result of the 2395 // conversion is a pointer to the base class sub-object of the 2396 // derived class object. The null pointer value is converted to 2397 // the null pointer value of the destination type. 2398 // 2399 // Note that we do not check for ambiguity or inaccessibility 2400 // here. That is handled by CheckPointerConversion. 2401 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2402 ToPointeeType->isRecordType() && 2403 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2404 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2405 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2406 ToPointeeType, 2407 ToType, Context); 2408 return true; 2409 } 2410 2411 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2412 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2413 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2414 ToPointeeType, 2415 ToType, Context); 2416 return true; 2417 } 2418 2419 return false; 2420 } 2421 2422 /// Adopt the given qualifiers for the given type. 2423 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2424 Qualifiers TQs = T.getQualifiers(); 2425 2426 // Check whether qualifiers already match. 2427 if (TQs == Qs) 2428 return T; 2429 2430 if (Qs.compatiblyIncludes(TQs)) 2431 return Context.getQualifiedType(T, Qs); 2432 2433 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2434 } 2435 2436 /// isObjCPointerConversion - Determines whether this is an 2437 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2438 /// with the same arguments and return values. 2439 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2440 QualType& ConvertedType, 2441 bool &IncompatibleObjC) { 2442 if (!getLangOpts().ObjC) 2443 return false; 2444 2445 // The set of qualifiers on the type we're converting from. 2446 Qualifiers FromQualifiers = FromType.getQualifiers(); 2447 2448 // First, we handle all conversions on ObjC object pointer types. 2449 const ObjCObjectPointerType* ToObjCPtr = 2450 ToType->getAs<ObjCObjectPointerType>(); 2451 const ObjCObjectPointerType *FromObjCPtr = 2452 FromType->getAs<ObjCObjectPointerType>(); 2453 2454 if (ToObjCPtr && FromObjCPtr) { 2455 // If the pointee types are the same (ignoring qualifications), 2456 // then this is not a pointer conversion. 2457 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2458 FromObjCPtr->getPointeeType())) 2459 return false; 2460 2461 // Conversion between Objective-C pointers. 2462 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2463 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2464 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2465 if (getLangOpts().CPlusPlus && LHS && RHS && 2466 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2467 FromObjCPtr->getPointeeType())) 2468 return false; 2469 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2470 ToObjCPtr->getPointeeType(), 2471 ToType, Context); 2472 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2473 return true; 2474 } 2475 2476 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2477 // Okay: this is some kind of implicit downcast of Objective-C 2478 // interfaces, which is permitted. However, we're going to 2479 // complain about it. 2480 IncompatibleObjC = true; 2481 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2482 ToObjCPtr->getPointeeType(), 2483 ToType, Context); 2484 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2485 return true; 2486 } 2487 } 2488 // Beyond this point, both types need to be C pointers or block pointers. 2489 QualType ToPointeeType; 2490 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2491 ToPointeeType = ToCPtr->getPointeeType(); 2492 else if (const BlockPointerType *ToBlockPtr = 2493 ToType->getAs<BlockPointerType>()) { 2494 // Objective C++: We're able to convert from a pointer to any object 2495 // to a block pointer type. 2496 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2497 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2498 return true; 2499 } 2500 ToPointeeType = ToBlockPtr->getPointeeType(); 2501 } 2502 else if (FromType->getAs<BlockPointerType>() && 2503 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2504 // Objective C++: We're able to convert from a block pointer type to a 2505 // pointer to any object. 2506 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2507 return true; 2508 } 2509 else 2510 return false; 2511 2512 QualType FromPointeeType; 2513 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2514 FromPointeeType = FromCPtr->getPointeeType(); 2515 else if (const BlockPointerType *FromBlockPtr = 2516 FromType->getAs<BlockPointerType>()) 2517 FromPointeeType = FromBlockPtr->getPointeeType(); 2518 else 2519 return false; 2520 2521 // If we have pointers to pointers, recursively check whether this 2522 // is an Objective-C conversion. 2523 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2524 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2525 IncompatibleObjC)) { 2526 // We always complain about this conversion. 2527 IncompatibleObjC = true; 2528 ConvertedType = Context.getPointerType(ConvertedType); 2529 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2530 return true; 2531 } 2532 // Allow conversion of pointee being objective-c pointer to another one; 2533 // as in I* to id. 2534 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2535 ToPointeeType->getAs<ObjCObjectPointerType>() && 2536 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2537 IncompatibleObjC)) { 2538 2539 ConvertedType = Context.getPointerType(ConvertedType); 2540 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2541 return true; 2542 } 2543 2544 // If we have pointers to functions or blocks, check whether the only 2545 // differences in the argument and result types are in Objective-C 2546 // pointer conversions. If so, we permit the conversion (but 2547 // complain about it). 2548 const FunctionProtoType *FromFunctionType 2549 = FromPointeeType->getAs<FunctionProtoType>(); 2550 const FunctionProtoType *ToFunctionType 2551 = ToPointeeType->getAs<FunctionProtoType>(); 2552 if (FromFunctionType && ToFunctionType) { 2553 // If the function types are exactly the same, this isn't an 2554 // Objective-C pointer conversion. 2555 if (Context.getCanonicalType(FromPointeeType) 2556 == Context.getCanonicalType(ToPointeeType)) 2557 return false; 2558 2559 // Perform the quick checks that will tell us whether these 2560 // function types are obviously different. 2561 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2562 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2563 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2564 return false; 2565 2566 bool HasObjCConversion = false; 2567 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2568 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2569 // Okay, the types match exactly. Nothing to do. 2570 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2571 ToFunctionType->getReturnType(), 2572 ConvertedType, IncompatibleObjC)) { 2573 // Okay, we have an Objective-C pointer conversion. 2574 HasObjCConversion = true; 2575 } else { 2576 // Function types are too different. Abort. 2577 return false; 2578 } 2579 2580 // Check argument types. 2581 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2582 ArgIdx != NumArgs; ++ArgIdx) { 2583 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2584 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2585 if (Context.getCanonicalType(FromArgType) 2586 == Context.getCanonicalType(ToArgType)) { 2587 // Okay, the types match exactly. Nothing to do. 2588 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2589 ConvertedType, IncompatibleObjC)) { 2590 // Okay, we have an Objective-C pointer conversion. 2591 HasObjCConversion = true; 2592 } else { 2593 // Argument types are too different. Abort. 2594 return false; 2595 } 2596 } 2597 2598 if (HasObjCConversion) { 2599 // We had an Objective-C conversion. Allow this pointer 2600 // conversion, but complain about it. 2601 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2602 IncompatibleObjC = true; 2603 return true; 2604 } 2605 } 2606 2607 return false; 2608 } 2609 2610 /// Determine whether this is an Objective-C writeback conversion, 2611 /// used for parameter passing when performing automatic reference counting. 2612 /// 2613 /// \param FromType The type we're converting form. 2614 /// 2615 /// \param ToType The type we're converting to. 2616 /// 2617 /// \param ConvertedType The type that will be produced after applying 2618 /// this conversion. 2619 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2620 QualType &ConvertedType) { 2621 if (!getLangOpts().ObjCAutoRefCount || 2622 Context.hasSameUnqualifiedType(FromType, ToType)) 2623 return false; 2624 2625 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2626 QualType ToPointee; 2627 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2628 ToPointee = ToPointer->getPointeeType(); 2629 else 2630 return false; 2631 2632 Qualifiers ToQuals = ToPointee.getQualifiers(); 2633 if (!ToPointee->isObjCLifetimeType() || 2634 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2635 !ToQuals.withoutObjCLifetime().empty()) 2636 return false; 2637 2638 // Argument must be a pointer to __strong to __weak. 2639 QualType FromPointee; 2640 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2641 FromPointee = FromPointer->getPointeeType(); 2642 else 2643 return false; 2644 2645 Qualifiers FromQuals = FromPointee.getQualifiers(); 2646 if (!FromPointee->isObjCLifetimeType() || 2647 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2648 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2649 return false; 2650 2651 // Make sure that we have compatible qualifiers. 2652 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2653 if (!ToQuals.compatiblyIncludes(FromQuals)) 2654 return false; 2655 2656 // Remove qualifiers from the pointee type we're converting from; they 2657 // aren't used in the compatibility check belong, and we'll be adding back 2658 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2659 FromPointee = FromPointee.getUnqualifiedType(); 2660 2661 // The unqualified form of the pointee types must be compatible. 2662 ToPointee = ToPointee.getUnqualifiedType(); 2663 bool IncompatibleObjC; 2664 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2665 FromPointee = ToPointee; 2666 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2667 IncompatibleObjC)) 2668 return false; 2669 2670 /// Construct the type we're converting to, which is a pointer to 2671 /// __autoreleasing pointee. 2672 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2673 ConvertedType = Context.getPointerType(FromPointee); 2674 return true; 2675 } 2676 2677 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2678 QualType& ConvertedType) { 2679 QualType ToPointeeType; 2680 if (const BlockPointerType *ToBlockPtr = 2681 ToType->getAs<BlockPointerType>()) 2682 ToPointeeType = ToBlockPtr->getPointeeType(); 2683 else 2684 return false; 2685 2686 QualType FromPointeeType; 2687 if (const BlockPointerType *FromBlockPtr = 2688 FromType->getAs<BlockPointerType>()) 2689 FromPointeeType = FromBlockPtr->getPointeeType(); 2690 else 2691 return false; 2692 // We have pointer to blocks, check whether the only 2693 // differences in the argument and result types are in Objective-C 2694 // pointer conversions. If so, we permit the conversion. 2695 2696 const FunctionProtoType *FromFunctionType 2697 = FromPointeeType->getAs<FunctionProtoType>(); 2698 const FunctionProtoType *ToFunctionType 2699 = ToPointeeType->getAs<FunctionProtoType>(); 2700 2701 if (!FromFunctionType || !ToFunctionType) 2702 return false; 2703 2704 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2705 return true; 2706 2707 // Perform the quick checks that will tell us whether these 2708 // function types are obviously different. 2709 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2710 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2711 return false; 2712 2713 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2714 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2715 if (FromEInfo != ToEInfo) 2716 return false; 2717 2718 bool IncompatibleObjC = false; 2719 if (Context.hasSameType(FromFunctionType->getReturnType(), 2720 ToFunctionType->getReturnType())) { 2721 // Okay, the types match exactly. Nothing to do. 2722 } else { 2723 QualType RHS = FromFunctionType->getReturnType(); 2724 QualType LHS = ToFunctionType->getReturnType(); 2725 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2726 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2727 LHS = LHS.getUnqualifiedType(); 2728 2729 if (Context.hasSameType(RHS,LHS)) { 2730 // OK exact match. 2731 } else if (isObjCPointerConversion(RHS, LHS, 2732 ConvertedType, IncompatibleObjC)) { 2733 if (IncompatibleObjC) 2734 return false; 2735 // Okay, we have an Objective-C pointer conversion. 2736 } 2737 else 2738 return false; 2739 } 2740 2741 // Check argument types. 2742 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2743 ArgIdx != NumArgs; ++ArgIdx) { 2744 IncompatibleObjC = false; 2745 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2746 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2747 if (Context.hasSameType(FromArgType, ToArgType)) { 2748 // Okay, the types match exactly. Nothing to do. 2749 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2750 ConvertedType, IncompatibleObjC)) { 2751 if (IncompatibleObjC) 2752 return false; 2753 // Okay, we have an Objective-C pointer conversion. 2754 } else 2755 // Argument types are too different. Abort. 2756 return false; 2757 } 2758 2759 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2760 bool CanUseToFPT, CanUseFromFPT; 2761 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2762 CanUseToFPT, CanUseFromFPT, 2763 NewParamInfos)) 2764 return false; 2765 2766 ConvertedType = ToType; 2767 return true; 2768 } 2769 2770 enum { 2771 ft_default, 2772 ft_different_class, 2773 ft_parameter_arity, 2774 ft_parameter_mismatch, 2775 ft_return_type, 2776 ft_qualifer_mismatch, 2777 ft_noexcept 2778 }; 2779 2780 /// Attempts to get the FunctionProtoType from a Type. Handles 2781 /// MemberFunctionPointers properly. 2782 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2783 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2784 return FPT; 2785 2786 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2787 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2788 2789 return nullptr; 2790 } 2791 2792 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2793 /// function types. Catches different number of parameter, mismatch in 2794 /// parameter types, and different return types. 2795 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2796 QualType FromType, QualType ToType) { 2797 // If either type is not valid, include no extra info. 2798 if (FromType.isNull() || ToType.isNull()) { 2799 PDiag << ft_default; 2800 return; 2801 } 2802 2803 // Get the function type from the pointers. 2804 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2805 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2806 *ToMember = ToType->getAs<MemberPointerType>(); 2807 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2808 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2809 << QualType(FromMember->getClass(), 0); 2810 return; 2811 } 2812 FromType = FromMember->getPointeeType(); 2813 ToType = ToMember->getPointeeType(); 2814 } 2815 2816 if (FromType->isPointerType()) 2817 FromType = FromType->getPointeeType(); 2818 if (ToType->isPointerType()) 2819 ToType = ToType->getPointeeType(); 2820 2821 // Remove references. 2822 FromType = FromType.getNonReferenceType(); 2823 ToType = ToType.getNonReferenceType(); 2824 2825 // Don't print extra info for non-specialized template functions. 2826 if (FromType->isInstantiationDependentType() && 2827 !FromType->getAs<TemplateSpecializationType>()) { 2828 PDiag << ft_default; 2829 return; 2830 } 2831 2832 // No extra info for same types. 2833 if (Context.hasSameType(FromType, ToType)) { 2834 PDiag << ft_default; 2835 return; 2836 } 2837 2838 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2839 *ToFunction = tryGetFunctionProtoType(ToType); 2840 2841 // Both types need to be function types. 2842 if (!FromFunction || !ToFunction) { 2843 PDiag << ft_default; 2844 return; 2845 } 2846 2847 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2848 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2849 << FromFunction->getNumParams(); 2850 return; 2851 } 2852 2853 // Handle different parameter types. 2854 unsigned ArgPos; 2855 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2856 PDiag << ft_parameter_mismatch << ArgPos + 1 2857 << ToFunction->getParamType(ArgPos) 2858 << FromFunction->getParamType(ArgPos); 2859 return; 2860 } 2861 2862 // Handle different return type. 2863 if (!Context.hasSameType(FromFunction->getReturnType(), 2864 ToFunction->getReturnType())) { 2865 PDiag << ft_return_type << ToFunction->getReturnType() 2866 << FromFunction->getReturnType(); 2867 return; 2868 } 2869 2870 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2871 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2872 << FromFunction->getMethodQuals(); 2873 return; 2874 } 2875 2876 // Handle exception specification differences on canonical type (in C++17 2877 // onwards). 2878 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2879 ->isNothrow() != 2880 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2881 ->isNothrow()) { 2882 PDiag << ft_noexcept; 2883 return; 2884 } 2885 2886 // Unable to find a difference, so add no extra info. 2887 PDiag << ft_default; 2888 } 2889 2890 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2891 /// for equality of their argument types. Caller has already checked that 2892 /// they have same number of arguments. If the parameters are different, 2893 /// ArgPos will have the parameter index of the first different parameter. 2894 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2895 const FunctionProtoType *NewType, 2896 unsigned *ArgPos) { 2897 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2898 N = NewType->param_type_begin(), 2899 E = OldType->param_type_end(); 2900 O && (O != E); ++O, ++N) { 2901 if (!Context.hasSameType(O->getUnqualifiedType(), 2902 N->getUnqualifiedType())) { 2903 if (ArgPos) 2904 *ArgPos = O - OldType->param_type_begin(); 2905 return false; 2906 } 2907 } 2908 return true; 2909 } 2910 2911 /// CheckPointerConversion - Check the pointer conversion from the 2912 /// expression From to the type ToType. This routine checks for 2913 /// ambiguous or inaccessible derived-to-base pointer 2914 /// conversions for which IsPointerConversion has already returned 2915 /// true. It returns true and produces a diagnostic if there was an 2916 /// error, or returns false otherwise. 2917 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2918 CastKind &Kind, 2919 CXXCastPath& BasePath, 2920 bool IgnoreBaseAccess, 2921 bool Diagnose) { 2922 QualType FromType = From->getType(); 2923 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2924 2925 Kind = CK_BitCast; 2926 2927 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2928 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2929 Expr::NPCK_ZeroExpression) { 2930 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2931 DiagRuntimeBehavior(From->getExprLoc(), From, 2932 PDiag(diag::warn_impcast_bool_to_null_pointer) 2933 << ToType << From->getSourceRange()); 2934 else if (!isUnevaluatedContext()) 2935 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2936 << ToType << From->getSourceRange(); 2937 } 2938 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2939 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2940 QualType FromPointeeType = FromPtrType->getPointeeType(), 2941 ToPointeeType = ToPtrType->getPointeeType(); 2942 2943 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2944 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2945 // We must have a derived-to-base conversion. Check an 2946 // ambiguous or inaccessible conversion. 2947 unsigned InaccessibleID = 0; 2948 unsigned AmbigiousID = 0; 2949 if (Diagnose) { 2950 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2951 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2952 } 2953 if (CheckDerivedToBaseConversion( 2954 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2955 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2956 &BasePath, IgnoreBaseAccess)) 2957 return true; 2958 2959 // The conversion was successful. 2960 Kind = CK_DerivedToBase; 2961 } 2962 2963 if (Diagnose && !IsCStyleOrFunctionalCast && 2964 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2965 assert(getLangOpts().MSVCCompat && 2966 "this should only be possible with MSVCCompat!"); 2967 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2968 << From->getSourceRange(); 2969 } 2970 } 2971 } else if (const ObjCObjectPointerType *ToPtrType = 2972 ToType->getAs<ObjCObjectPointerType>()) { 2973 if (const ObjCObjectPointerType *FromPtrType = 2974 FromType->getAs<ObjCObjectPointerType>()) { 2975 // Objective-C++ conversions are always okay. 2976 // FIXME: We should have a different class of conversions for the 2977 // Objective-C++ implicit conversions. 2978 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2979 return false; 2980 } else if (FromType->isBlockPointerType()) { 2981 Kind = CK_BlockPointerToObjCPointerCast; 2982 } else { 2983 Kind = CK_CPointerToObjCPointerCast; 2984 } 2985 } else if (ToType->isBlockPointerType()) { 2986 if (!FromType->isBlockPointerType()) 2987 Kind = CK_AnyPointerToBlockPointerCast; 2988 } 2989 2990 // We shouldn't fall into this case unless it's valid for other 2991 // reasons. 2992 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2993 Kind = CK_NullToPointer; 2994 2995 return false; 2996 } 2997 2998 /// IsMemberPointerConversion - Determines whether the conversion of the 2999 /// expression From, which has the (possibly adjusted) type FromType, can be 3000 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3001 /// If so, returns true and places the converted type (that might differ from 3002 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3003 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3004 QualType ToType, 3005 bool InOverloadResolution, 3006 QualType &ConvertedType) { 3007 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3008 if (!ToTypePtr) 3009 return false; 3010 3011 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3012 if (From->isNullPointerConstant(Context, 3013 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3014 : Expr::NPC_ValueDependentIsNull)) { 3015 ConvertedType = ToType; 3016 return true; 3017 } 3018 3019 // Otherwise, both types have to be member pointers. 3020 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3021 if (!FromTypePtr) 3022 return false; 3023 3024 // A pointer to member of B can be converted to a pointer to member of D, 3025 // where D is derived from B (C++ 4.11p2). 3026 QualType FromClass(FromTypePtr->getClass(), 0); 3027 QualType ToClass(ToTypePtr->getClass(), 0); 3028 3029 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3030 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3031 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3032 ToClass.getTypePtr()); 3033 return true; 3034 } 3035 3036 return false; 3037 } 3038 3039 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3040 /// expression From to the type ToType. This routine checks for ambiguous or 3041 /// virtual or inaccessible base-to-derived member pointer conversions 3042 /// for which IsMemberPointerConversion has already returned true. It returns 3043 /// true and produces a diagnostic if there was an error, or returns false 3044 /// otherwise. 3045 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3046 CastKind &Kind, 3047 CXXCastPath &BasePath, 3048 bool IgnoreBaseAccess) { 3049 QualType FromType = From->getType(); 3050 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3051 if (!FromPtrType) { 3052 // This must be a null pointer to member pointer conversion 3053 assert(From->isNullPointerConstant(Context, 3054 Expr::NPC_ValueDependentIsNull) && 3055 "Expr must be null pointer constant!"); 3056 Kind = CK_NullToMemberPointer; 3057 return false; 3058 } 3059 3060 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3061 assert(ToPtrType && "No member pointer cast has a target type " 3062 "that is not a member pointer."); 3063 3064 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3065 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3066 3067 // FIXME: What about dependent types? 3068 assert(FromClass->isRecordType() && "Pointer into non-class."); 3069 assert(ToClass->isRecordType() && "Pointer into non-class."); 3070 3071 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3072 /*DetectVirtual=*/true); 3073 bool DerivationOkay = 3074 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3075 assert(DerivationOkay && 3076 "Should not have been called if derivation isn't OK."); 3077 (void)DerivationOkay; 3078 3079 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3080 getUnqualifiedType())) { 3081 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3082 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3083 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3084 return true; 3085 } 3086 3087 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3088 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3089 << FromClass << ToClass << QualType(VBase, 0) 3090 << From->getSourceRange(); 3091 return true; 3092 } 3093 3094 if (!IgnoreBaseAccess) 3095 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3096 Paths.front(), 3097 diag::err_downcast_from_inaccessible_base); 3098 3099 // Must be a base to derived member conversion. 3100 BuildBasePathArray(Paths, BasePath); 3101 Kind = CK_BaseToDerivedMemberPointer; 3102 return false; 3103 } 3104 3105 /// Determine whether the lifetime conversion between the two given 3106 /// qualifiers sets is nontrivial. 3107 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3108 Qualifiers ToQuals) { 3109 // Converting anything to const __unsafe_unretained is trivial. 3110 if (ToQuals.hasConst() && 3111 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3112 return false; 3113 3114 return true; 3115 } 3116 3117 /// IsQualificationConversion - Determines whether the conversion from 3118 /// an rvalue of type FromType to ToType is a qualification conversion 3119 /// (C++ 4.4). 3120 /// 3121 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3122 /// when the qualification conversion involves a change in the Objective-C 3123 /// object lifetime. 3124 bool 3125 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3126 bool CStyle, bool &ObjCLifetimeConversion) { 3127 FromType = Context.getCanonicalType(FromType); 3128 ToType = Context.getCanonicalType(ToType); 3129 ObjCLifetimeConversion = false; 3130 3131 // If FromType and ToType are the same type, this is not a 3132 // qualification conversion. 3133 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3134 return false; 3135 3136 // (C++ 4.4p4): 3137 // A conversion can add cv-qualifiers at levels other than the first 3138 // in multi-level pointers, subject to the following rules: [...] 3139 bool PreviousToQualsIncludeConst = true; 3140 bool UnwrappedAnyPointer = false; 3141 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3142 // Within each iteration of the loop, we check the qualifiers to 3143 // determine if this still looks like a qualification 3144 // conversion. Then, if all is well, we unwrap one more level of 3145 // pointers or pointers-to-members and do it all again 3146 // until there are no more pointers or pointers-to-members left to 3147 // unwrap. 3148 UnwrappedAnyPointer = true; 3149 3150 Qualifiers FromQuals = FromType.getQualifiers(); 3151 Qualifiers ToQuals = ToType.getQualifiers(); 3152 3153 // Ignore __unaligned qualifier if this type is void. 3154 if (ToType.getUnqualifiedType()->isVoidType()) 3155 FromQuals.removeUnaligned(); 3156 3157 // Objective-C ARC: 3158 // Check Objective-C lifetime conversions. 3159 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3160 UnwrappedAnyPointer) { 3161 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3162 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3163 ObjCLifetimeConversion = true; 3164 FromQuals.removeObjCLifetime(); 3165 ToQuals.removeObjCLifetime(); 3166 } else { 3167 // Qualification conversions cannot cast between different 3168 // Objective-C lifetime qualifiers. 3169 return false; 3170 } 3171 } 3172 3173 // Allow addition/removal of GC attributes but not changing GC attributes. 3174 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3175 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3176 FromQuals.removeObjCGCAttr(); 3177 ToQuals.removeObjCGCAttr(); 3178 } 3179 3180 // -- for every j > 0, if const is in cv 1,j then const is in cv 3181 // 2,j, and similarly for volatile. 3182 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3183 return false; 3184 3185 // -- if the cv 1,j and cv 2,j are different, then const is in 3186 // every cv for 0 < k < j. 3187 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3188 && !PreviousToQualsIncludeConst) 3189 return false; 3190 3191 // Keep track of whether all prior cv-qualifiers in the "to" type 3192 // include const. 3193 PreviousToQualsIncludeConst 3194 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3195 } 3196 3197 // Allows address space promotion by language rules implemented in 3198 // Type::Qualifiers::isAddressSpaceSupersetOf. 3199 Qualifiers FromQuals = FromType.getQualifiers(); 3200 Qualifiers ToQuals = ToType.getQualifiers(); 3201 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3202 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3203 return false; 3204 } 3205 3206 // We are left with FromType and ToType being the pointee types 3207 // after unwrapping the original FromType and ToType the same number 3208 // of types. If we unwrapped any pointers, and if FromType and 3209 // ToType have the same unqualified type (since we checked 3210 // qualifiers above), then this is a qualification conversion. 3211 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3212 } 3213 3214 /// - Determine whether this is a conversion from a scalar type to an 3215 /// atomic type. 3216 /// 3217 /// If successful, updates \c SCS's second and third steps in the conversion 3218 /// sequence to finish the conversion. 3219 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3220 bool InOverloadResolution, 3221 StandardConversionSequence &SCS, 3222 bool CStyle) { 3223 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3224 if (!ToAtomic) 3225 return false; 3226 3227 StandardConversionSequence InnerSCS; 3228 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3229 InOverloadResolution, InnerSCS, 3230 CStyle, /*AllowObjCWritebackConversion=*/false)) 3231 return false; 3232 3233 SCS.Second = InnerSCS.Second; 3234 SCS.setToType(1, InnerSCS.getToType(1)); 3235 SCS.Third = InnerSCS.Third; 3236 SCS.QualificationIncludesObjCLifetime 3237 = InnerSCS.QualificationIncludesObjCLifetime; 3238 SCS.setToType(2, InnerSCS.getToType(2)); 3239 return true; 3240 } 3241 3242 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3243 CXXConstructorDecl *Constructor, 3244 QualType Type) { 3245 const FunctionProtoType *CtorType = 3246 Constructor->getType()->getAs<FunctionProtoType>(); 3247 if (CtorType->getNumParams() > 0) { 3248 QualType FirstArg = CtorType->getParamType(0); 3249 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3250 return true; 3251 } 3252 return false; 3253 } 3254 3255 static OverloadingResult 3256 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3257 CXXRecordDecl *To, 3258 UserDefinedConversionSequence &User, 3259 OverloadCandidateSet &CandidateSet, 3260 bool AllowExplicit) { 3261 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3262 for (auto *D : S.LookupConstructors(To)) { 3263 auto Info = getConstructorInfo(D); 3264 if (!Info) 3265 continue; 3266 3267 bool Usable = !Info.Constructor->isInvalidDecl() && 3268 S.isInitListConstructor(Info.Constructor) && 3269 (AllowExplicit || !Info.Constructor->isExplicit()); 3270 if (Usable) { 3271 // If the first argument is (a reference to) the target type, 3272 // suppress conversions. 3273 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3274 S.Context, Info.Constructor, ToType); 3275 if (Info.ConstructorTmpl) 3276 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3277 /*ExplicitArgs*/ nullptr, From, 3278 CandidateSet, SuppressUserConversions, 3279 /*PartialOverloading*/ false, 3280 AllowExplicit); 3281 else 3282 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3283 CandidateSet, SuppressUserConversions, 3284 /*PartialOverloading*/ false, AllowExplicit); 3285 } 3286 } 3287 3288 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3289 3290 OverloadCandidateSet::iterator Best; 3291 switch (auto Result = 3292 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3293 case OR_Deleted: 3294 case OR_Success: { 3295 // Record the standard conversion we used and the conversion function. 3296 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3297 QualType ThisType = Constructor->getThisType(); 3298 // Initializer lists don't have conversions as such. 3299 User.Before.setAsIdentityConversion(); 3300 User.HadMultipleCandidates = HadMultipleCandidates; 3301 User.ConversionFunction = Constructor; 3302 User.FoundConversionFunction = Best->FoundDecl; 3303 User.After.setAsIdentityConversion(); 3304 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3305 User.After.setAllToTypes(ToType); 3306 return Result; 3307 } 3308 3309 case OR_No_Viable_Function: 3310 return OR_No_Viable_Function; 3311 case OR_Ambiguous: 3312 return OR_Ambiguous; 3313 } 3314 3315 llvm_unreachable("Invalid OverloadResult!"); 3316 } 3317 3318 /// Determines whether there is a user-defined conversion sequence 3319 /// (C++ [over.ics.user]) that converts expression From to the type 3320 /// ToType. If such a conversion exists, User will contain the 3321 /// user-defined conversion sequence that performs such a conversion 3322 /// and this routine will return true. Otherwise, this routine returns 3323 /// false and User is unspecified. 3324 /// 3325 /// \param AllowExplicit true if the conversion should consider C++0x 3326 /// "explicit" conversion functions as well as non-explicit conversion 3327 /// functions (C++0x [class.conv.fct]p2). 3328 /// 3329 /// \param AllowObjCConversionOnExplicit true if the conversion should 3330 /// allow an extra Objective-C pointer conversion on uses of explicit 3331 /// constructors. Requires \c AllowExplicit to also be set. 3332 static OverloadingResult 3333 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3334 UserDefinedConversionSequence &User, 3335 OverloadCandidateSet &CandidateSet, 3336 bool AllowExplicit, 3337 bool AllowObjCConversionOnExplicit) { 3338 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3339 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3340 3341 // Whether we will only visit constructors. 3342 bool ConstructorsOnly = false; 3343 3344 // If the type we are conversion to is a class type, enumerate its 3345 // constructors. 3346 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3347 // C++ [over.match.ctor]p1: 3348 // When objects of class type are direct-initialized (8.5), or 3349 // copy-initialized from an expression of the same or a 3350 // derived class type (8.5), overload resolution selects the 3351 // constructor. [...] For copy-initialization, the candidate 3352 // functions are all the converting constructors (12.3.1) of 3353 // that class. The argument list is the expression-list within 3354 // the parentheses of the initializer. 3355 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3356 (From->getType()->getAs<RecordType>() && 3357 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3358 ConstructorsOnly = true; 3359 3360 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3361 // We're not going to find any constructors. 3362 } else if (CXXRecordDecl *ToRecordDecl 3363 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3364 3365 Expr **Args = &From; 3366 unsigned NumArgs = 1; 3367 bool ListInitializing = false; 3368 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3369 // But first, see if there is an init-list-constructor that will work. 3370 OverloadingResult Result = IsInitializerListConstructorConversion( 3371 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3372 if (Result != OR_No_Viable_Function) 3373 return Result; 3374 // Never mind. 3375 CandidateSet.clear( 3376 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3377 3378 // If we're list-initializing, we pass the individual elements as 3379 // arguments, not the entire list. 3380 Args = InitList->getInits(); 3381 NumArgs = InitList->getNumInits(); 3382 ListInitializing = true; 3383 } 3384 3385 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3386 auto Info = getConstructorInfo(D); 3387 if (!Info) 3388 continue; 3389 3390 bool Usable = !Info.Constructor->isInvalidDecl(); 3391 if (ListInitializing) 3392 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3393 else 3394 Usable = Usable && 3395 Info.Constructor->isConvertingConstructor(AllowExplicit); 3396 if (Usable) { 3397 bool SuppressUserConversions = !ConstructorsOnly; 3398 if (SuppressUserConversions && ListInitializing) { 3399 SuppressUserConversions = false; 3400 if (NumArgs == 1) { 3401 // If the first argument is (a reference to) the target type, 3402 // suppress conversions. 3403 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3404 S.Context, Info.Constructor, ToType); 3405 } 3406 } 3407 if (Info.ConstructorTmpl) 3408 S.AddTemplateOverloadCandidate( 3409 Info.ConstructorTmpl, Info.FoundDecl, 3410 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3411 CandidateSet, SuppressUserConversions, 3412 /*PartialOverloading*/ false, AllowExplicit); 3413 else 3414 // Allow one user-defined conversion when user specifies a 3415 // From->ToType conversion via an static cast (c-style, etc). 3416 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3417 llvm::makeArrayRef(Args, NumArgs), 3418 CandidateSet, SuppressUserConversions, 3419 /*PartialOverloading*/ false, AllowExplicit); 3420 } 3421 } 3422 } 3423 } 3424 3425 // Enumerate conversion functions, if we're allowed to. 3426 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3427 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3428 // No conversion functions from incomplete types. 3429 } else if (const RecordType *FromRecordType = 3430 From->getType()->getAs<RecordType>()) { 3431 if (CXXRecordDecl *FromRecordDecl 3432 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3433 // Add all of the conversion functions as candidates. 3434 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3435 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3436 DeclAccessPair FoundDecl = I.getPair(); 3437 NamedDecl *D = FoundDecl.getDecl(); 3438 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3439 if (isa<UsingShadowDecl>(D)) 3440 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3441 3442 CXXConversionDecl *Conv; 3443 FunctionTemplateDecl *ConvTemplate; 3444 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3445 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3446 else 3447 Conv = cast<CXXConversionDecl>(D); 3448 3449 if (AllowExplicit || !Conv->isExplicit()) { 3450 if (ConvTemplate) 3451 S.AddTemplateConversionCandidate( 3452 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3453 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3454 else 3455 S.AddConversionCandidate( 3456 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3457 AllowObjCConversionOnExplicit, AllowExplicit); 3458 } 3459 } 3460 } 3461 } 3462 3463 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3464 3465 OverloadCandidateSet::iterator Best; 3466 switch (auto Result = 3467 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3468 case OR_Success: 3469 case OR_Deleted: 3470 // Record the standard conversion we used and the conversion function. 3471 if (CXXConstructorDecl *Constructor 3472 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3473 // C++ [over.ics.user]p1: 3474 // If the user-defined conversion is specified by a 3475 // constructor (12.3.1), the initial standard conversion 3476 // sequence converts the source type to the type required by 3477 // the argument of the constructor. 3478 // 3479 QualType ThisType = Constructor->getThisType(); 3480 if (isa<InitListExpr>(From)) { 3481 // Initializer lists don't have conversions as such. 3482 User.Before.setAsIdentityConversion(); 3483 } else { 3484 if (Best->Conversions[0].isEllipsis()) 3485 User.EllipsisConversion = true; 3486 else { 3487 User.Before = Best->Conversions[0].Standard; 3488 User.EllipsisConversion = false; 3489 } 3490 } 3491 User.HadMultipleCandidates = HadMultipleCandidates; 3492 User.ConversionFunction = Constructor; 3493 User.FoundConversionFunction = Best->FoundDecl; 3494 User.After.setAsIdentityConversion(); 3495 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3496 User.After.setAllToTypes(ToType); 3497 return Result; 3498 } 3499 if (CXXConversionDecl *Conversion 3500 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3501 // C++ [over.ics.user]p1: 3502 // 3503 // [...] If the user-defined conversion is specified by a 3504 // conversion function (12.3.2), the initial standard 3505 // conversion sequence converts the source type to the 3506 // implicit object parameter of the conversion function. 3507 User.Before = Best->Conversions[0].Standard; 3508 User.HadMultipleCandidates = HadMultipleCandidates; 3509 User.ConversionFunction = Conversion; 3510 User.FoundConversionFunction = Best->FoundDecl; 3511 User.EllipsisConversion = false; 3512 3513 // C++ [over.ics.user]p2: 3514 // The second standard conversion sequence converts the 3515 // result of the user-defined conversion to the target type 3516 // for the sequence. Since an implicit conversion sequence 3517 // is an initialization, the special rules for 3518 // initialization by user-defined conversion apply when 3519 // selecting the best user-defined conversion for a 3520 // user-defined conversion sequence (see 13.3.3 and 3521 // 13.3.3.1). 3522 User.After = Best->FinalConversion; 3523 return Result; 3524 } 3525 llvm_unreachable("Not a constructor or conversion function?"); 3526 3527 case OR_No_Viable_Function: 3528 return OR_No_Viable_Function; 3529 3530 case OR_Ambiguous: 3531 return OR_Ambiguous; 3532 } 3533 3534 llvm_unreachable("Invalid OverloadResult!"); 3535 } 3536 3537 bool 3538 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3539 ImplicitConversionSequence ICS; 3540 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3541 OverloadCandidateSet::CSK_Normal); 3542 OverloadingResult OvResult = 3543 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3544 CandidateSet, false, false); 3545 3546 if (!(OvResult == OR_Ambiguous || 3547 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3548 return false; 3549 3550 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From); 3551 if (OvResult == OR_Ambiguous) 3552 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3553 << From->getType() << ToType << From->getSourceRange(); 3554 else { // OR_No_Viable_Function && !CandidateSet.empty() 3555 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3556 diag::err_typecheck_nonviable_condition_incomplete, 3557 From->getType(), From->getSourceRange())) 3558 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3559 << false << From->getType() << From->getSourceRange() << ToType; 3560 } 3561 3562 CandidateSet.NoteCandidates( 3563 *this, From, Cands); 3564 return true; 3565 } 3566 3567 /// Compare the user-defined conversion functions or constructors 3568 /// of two user-defined conversion sequences to determine whether any ordering 3569 /// is possible. 3570 static ImplicitConversionSequence::CompareKind 3571 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3572 FunctionDecl *Function2) { 3573 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3574 return ImplicitConversionSequence::Indistinguishable; 3575 3576 // Objective-C++: 3577 // If both conversion functions are implicitly-declared conversions from 3578 // a lambda closure type to a function pointer and a block pointer, 3579 // respectively, always prefer the conversion to a function pointer, 3580 // because the function pointer is more lightweight and is more likely 3581 // to keep code working. 3582 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3583 if (!Conv1) 3584 return ImplicitConversionSequence::Indistinguishable; 3585 3586 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3587 if (!Conv2) 3588 return ImplicitConversionSequence::Indistinguishable; 3589 3590 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3591 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3592 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3593 if (Block1 != Block2) 3594 return Block1 ? ImplicitConversionSequence::Worse 3595 : ImplicitConversionSequence::Better; 3596 } 3597 3598 return ImplicitConversionSequence::Indistinguishable; 3599 } 3600 3601 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3602 const ImplicitConversionSequence &ICS) { 3603 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3604 (ICS.isUserDefined() && 3605 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3606 } 3607 3608 /// CompareImplicitConversionSequences - Compare two implicit 3609 /// conversion sequences to determine whether one is better than the 3610 /// other or if they are indistinguishable (C++ 13.3.3.2). 3611 static ImplicitConversionSequence::CompareKind 3612 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3613 const ImplicitConversionSequence& ICS1, 3614 const ImplicitConversionSequence& ICS2) 3615 { 3616 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3617 // conversion sequences (as defined in 13.3.3.1) 3618 // -- a standard conversion sequence (13.3.3.1.1) is a better 3619 // conversion sequence than a user-defined conversion sequence or 3620 // an ellipsis conversion sequence, and 3621 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3622 // conversion sequence than an ellipsis conversion sequence 3623 // (13.3.3.1.3). 3624 // 3625 // C++0x [over.best.ics]p10: 3626 // For the purpose of ranking implicit conversion sequences as 3627 // described in 13.3.3.2, the ambiguous conversion sequence is 3628 // treated as a user-defined sequence that is indistinguishable 3629 // from any other user-defined conversion sequence. 3630 3631 // String literal to 'char *' conversion has been deprecated in C++03. It has 3632 // been removed from C++11. We still accept this conversion, if it happens at 3633 // the best viable function. Otherwise, this conversion is considered worse 3634 // than ellipsis conversion. Consider this as an extension; this is not in the 3635 // standard. For example: 3636 // 3637 // int &f(...); // #1 3638 // void f(char*); // #2 3639 // void g() { int &r = f("foo"); } 3640 // 3641 // In C++03, we pick #2 as the best viable function. 3642 // In C++11, we pick #1 as the best viable function, because ellipsis 3643 // conversion is better than string-literal to char* conversion (since there 3644 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3645 // convert arguments, #2 would be the best viable function in C++11. 3646 // If the best viable function has this conversion, a warning will be issued 3647 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3648 3649 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3650 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3651 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3652 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3653 ? ImplicitConversionSequence::Worse 3654 : ImplicitConversionSequence::Better; 3655 3656 if (ICS1.getKindRank() < ICS2.getKindRank()) 3657 return ImplicitConversionSequence::Better; 3658 if (ICS2.getKindRank() < ICS1.getKindRank()) 3659 return ImplicitConversionSequence::Worse; 3660 3661 // The following checks require both conversion sequences to be of 3662 // the same kind. 3663 if (ICS1.getKind() != ICS2.getKind()) 3664 return ImplicitConversionSequence::Indistinguishable; 3665 3666 ImplicitConversionSequence::CompareKind Result = 3667 ImplicitConversionSequence::Indistinguishable; 3668 3669 // Two implicit conversion sequences of the same form are 3670 // indistinguishable conversion sequences unless one of the 3671 // following rules apply: (C++ 13.3.3.2p3): 3672 3673 // List-initialization sequence L1 is a better conversion sequence than 3674 // list-initialization sequence L2 if: 3675 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3676 // if not that, 3677 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3678 // and N1 is smaller than N2., 3679 // even if one of the other rules in this paragraph would otherwise apply. 3680 if (!ICS1.isBad()) { 3681 if (ICS1.isStdInitializerListElement() && 3682 !ICS2.isStdInitializerListElement()) 3683 return ImplicitConversionSequence::Better; 3684 if (!ICS1.isStdInitializerListElement() && 3685 ICS2.isStdInitializerListElement()) 3686 return ImplicitConversionSequence::Worse; 3687 } 3688 3689 if (ICS1.isStandard()) 3690 // Standard conversion sequence S1 is a better conversion sequence than 3691 // standard conversion sequence S2 if [...] 3692 Result = CompareStandardConversionSequences(S, Loc, 3693 ICS1.Standard, ICS2.Standard); 3694 else if (ICS1.isUserDefined()) { 3695 // User-defined conversion sequence U1 is a better conversion 3696 // sequence than another user-defined conversion sequence U2 if 3697 // they contain the same user-defined conversion function or 3698 // constructor and if the second standard conversion sequence of 3699 // U1 is better than the second standard conversion sequence of 3700 // U2 (C++ 13.3.3.2p3). 3701 if (ICS1.UserDefined.ConversionFunction == 3702 ICS2.UserDefined.ConversionFunction) 3703 Result = CompareStandardConversionSequences(S, Loc, 3704 ICS1.UserDefined.After, 3705 ICS2.UserDefined.After); 3706 else 3707 Result = compareConversionFunctions(S, 3708 ICS1.UserDefined.ConversionFunction, 3709 ICS2.UserDefined.ConversionFunction); 3710 } 3711 3712 return Result; 3713 } 3714 3715 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3716 // determine if one is a proper subset of the other. 3717 static ImplicitConversionSequence::CompareKind 3718 compareStandardConversionSubsets(ASTContext &Context, 3719 const StandardConversionSequence& SCS1, 3720 const StandardConversionSequence& SCS2) { 3721 ImplicitConversionSequence::CompareKind Result 3722 = ImplicitConversionSequence::Indistinguishable; 3723 3724 // the identity conversion sequence is considered to be a subsequence of 3725 // any non-identity conversion sequence 3726 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3727 return ImplicitConversionSequence::Better; 3728 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3729 return ImplicitConversionSequence::Worse; 3730 3731 if (SCS1.Second != SCS2.Second) { 3732 if (SCS1.Second == ICK_Identity) 3733 Result = ImplicitConversionSequence::Better; 3734 else if (SCS2.Second == ICK_Identity) 3735 Result = ImplicitConversionSequence::Worse; 3736 else 3737 return ImplicitConversionSequence::Indistinguishable; 3738 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3739 return ImplicitConversionSequence::Indistinguishable; 3740 3741 if (SCS1.Third == SCS2.Third) { 3742 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3743 : ImplicitConversionSequence::Indistinguishable; 3744 } 3745 3746 if (SCS1.Third == ICK_Identity) 3747 return Result == ImplicitConversionSequence::Worse 3748 ? ImplicitConversionSequence::Indistinguishable 3749 : ImplicitConversionSequence::Better; 3750 3751 if (SCS2.Third == ICK_Identity) 3752 return Result == ImplicitConversionSequence::Better 3753 ? ImplicitConversionSequence::Indistinguishable 3754 : ImplicitConversionSequence::Worse; 3755 3756 return ImplicitConversionSequence::Indistinguishable; 3757 } 3758 3759 /// Determine whether one of the given reference bindings is better 3760 /// than the other based on what kind of bindings they are. 3761 static bool 3762 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3763 const StandardConversionSequence &SCS2) { 3764 // C++0x [over.ics.rank]p3b4: 3765 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3766 // implicit object parameter of a non-static member function declared 3767 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3768 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3769 // lvalue reference to a function lvalue and S2 binds an rvalue 3770 // reference*. 3771 // 3772 // FIXME: Rvalue references. We're going rogue with the above edits, 3773 // because the semantics in the current C++0x working paper (N3225 at the 3774 // time of this writing) break the standard definition of std::forward 3775 // and std::reference_wrapper when dealing with references to functions. 3776 // Proposed wording changes submitted to CWG for consideration. 3777 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3778 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3779 return false; 3780 3781 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3782 SCS2.IsLvalueReference) || 3783 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3784 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3785 } 3786 3787 enum class FixedEnumPromotion { 3788 None, 3789 ToUnderlyingType, 3790 ToPromotedUnderlyingType 3791 }; 3792 3793 /// Returns kind of fixed enum promotion the \a SCS uses. 3794 static FixedEnumPromotion 3795 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3796 3797 if (SCS.Second != ICK_Integral_Promotion) 3798 return FixedEnumPromotion::None; 3799 3800 QualType FromType = SCS.getFromType(); 3801 if (!FromType->isEnumeralType()) 3802 return FixedEnumPromotion::None; 3803 3804 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3805 if (!Enum->isFixed()) 3806 return FixedEnumPromotion::None; 3807 3808 QualType UnderlyingType = Enum->getIntegerType(); 3809 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3810 return FixedEnumPromotion::ToUnderlyingType; 3811 3812 return FixedEnumPromotion::ToPromotedUnderlyingType; 3813 } 3814 3815 /// CompareStandardConversionSequences - Compare two standard 3816 /// conversion sequences to determine whether one is better than the 3817 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3818 static ImplicitConversionSequence::CompareKind 3819 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3820 const StandardConversionSequence& SCS1, 3821 const StandardConversionSequence& SCS2) 3822 { 3823 // Standard conversion sequence S1 is a better conversion sequence 3824 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3825 3826 // -- S1 is a proper subsequence of S2 (comparing the conversion 3827 // sequences in the canonical form defined by 13.3.3.1.1, 3828 // excluding any Lvalue Transformation; the identity conversion 3829 // sequence is considered to be a subsequence of any 3830 // non-identity conversion sequence) or, if not that, 3831 if (ImplicitConversionSequence::CompareKind CK 3832 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3833 return CK; 3834 3835 // -- the rank of S1 is better than the rank of S2 (by the rules 3836 // defined below), or, if not that, 3837 ImplicitConversionRank Rank1 = SCS1.getRank(); 3838 ImplicitConversionRank Rank2 = SCS2.getRank(); 3839 if (Rank1 < Rank2) 3840 return ImplicitConversionSequence::Better; 3841 else if (Rank2 < Rank1) 3842 return ImplicitConversionSequence::Worse; 3843 3844 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3845 // are indistinguishable unless one of the following rules 3846 // applies: 3847 3848 // A conversion that is not a conversion of a pointer, or 3849 // pointer to member, to bool is better than another conversion 3850 // that is such a conversion. 3851 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3852 return SCS2.isPointerConversionToBool() 3853 ? ImplicitConversionSequence::Better 3854 : ImplicitConversionSequence::Worse; 3855 3856 // C++14 [over.ics.rank]p4b2: 3857 // This is retroactively applied to C++11 by CWG 1601. 3858 // 3859 // A conversion that promotes an enumeration whose underlying type is fixed 3860 // to its underlying type is better than one that promotes to the promoted 3861 // underlying type, if the two are different. 3862 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3863 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3864 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3865 FEP1 != FEP2) 3866 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3867 ? ImplicitConversionSequence::Better 3868 : ImplicitConversionSequence::Worse; 3869 3870 // C++ [over.ics.rank]p4b2: 3871 // 3872 // If class B is derived directly or indirectly from class A, 3873 // conversion of B* to A* is better than conversion of B* to 3874 // void*, and conversion of A* to void* is better than conversion 3875 // of B* to void*. 3876 bool SCS1ConvertsToVoid 3877 = SCS1.isPointerConversionToVoidPointer(S.Context); 3878 bool SCS2ConvertsToVoid 3879 = SCS2.isPointerConversionToVoidPointer(S.Context); 3880 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3881 // Exactly one of the conversion sequences is a conversion to 3882 // a void pointer; it's the worse conversion. 3883 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3884 : ImplicitConversionSequence::Worse; 3885 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3886 // Neither conversion sequence converts to a void pointer; compare 3887 // their derived-to-base conversions. 3888 if (ImplicitConversionSequence::CompareKind DerivedCK 3889 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3890 return DerivedCK; 3891 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3892 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3893 // Both conversion sequences are conversions to void 3894 // pointers. Compare the source types to determine if there's an 3895 // inheritance relationship in their sources. 3896 QualType FromType1 = SCS1.getFromType(); 3897 QualType FromType2 = SCS2.getFromType(); 3898 3899 // Adjust the types we're converting from via the array-to-pointer 3900 // conversion, if we need to. 3901 if (SCS1.First == ICK_Array_To_Pointer) 3902 FromType1 = S.Context.getArrayDecayedType(FromType1); 3903 if (SCS2.First == ICK_Array_To_Pointer) 3904 FromType2 = S.Context.getArrayDecayedType(FromType2); 3905 3906 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3907 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3908 3909 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3910 return ImplicitConversionSequence::Better; 3911 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3912 return ImplicitConversionSequence::Worse; 3913 3914 // Objective-C++: If one interface is more specific than the 3915 // other, it is the better one. 3916 const ObjCObjectPointerType* FromObjCPtr1 3917 = FromType1->getAs<ObjCObjectPointerType>(); 3918 const ObjCObjectPointerType* FromObjCPtr2 3919 = FromType2->getAs<ObjCObjectPointerType>(); 3920 if (FromObjCPtr1 && FromObjCPtr2) { 3921 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3922 FromObjCPtr2); 3923 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3924 FromObjCPtr1); 3925 if (AssignLeft != AssignRight) { 3926 return AssignLeft? ImplicitConversionSequence::Better 3927 : ImplicitConversionSequence::Worse; 3928 } 3929 } 3930 } 3931 3932 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3933 // bullet 3). 3934 if (ImplicitConversionSequence::CompareKind QualCK 3935 = CompareQualificationConversions(S, SCS1, SCS2)) 3936 return QualCK; 3937 3938 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3939 // Check for a better reference binding based on the kind of bindings. 3940 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3941 return ImplicitConversionSequence::Better; 3942 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3943 return ImplicitConversionSequence::Worse; 3944 3945 // C++ [over.ics.rank]p3b4: 3946 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3947 // which the references refer are the same type except for 3948 // top-level cv-qualifiers, and the type to which the reference 3949 // initialized by S2 refers is more cv-qualified than the type 3950 // to which the reference initialized by S1 refers. 3951 QualType T1 = SCS1.getToType(2); 3952 QualType T2 = SCS2.getToType(2); 3953 T1 = S.Context.getCanonicalType(T1); 3954 T2 = S.Context.getCanonicalType(T2); 3955 Qualifiers T1Quals, T2Quals; 3956 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3957 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3958 if (UnqualT1 == UnqualT2) { 3959 // Objective-C++ ARC: If the references refer to objects with different 3960 // lifetimes, prefer bindings that don't change lifetime. 3961 if (SCS1.ObjCLifetimeConversionBinding != 3962 SCS2.ObjCLifetimeConversionBinding) { 3963 return SCS1.ObjCLifetimeConversionBinding 3964 ? ImplicitConversionSequence::Worse 3965 : ImplicitConversionSequence::Better; 3966 } 3967 3968 // If the type is an array type, promote the element qualifiers to the 3969 // type for comparison. 3970 if (isa<ArrayType>(T1) && T1Quals) 3971 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3972 if (isa<ArrayType>(T2) && T2Quals) 3973 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3974 if (T2.isMoreQualifiedThan(T1)) 3975 return ImplicitConversionSequence::Better; 3976 else if (T1.isMoreQualifiedThan(T2)) 3977 return ImplicitConversionSequence::Worse; 3978 } 3979 } 3980 3981 // In Microsoft mode, prefer an integral conversion to a 3982 // floating-to-integral conversion if the integral conversion 3983 // is between types of the same size. 3984 // For example: 3985 // void f(float); 3986 // void f(int); 3987 // int main { 3988 // long a; 3989 // f(a); 3990 // } 3991 // Here, MSVC will call f(int) instead of generating a compile error 3992 // as clang will do in standard mode. 3993 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3994 SCS2.Second == ICK_Floating_Integral && 3995 S.Context.getTypeSize(SCS1.getFromType()) == 3996 S.Context.getTypeSize(SCS1.getToType(2))) 3997 return ImplicitConversionSequence::Better; 3998 3999 // Prefer a compatible vector conversion over a lax vector conversion 4000 // For example: 4001 // 4002 // typedef float __v4sf __attribute__((__vector_size__(16))); 4003 // void f(vector float); 4004 // void f(vector signed int); 4005 // int main() { 4006 // __v4sf a; 4007 // f(a); 4008 // } 4009 // Here, we'd like to choose f(vector float) and not 4010 // report an ambiguous call error 4011 if (SCS1.Second == ICK_Vector_Conversion && 4012 SCS2.Second == ICK_Vector_Conversion) { 4013 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4014 SCS1.getFromType(), SCS1.getToType(2)); 4015 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4016 SCS2.getFromType(), SCS2.getToType(2)); 4017 4018 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4019 return SCS1IsCompatibleVectorConversion 4020 ? ImplicitConversionSequence::Better 4021 : ImplicitConversionSequence::Worse; 4022 } 4023 4024 return ImplicitConversionSequence::Indistinguishable; 4025 } 4026 4027 /// CompareQualificationConversions - Compares two standard conversion 4028 /// sequences to determine whether they can be ranked based on their 4029 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4030 static ImplicitConversionSequence::CompareKind 4031 CompareQualificationConversions(Sema &S, 4032 const StandardConversionSequence& SCS1, 4033 const StandardConversionSequence& SCS2) { 4034 // C++ 13.3.3.2p3: 4035 // -- S1 and S2 differ only in their qualification conversion and 4036 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4037 // cv-qualification signature of type T1 is a proper subset of 4038 // the cv-qualification signature of type T2, and S1 is not the 4039 // deprecated string literal array-to-pointer conversion (4.2). 4040 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4041 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4042 return ImplicitConversionSequence::Indistinguishable; 4043 4044 // FIXME: the example in the standard doesn't use a qualification 4045 // conversion (!) 4046 QualType T1 = SCS1.getToType(2); 4047 QualType T2 = SCS2.getToType(2); 4048 T1 = S.Context.getCanonicalType(T1); 4049 T2 = S.Context.getCanonicalType(T2); 4050 Qualifiers T1Quals, T2Quals; 4051 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4052 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4053 4054 // If the types are the same, we won't learn anything by unwrapped 4055 // them. 4056 if (UnqualT1 == UnqualT2) 4057 return ImplicitConversionSequence::Indistinguishable; 4058 4059 // If the type is an array type, promote the element qualifiers to the type 4060 // for comparison. 4061 if (isa<ArrayType>(T1) && T1Quals) 4062 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4063 if (isa<ArrayType>(T2) && T2Quals) 4064 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4065 4066 ImplicitConversionSequence::CompareKind Result 4067 = ImplicitConversionSequence::Indistinguishable; 4068 4069 // Objective-C++ ARC: 4070 // Prefer qualification conversions not involving a change in lifetime 4071 // to qualification conversions that do not change lifetime. 4072 if (SCS1.QualificationIncludesObjCLifetime != 4073 SCS2.QualificationIncludesObjCLifetime) { 4074 Result = SCS1.QualificationIncludesObjCLifetime 4075 ? ImplicitConversionSequence::Worse 4076 : ImplicitConversionSequence::Better; 4077 } 4078 4079 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4080 // Within each iteration of the loop, we check the qualifiers to 4081 // determine if this still looks like a qualification 4082 // conversion. Then, if all is well, we unwrap one more level of 4083 // pointers or pointers-to-members and do it all again 4084 // until there are no more pointers or pointers-to-members left 4085 // to unwrap. This essentially mimics what 4086 // IsQualificationConversion does, but here we're checking for a 4087 // strict subset of qualifiers. 4088 if (T1.getQualifiers().withoutObjCLifetime() == 4089 T2.getQualifiers().withoutObjCLifetime()) 4090 // The qualifiers are the same, so this doesn't tell us anything 4091 // about how the sequences rank. 4092 // ObjC ownership quals are omitted above as they interfere with 4093 // the ARC overload rule. 4094 ; 4095 else if (T2.isMoreQualifiedThan(T1)) { 4096 // T1 has fewer qualifiers, so it could be the better sequence. 4097 if (Result == ImplicitConversionSequence::Worse) 4098 // Neither has qualifiers that are a subset of the other's 4099 // qualifiers. 4100 return ImplicitConversionSequence::Indistinguishable; 4101 4102 Result = ImplicitConversionSequence::Better; 4103 } else if (T1.isMoreQualifiedThan(T2)) { 4104 // T2 has fewer qualifiers, so it could be the better sequence. 4105 if (Result == ImplicitConversionSequence::Better) 4106 // Neither has qualifiers that are a subset of the other's 4107 // qualifiers. 4108 return ImplicitConversionSequence::Indistinguishable; 4109 4110 Result = ImplicitConversionSequence::Worse; 4111 } else { 4112 // Qualifiers are disjoint. 4113 return ImplicitConversionSequence::Indistinguishable; 4114 } 4115 4116 // If the types after this point are equivalent, we're done. 4117 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4118 break; 4119 } 4120 4121 // Check that the winning standard conversion sequence isn't using 4122 // the deprecated string literal array to pointer conversion. 4123 switch (Result) { 4124 case ImplicitConversionSequence::Better: 4125 if (SCS1.DeprecatedStringLiteralToCharPtr) 4126 Result = ImplicitConversionSequence::Indistinguishable; 4127 break; 4128 4129 case ImplicitConversionSequence::Indistinguishable: 4130 break; 4131 4132 case ImplicitConversionSequence::Worse: 4133 if (SCS2.DeprecatedStringLiteralToCharPtr) 4134 Result = ImplicitConversionSequence::Indistinguishable; 4135 break; 4136 } 4137 4138 return Result; 4139 } 4140 4141 /// CompareDerivedToBaseConversions - Compares two standard conversion 4142 /// sequences to determine whether they can be ranked based on their 4143 /// various kinds of derived-to-base conversions (C++ 4144 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4145 /// conversions between Objective-C interface types. 4146 static ImplicitConversionSequence::CompareKind 4147 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4148 const StandardConversionSequence& SCS1, 4149 const StandardConversionSequence& SCS2) { 4150 QualType FromType1 = SCS1.getFromType(); 4151 QualType ToType1 = SCS1.getToType(1); 4152 QualType FromType2 = SCS2.getFromType(); 4153 QualType ToType2 = SCS2.getToType(1); 4154 4155 // Adjust the types we're converting from via the array-to-pointer 4156 // conversion, if we need to. 4157 if (SCS1.First == ICK_Array_To_Pointer) 4158 FromType1 = S.Context.getArrayDecayedType(FromType1); 4159 if (SCS2.First == ICK_Array_To_Pointer) 4160 FromType2 = S.Context.getArrayDecayedType(FromType2); 4161 4162 // Canonicalize all of the types. 4163 FromType1 = S.Context.getCanonicalType(FromType1); 4164 ToType1 = S.Context.getCanonicalType(ToType1); 4165 FromType2 = S.Context.getCanonicalType(FromType2); 4166 ToType2 = S.Context.getCanonicalType(ToType2); 4167 4168 // C++ [over.ics.rank]p4b3: 4169 // 4170 // If class B is derived directly or indirectly from class A and 4171 // class C is derived directly or indirectly from B, 4172 // 4173 // Compare based on pointer conversions. 4174 if (SCS1.Second == ICK_Pointer_Conversion && 4175 SCS2.Second == ICK_Pointer_Conversion && 4176 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4177 FromType1->isPointerType() && FromType2->isPointerType() && 4178 ToType1->isPointerType() && ToType2->isPointerType()) { 4179 QualType FromPointee1 = 4180 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4181 QualType ToPointee1 = 4182 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4183 QualType FromPointee2 = 4184 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4185 QualType ToPointee2 = 4186 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4187 4188 // -- conversion of C* to B* is better than conversion of C* to A*, 4189 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4190 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4191 return ImplicitConversionSequence::Better; 4192 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4193 return ImplicitConversionSequence::Worse; 4194 } 4195 4196 // -- conversion of B* to A* is better than conversion of C* to A*, 4197 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4198 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4199 return ImplicitConversionSequence::Better; 4200 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4201 return ImplicitConversionSequence::Worse; 4202 } 4203 } else if (SCS1.Second == ICK_Pointer_Conversion && 4204 SCS2.Second == ICK_Pointer_Conversion) { 4205 const ObjCObjectPointerType *FromPtr1 4206 = FromType1->getAs<ObjCObjectPointerType>(); 4207 const ObjCObjectPointerType *FromPtr2 4208 = FromType2->getAs<ObjCObjectPointerType>(); 4209 const ObjCObjectPointerType *ToPtr1 4210 = ToType1->getAs<ObjCObjectPointerType>(); 4211 const ObjCObjectPointerType *ToPtr2 4212 = ToType2->getAs<ObjCObjectPointerType>(); 4213 4214 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4215 // Apply the same conversion ranking rules for Objective-C pointer types 4216 // that we do for C++ pointers to class types. However, we employ the 4217 // Objective-C pseudo-subtyping relationship used for assignment of 4218 // Objective-C pointer types. 4219 bool FromAssignLeft 4220 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4221 bool FromAssignRight 4222 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4223 bool ToAssignLeft 4224 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4225 bool ToAssignRight 4226 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4227 4228 // A conversion to an a non-id object pointer type or qualified 'id' 4229 // type is better than a conversion to 'id'. 4230 if (ToPtr1->isObjCIdType() && 4231 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4232 return ImplicitConversionSequence::Worse; 4233 if (ToPtr2->isObjCIdType() && 4234 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4235 return ImplicitConversionSequence::Better; 4236 4237 // A conversion to a non-id object pointer type is better than a 4238 // conversion to a qualified 'id' type 4239 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4240 return ImplicitConversionSequence::Worse; 4241 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4242 return ImplicitConversionSequence::Better; 4243 4244 // A conversion to an a non-Class object pointer type or qualified 'Class' 4245 // type is better than a conversion to 'Class'. 4246 if (ToPtr1->isObjCClassType() && 4247 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4248 return ImplicitConversionSequence::Worse; 4249 if (ToPtr2->isObjCClassType() && 4250 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4251 return ImplicitConversionSequence::Better; 4252 4253 // A conversion to a non-Class object pointer type is better than a 4254 // conversion to a qualified 'Class' type. 4255 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4256 return ImplicitConversionSequence::Worse; 4257 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4258 return ImplicitConversionSequence::Better; 4259 4260 // -- "conversion of C* to B* is better than conversion of C* to A*," 4261 if (S.Context.hasSameType(FromType1, FromType2) && 4262 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4263 (ToAssignLeft != ToAssignRight)) { 4264 if (FromPtr1->isSpecialized()) { 4265 // "conversion of B<A> * to B * is better than conversion of B * to 4266 // C *. 4267 bool IsFirstSame = 4268 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4269 bool IsSecondSame = 4270 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4271 if (IsFirstSame) { 4272 if (!IsSecondSame) 4273 return ImplicitConversionSequence::Better; 4274 } else if (IsSecondSame) 4275 return ImplicitConversionSequence::Worse; 4276 } 4277 return ToAssignLeft? ImplicitConversionSequence::Worse 4278 : ImplicitConversionSequence::Better; 4279 } 4280 4281 // -- "conversion of B* to A* is better than conversion of C* to A*," 4282 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4283 (FromAssignLeft != FromAssignRight)) 4284 return FromAssignLeft? ImplicitConversionSequence::Better 4285 : ImplicitConversionSequence::Worse; 4286 } 4287 } 4288 4289 // Ranking of member-pointer types. 4290 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4291 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4292 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4293 const MemberPointerType * FromMemPointer1 = 4294 FromType1->getAs<MemberPointerType>(); 4295 const MemberPointerType * ToMemPointer1 = 4296 ToType1->getAs<MemberPointerType>(); 4297 const MemberPointerType * FromMemPointer2 = 4298 FromType2->getAs<MemberPointerType>(); 4299 const MemberPointerType * ToMemPointer2 = 4300 ToType2->getAs<MemberPointerType>(); 4301 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4302 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4303 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4304 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4305 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4306 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4307 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4308 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4309 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4310 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4311 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4312 return ImplicitConversionSequence::Worse; 4313 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4314 return ImplicitConversionSequence::Better; 4315 } 4316 // conversion of B::* to C::* is better than conversion of A::* to C::* 4317 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4318 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4319 return ImplicitConversionSequence::Better; 4320 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4321 return ImplicitConversionSequence::Worse; 4322 } 4323 } 4324 4325 if (SCS1.Second == ICK_Derived_To_Base) { 4326 // -- conversion of C to B is better than conversion of C to A, 4327 // -- binding of an expression of type C to a reference of type 4328 // B& is better than binding an expression of type C to a 4329 // reference of type A&, 4330 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4331 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4332 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4333 return ImplicitConversionSequence::Better; 4334 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4335 return ImplicitConversionSequence::Worse; 4336 } 4337 4338 // -- conversion of B to A is better than conversion of C to A. 4339 // -- binding of an expression of type B to a reference of type 4340 // A& is better than binding an expression of type C to a 4341 // reference of type A&, 4342 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4343 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4344 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4345 return ImplicitConversionSequence::Better; 4346 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4347 return ImplicitConversionSequence::Worse; 4348 } 4349 } 4350 4351 return ImplicitConversionSequence::Indistinguishable; 4352 } 4353 4354 /// Determine whether the given type is valid, e.g., it is not an invalid 4355 /// C++ class. 4356 static bool isTypeValid(QualType T) { 4357 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4358 return !Record->isInvalidDecl(); 4359 4360 return true; 4361 } 4362 4363 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4364 /// determine whether they are reference-related, 4365 /// reference-compatible, reference-compatible with added 4366 /// qualification, or incompatible, for use in C++ initialization by 4367 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4368 /// type, and the first type (T1) is the pointee type of the reference 4369 /// type being initialized. 4370 Sema::ReferenceCompareResult 4371 Sema::CompareReferenceRelationship(SourceLocation Loc, 4372 QualType OrigT1, QualType OrigT2, 4373 bool &DerivedToBase, 4374 bool &ObjCConversion, 4375 bool &ObjCLifetimeConversion, 4376 bool &FunctionConversion) { 4377 assert(!OrigT1->isReferenceType() && 4378 "T1 must be the pointee type of the reference type"); 4379 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4380 4381 QualType T1 = Context.getCanonicalType(OrigT1); 4382 QualType T2 = Context.getCanonicalType(OrigT2); 4383 Qualifiers T1Quals, T2Quals; 4384 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4385 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4386 4387 // C++ [dcl.init.ref]p4: 4388 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4389 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4390 // T1 is a base class of T2. 4391 DerivedToBase = false; 4392 ObjCConversion = false; 4393 ObjCLifetimeConversion = false; 4394 QualType ConvertedT2; 4395 if (UnqualT1 == UnqualT2) { 4396 // Nothing to do. 4397 } else if (isCompleteType(Loc, OrigT2) && 4398 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4399 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4400 DerivedToBase = true; 4401 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4402 UnqualT2->isObjCObjectOrInterfaceType() && 4403 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4404 ObjCConversion = true; 4405 else if (UnqualT2->isFunctionType() && 4406 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4407 // C++1z [dcl.init.ref]p4: 4408 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4409 // function" and T1 is "function" 4410 // 4411 // We extend this to also apply to 'noreturn', so allow any function 4412 // conversion between function types. 4413 FunctionConversion = true; 4414 return Ref_Compatible; 4415 } else 4416 return Ref_Incompatible; 4417 4418 // At this point, we know that T1 and T2 are reference-related (at 4419 // least). 4420 4421 // If the type is an array type, promote the element qualifiers to the type 4422 // for comparison. 4423 if (isa<ArrayType>(T1) && T1Quals) 4424 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4425 if (isa<ArrayType>(T2) && T2Quals) 4426 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4427 4428 // C++ [dcl.init.ref]p4: 4429 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4430 // reference-related to T2 and cv1 is the same cv-qualification 4431 // as, or greater cv-qualification than, cv2. For purposes of 4432 // overload resolution, cases for which cv1 is greater 4433 // cv-qualification than cv2 are identified as 4434 // reference-compatible with added qualification (see 13.3.3.2). 4435 // 4436 // Note that we also require equivalence of Objective-C GC and address-space 4437 // qualifiers when performing these computations, so that e.g., an int in 4438 // address space 1 is not reference-compatible with an int in address 4439 // space 2. 4440 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4441 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4442 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4443 ObjCLifetimeConversion = true; 4444 4445 T1Quals.removeObjCLifetime(); 4446 T2Quals.removeObjCLifetime(); 4447 } 4448 4449 // MS compiler ignores __unaligned qualifier for references; do the same. 4450 T1Quals.removeUnaligned(); 4451 T2Quals.removeUnaligned(); 4452 4453 if (T1Quals.compatiblyIncludes(T2Quals)) 4454 return Ref_Compatible; 4455 else 4456 return Ref_Related; 4457 } 4458 4459 /// Look for a user-defined conversion to a value reference-compatible 4460 /// with DeclType. Return true if something definite is found. 4461 static bool 4462 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4463 QualType DeclType, SourceLocation DeclLoc, 4464 Expr *Init, QualType T2, bool AllowRvalues, 4465 bool AllowExplicit) { 4466 assert(T2->isRecordType() && "Can only find conversions of record types."); 4467 CXXRecordDecl *T2RecordDecl 4468 = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4469 4470 OverloadCandidateSet CandidateSet( 4471 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4472 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4473 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4474 NamedDecl *D = *I; 4475 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4476 if (isa<UsingShadowDecl>(D)) 4477 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4478 4479 FunctionTemplateDecl *ConvTemplate 4480 = dyn_cast<FunctionTemplateDecl>(D); 4481 CXXConversionDecl *Conv; 4482 if (ConvTemplate) 4483 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4484 else 4485 Conv = cast<CXXConversionDecl>(D); 4486 4487 // If this is an explicit conversion, and we're not allowed to consider 4488 // explicit conversions, skip it. 4489 if (!AllowExplicit && Conv->isExplicit()) 4490 continue; 4491 4492 if (AllowRvalues) { 4493 bool DerivedToBase = false; 4494 bool ObjCConversion = false; 4495 bool ObjCLifetimeConversion = false; 4496 bool FunctionConversion = false; 4497 4498 // If we are initializing an rvalue reference, don't permit conversion 4499 // functions that return lvalues. 4500 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4501 const ReferenceType *RefType 4502 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4503 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4504 continue; 4505 } 4506 4507 if (!ConvTemplate && 4508 S.CompareReferenceRelationship( 4509 DeclLoc, 4510 Conv->getConversionType() 4511 .getNonReferenceType() 4512 .getUnqualifiedType(), 4513 DeclType.getNonReferenceType().getUnqualifiedType(), 4514 DerivedToBase, ObjCConversion, ObjCLifetimeConversion, 4515 FunctionConversion) == Sema::Ref_Incompatible) 4516 continue; 4517 } else { 4518 // If the conversion function doesn't return a reference type, 4519 // it can't be considered for this conversion. An rvalue reference 4520 // is only acceptable if its referencee is a function type. 4521 4522 const ReferenceType *RefType = 4523 Conv->getConversionType()->getAs<ReferenceType>(); 4524 if (!RefType || 4525 (!RefType->isLValueReferenceType() && 4526 !RefType->getPointeeType()->isFunctionType())) 4527 continue; 4528 } 4529 4530 if (ConvTemplate) 4531 S.AddTemplateConversionCandidate( 4532 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4533 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4534 else 4535 S.AddConversionCandidate( 4536 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4537 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4538 } 4539 4540 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4541 4542 OverloadCandidateSet::iterator Best; 4543 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4544 case OR_Success: 4545 // C++ [over.ics.ref]p1: 4546 // 4547 // [...] If the parameter binds directly to the result of 4548 // applying a conversion function to the argument 4549 // expression, the implicit conversion sequence is a 4550 // user-defined conversion sequence (13.3.3.1.2), with the 4551 // second standard conversion sequence either an identity 4552 // conversion or, if the conversion function returns an 4553 // entity of a type that is a derived class of the parameter 4554 // type, a derived-to-base Conversion. 4555 if (!Best->FinalConversion.DirectBinding) 4556 return false; 4557 4558 ICS.setUserDefined(); 4559 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4560 ICS.UserDefined.After = Best->FinalConversion; 4561 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4562 ICS.UserDefined.ConversionFunction = Best->Function; 4563 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4564 ICS.UserDefined.EllipsisConversion = false; 4565 assert(ICS.UserDefined.After.ReferenceBinding && 4566 ICS.UserDefined.After.DirectBinding && 4567 "Expected a direct reference binding!"); 4568 return true; 4569 4570 case OR_Ambiguous: 4571 ICS.setAmbiguous(); 4572 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4573 Cand != CandidateSet.end(); ++Cand) 4574 if (Cand->Viable) 4575 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4576 return true; 4577 4578 case OR_No_Viable_Function: 4579 case OR_Deleted: 4580 // There was no suitable conversion, or we found a deleted 4581 // conversion; continue with other checks. 4582 return false; 4583 } 4584 4585 llvm_unreachable("Invalid OverloadResult!"); 4586 } 4587 4588 /// Compute an implicit conversion sequence for reference 4589 /// initialization. 4590 static ImplicitConversionSequence 4591 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4592 SourceLocation DeclLoc, 4593 bool SuppressUserConversions, 4594 bool AllowExplicit) { 4595 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4596 4597 // Most paths end in a failed conversion. 4598 ImplicitConversionSequence ICS; 4599 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4600 4601 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4602 QualType T2 = Init->getType(); 4603 4604 // If the initializer is the address of an overloaded function, try 4605 // to resolve the overloaded function. If all goes well, T2 is the 4606 // type of the resulting function. 4607 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4608 DeclAccessPair Found; 4609 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4610 false, Found)) 4611 T2 = Fn->getType(); 4612 } 4613 4614 // Compute some basic properties of the types and the initializer. 4615 bool isRValRef = DeclType->isRValueReferenceType(); 4616 bool DerivedToBase = false; 4617 bool ObjCConversion = false; 4618 bool ObjCLifetimeConversion = false; 4619 bool FunctionConversion = false; 4620 Expr::Classification InitCategory = Init->Classify(S.Context); 4621 Sema::ReferenceCompareResult RefRelationship = S.CompareReferenceRelationship( 4622 DeclLoc, T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion, 4623 FunctionConversion); 4624 4625 // C++0x [dcl.init.ref]p5: 4626 // A reference to type "cv1 T1" is initialized by an expression 4627 // of type "cv2 T2" as follows: 4628 4629 // -- If reference is an lvalue reference and the initializer expression 4630 if (!isRValRef) { 4631 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4632 // reference-compatible with "cv2 T2," or 4633 // 4634 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4635 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4636 // C++ [over.ics.ref]p1: 4637 // When a parameter of reference type binds directly (8.5.3) 4638 // to an argument expression, the implicit conversion sequence 4639 // is the identity conversion, unless the argument expression 4640 // has a type that is a derived class of the parameter type, 4641 // in which case the implicit conversion sequence is a 4642 // derived-to-base Conversion (13.3.3.1). 4643 ICS.setStandard(); 4644 ICS.Standard.First = ICK_Identity; 4645 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4646 : ObjCConversion? ICK_Compatible_Conversion 4647 : ICK_Identity; 4648 ICS.Standard.Third = ICK_Identity; 4649 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4650 ICS.Standard.setToType(0, T2); 4651 ICS.Standard.setToType(1, T1); 4652 ICS.Standard.setToType(2, T1); 4653 ICS.Standard.ReferenceBinding = true; 4654 ICS.Standard.DirectBinding = true; 4655 ICS.Standard.IsLvalueReference = !isRValRef; 4656 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4657 ICS.Standard.BindsToRvalue = false; 4658 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4659 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4660 ICS.Standard.CopyConstructor = nullptr; 4661 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4662 4663 // Nothing more to do: the inaccessibility/ambiguity check for 4664 // derived-to-base conversions is suppressed when we're 4665 // computing the implicit conversion sequence (C++ 4666 // [over.best.ics]p2). 4667 return ICS; 4668 } 4669 4670 // -- has a class type (i.e., T2 is a class type), where T1 is 4671 // not reference-related to T2, and can be implicitly 4672 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4673 // is reference-compatible with "cv3 T3" 92) (this 4674 // conversion is selected by enumerating the applicable 4675 // conversion functions (13.3.1.6) and choosing the best 4676 // one through overload resolution (13.3)), 4677 if (!SuppressUserConversions && T2->isRecordType() && 4678 S.isCompleteType(DeclLoc, T2) && 4679 RefRelationship == Sema::Ref_Incompatible) { 4680 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4681 Init, T2, /*AllowRvalues=*/false, 4682 AllowExplicit)) 4683 return ICS; 4684 } 4685 } 4686 4687 // -- Otherwise, the reference shall be an lvalue reference to a 4688 // non-volatile const type (i.e., cv1 shall be const), or the reference 4689 // shall be an rvalue reference. 4690 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4691 return ICS; 4692 4693 // -- If the initializer expression 4694 // 4695 // -- is an xvalue, class prvalue, array prvalue or function 4696 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4697 if (RefRelationship == Sema::Ref_Compatible && 4698 (InitCategory.isXValue() || 4699 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4700 (InitCategory.isLValue() && T2->isFunctionType()))) { 4701 ICS.setStandard(); 4702 ICS.Standard.First = ICK_Identity; 4703 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4704 : ObjCConversion? ICK_Compatible_Conversion 4705 : ICK_Identity; 4706 ICS.Standard.Third = ICK_Identity; 4707 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4708 ICS.Standard.setToType(0, T2); 4709 ICS.Standard.setToType(1, T1); 4710 ICS.Standard.setToType(2, T1); 4711 ICS.Standard.ReferenceBinding = true; 4712 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4713 // binding unless we're binding to a class prvalue. 4714 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4715 // allow the use of rvalue references in C++98/03 for the benefit of 4716 // standard library implementors; therefore, we need the xvalue check here. 4717 ICS.Standard.DirectBinding = 4718 S.getLangOpts().CPlusPlus11 || 4719 !(InitCategory.isPRValue() || T2->isRecordType()); 4720 ICS.Standard.IsLvalueReference = !isRValRef; 4721 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4722 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4723 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4724 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4725 ICS.Standard.CopyConstructor = nullptr; 4726 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4727 return ICS; 4728 } 4729 4730 // -- has a class type (i.e., T2 is a class type), where T1 is not 4731 // reference-related to T2, and can be implicitly converted to 4732 // an xvalue, class prvalue, or function lvalue of type 4733 // "cv3 T3", where "cv1 T1" is reference-compatible with 4734 // "cv3 T3", 4735 // 4736 // then the reference is bound to the value of the initializer 4737 // expression in the first case and to the result of the conversion 4738 // in the second case (or, in either case, to an appropriate base 4739 // class subobject). 4740 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4741 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4742 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4743 Init, T2, /*AllowRvalues=*/true, 4744 AllowExplicit)) { 4745 // In the second case, if the reference is an rvalue reference 4746 // and the second standard conversion sequence of the 4747 // user-defined conversion sequence includes an lvalue-to-rvalue 4748 // conversion, the program is ill-formed. 4749 if (ICS.isUserDefined() && isRValRef && 4750 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4751 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4752 4753 return ICS; 4754 } 4755 4756 // A temporary of function type cannot be created; don't even try. 4757 if (T1->isFunctionType()) 4758 return ICS; 4759 4760 // -- Otherwise, a temporary of type "cv1 T1" is created and 4761 // initialized from the initializer expression using the 4762 // rules for a non-reference copy initialization (8.5). The 4763 // reference is then bound to the temporary. If T1 is 4764 // reference-related to T2, cv1 must be the same 4765 // cv-qualification as, or greater cv-qualification than, 4766 // cv2; otherwise, the program is ill-formed. 4767 if (RefRelationship == Sema::Ref_Related) { 4768 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4769 // we would be reference-compatible or reference-compatible with 4770 // added qualification. But that wasn't the case, so the reference 4771 // initialization fails. 4772 // 4773 // Note that we only want to check address spaces and cvr-qualifiers here. 4774 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4775 Qualifiers T1Quals = T1.getQualifiers(); 4776 Qualifiers T2Quals = T2.getQualifiers(); 4777 T1Quals.removeObjCGCAttr(); 4778 T1Quals.removeObjCLifetime(); 4779 T2Quals.removeObjCGCAttr(); 4780 T2Quals.removeObjCLifetime(); 4781 // MS compiler ignores __unaligned qualifier for references; do the same. 4782 T1Quals.removeUnaligned(); 4783 T2Quals.removeUnaligned(); 4784 if (!T1Quals.compatiblyIncludes(T2Quals)) 4785 return ICS; 4786 } 4787 4788 // If at least one of the types is a class type, the types are not 4789 // related, and we aren't allowed any user conversions, the 4790 // reference binding fails. This case is important for breaking 4791 // recursion, since TryImplicitConversion below will attempt to 4792 // create a temporary through the use of a copy constructor. 4793 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4794 (T1->isRecordType() || T2->isRecordType())) 4795 return ICS; 4796 4797 // If T1 is reference-related to T2 and the reference is an rvalue 4798 // reference, the initializer expression shall not be an lvalue. 4799 if (RefRelationship >= Sema::Ref_Related && 4800 isRValRef && Init->Classify(S.Context).isLValue()) 4801 return ICS; 4802 4803 // C++ [over.ics.ref]p2: 4804 // When a parameter of reference type is not bound directly to 4805 // an argument expression, the conversion sequence is the one 4806 // required to convert the argument expression to the 4807 // underlying type of the reference according to 4808 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4809 // to copy-initializing a temporary of the underlying type with 4810 // the argument expression. Any difference in top-level 4811 // cv-qualification is subsumed by the initialization itself 4812 // and does not constitute a conversion. 4813 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4814 /*AllowExplicit=*/false, 4815 /*InOverloadResolution=*/false, 4816 /*CStyle=*/false, 4817 /*AllowObjCWritebackConversion=*/false, 4818 /*AllowObjCConversionOnExplicit=*/false); 4819 4820 // Of course, that's still a reference binding. 4821 if (ICS.isStandard()) { 4822 ICS.Standard.ReferenceBinding = true; 4823 ICS.Standard.IsLvalueReference = !isRValRef; 4824 ICS.Standard.BindsToFunctionLvalue = false; 4825 ICS.Standard.BindsToRvalue = true; 4826 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4827 ICS.Standard.ObjCLifetimeConversionBinding = false; 4828 } else if (ICS.isUserDefined()) { 4829 const ReferenceType *LValRefType = 4830 ICS.UserDefined.ConversionFunction->getReturnType() 4831 ->getAs<LValueReferenceType>(); 4832 4833 // C++ [over.ics.ref]p3: 4834 // Except for an implicit object parameter, for which see 13.3.1, a 4835 // standard conversion sequence cannot be formed if it requires [...] 4836 // binding an rvalue reference to an lvalue other than a function 4837 // lvalue. 4838 // Note that the function case is not possible here. 4839 if (DeclType->isRValueReferenceType() && LValRefType) { 4840 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4841 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4842 // reference to an rvalue! 4843 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4844 return ICS; 4845 } 4846 4847 ICS.UserDefined.After.ReferenceBinding = true; 4848 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4849 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4850 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4851 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4852 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4853 } 4854 4855 return ICS; 4856 } 4857 4858 static ImplicitConversionSequence 4859 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4860 bool SuppressUserConversions, 4861 bool InOverloadResolution, 4862 bool AllowObjCWritebackConversion, 4863 bool AllowExplicit = false); 4864 4865 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4866 /// initializer list From. 4867 static ImplicitConversionSequence 4868 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4869 bool SuppressUserConversions, 4870 bool InOverloadResolution, 4871 bool AllowObjCWritebackConversion) { 4872 // C++11 [over.ics.list]p1: 4873 // When an argument is an initializer list, it is not an expression and 4874 // special rules apply for converting it to a parameter type. 4875 4876 ImplicitConversionSequence Result; 4877 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4878 4879 // We need a complete type for what follows. Incomplete types can never be 4880 // initialized from init lists. 4881 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4882 return Result; 4883 4884 // Per DR1467: 4885 // If the parameter type is a class X and the initializer list has a single 4886 // element of type cv U, where U is X or a class derived from X, the 4887 // implicit conversion sequence is the one required to convert the element 4888 // to the parameter type. 4889 // 4890 // Otherwise, if the parameter type is a character array [... ] 4891 // and the initializer list has a single element that is an 4892 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4893 // implicit conversion sequence is the identity conversion. 4894 if (From->getNumInits() == 1) { 4895 if (ToType->isRecordType()) { 4896 QualType InitType = From->getInit(0)->getType(); 4897 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4898 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4899 return TryCopyInitialization(S, From->getInit(0), ToType, 4900 SuppressUserConversions, 4901 InOverloadResolution, 4902 AllowObjCWritebackConversion); 4903 } 4904 // FIXME: Check the other conditions here: array of character type, 4905 // initializer is a string literal. 4906 if (ToType->isArrayType()) { 4907 InitializedEntity Entity = 4908 InitializedEntity::InitializeParameter(S.Context, ToType, 4909 /*Consumed=*/false); 4910 if (S.CanPerformCopyInitialization(Entity, From)) { 4911 Result.setStandard(); 4912 Result.Standard.setAsIdentityConversion(); 4913 Result.Standard.setFromType(ToType); 4914 Result.Standard.setAllToTypes(ToType); 4915 return Result; 4916 } 4917 } 4918 } 4919 4920 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4921 // C++11 [over.ics.list]p2: 4922 // If the parameter type is std::initializer_list<X> or "array of X" and 4923 // all the elements can be implicitly converted to X, the implicit 4924 // conversion sequence is the worst conversion necessary to convert an 4925 // element of the list to X. 4926 // 4927 // C++14 [over.ics.list]p3: 4928 // Otherwise, if the parameter type is "array of N X", if the initializer 4929 // list has exactly N elements or if it has fewer than N elements and X is 4930 // default-constructible, and if all the elements of the initializer list 4931 // can be implicitly converted to X, the implicit conversion sequence is 4932 // the worst conversion necessary to convert an element of the list to X. 4933 // 4934 // FIXME: We're missing a lot of these checks. 4935 bool toStdInitializerList = false; 4936 QualType X; 4937 if (ToType->isArrayType()) 4938 X = S.Context.getAsArrayType(ToType)->getElementType(); 4939 else 4940 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4941 if (!X.isNull()) { 4942 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4943 Expr *Init = From->getInit(i); 4944 ImplicitConversionSequence ICS = 4945 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4946 InOverloadResolution, 4947 AllowObjCWritebackConversion); 4948 // If a single element isn't convertible, fail. 4949 if (ICS.isBad()) { 4950 Result = ICS; 4951 break; 4952 } 4953 // Otherwise, look for the worst conversion. 4954 if (Result.isBad() || CompareImplicitConversionSequences( 4955 S, From->getBeginLoc(), ICS, Result) == 4956 ImplicitConversionSequence::Worse) 4957 Result = ICS; 4958 } 4959 4960 // For an empty list, we won't have computed any conversion sequence. 4961 // Introduce the identity conversion sequence. 4962 if (From->getNumInits() == 0) { 4963 Result.setStandard(); 4964 Result.Standard.setAsIdentityConversion(); 4965 Result.Standard.setFromType(ToType); 4966 Result.Standard.setAllToTypes(ToType); 4967 } 4968 4969 Result.setStdInitializerListElement(toStdInitializerList); 4970 return Result; 4971 } 4972 4973 // C++14 [over.ics.list]p4: 4974 // C++11 [over.ics.list]p3: 4975 // Otherwise, if the parameter is a non-aggregate class X and overload 4976 // resolution chooses a single best constructor [...] the implicit 4977 // conversion sequence is a user-defined conversion sequence. If multiple 4978 // constructors are viable but none is better than the others, the 4979 // implicit conversion sequence is a user-defined conversion sequence. 4980 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4981 // This function can deal with initializer lists. 4982 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4983 /*AllowExplicit=*/false, 4984 InOverloadResolution, /*CStyle=*/false, 4985 AllowObjCWritebackConversion, 4986 /*AllowObjCConversionOnExplicit=*/false); 4987 } 4988 4989 // C++14 [over.ics.list]p5: 4990 // C++11 [over.ics.list]p4: 4991 // Otherwise, if the parameter has an aggregate type which can be 4992 // initialized from the initializer list [...] the implicit conversion 4993 // sequence is a user-defined conversion sequence. 4994 if (ToType->isAggregateType()) { 4995 // Type is an aggregate, argument is an init list. At this point it comes 4996 // down to checking whether the initialization works. 4997 // FIXME: Find out whether this parameter is consumed or not. 4998 InitializedEntity Entity = 4999 InitializedEntity::InitializeParameter(S.Context, ToType, 5000 /*Consumed=*/false); 5001 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5002 From)) { 5003 Result.setUserDefined(); 5004 Result.UserDefined.Before.setAsIdentityConversion(); 5005 // Initializer lists don't have a type. 5006 Result.UserDefined.Before.setFromType(QualType()); 5007 Result.UserDefined.Before.setAllToTypes(QualType()); 5008 5009 Result.UserDefined.After.setAsIdentityConversion(); 5010 Result.UserDefined.After.setFromType(ToType); 5011 Result.UserDefined.After.setAllToTypes(ToType); 5012 Result.UserDefined.ConversionFunction = nullptr; 5013 } 5014 return Result; 5015 } 5016 5017 // C++14 [over.ics.list]p6: 5018 // C++11 [over.ics.list]p5: 5019 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5020 if (ToType->isReferenceType()) { 5021 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5022 // mention initializer lists in any way. So we go by what list- 5023 // initialization would do and try to extrapolate from that. 5024 5025 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5026 5027 // If the initializer list has a single element that is reference-related 5028 // to the parameter type, we initialize the reference from that. 5029 if (From->getNumInits() == 1) { 5030 Expr *Init = From->getInit(0); 5031 5032 QualType T2 = Init->getType(); 5033 5034 // If the initializer is the address of an overloaded function, try 5035 // to resolve the overloaded function. If all goes well, T2 is the 5036 // type of the resulting function. 5037 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5038 DeclAccessPair Found; 5039 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5040 Init, ToType, false, Found)) 5041 T2 = Fn->getType(); 5042 } 5043 5044 // Compute some basic properties of the types and the initializer. 5045 bool dummy1 = false; 5046 bool dummy2 = false; 5047 bool dummy3 = false; 5048 bool dummy4 = false; 5049 Sema::ReferenceCompareResult RefRelationship = 5050 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 5051 dummy2, dummy3, dummy4); 5052 5053 if (RefRelationship >= Sema::Ref_Related) { 5054 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5055 SuppressUserConversions, 5056 /*AllowExplicit=*/false); 5057 } 5058 } 5059 5060 // Otherwise, we bind the reference to a temporary created from the 5061 // initializer list. 5062 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5063 InOverloadResolution, 5064 AllowObjCWritebackConversion); 5065 if (Result.isFailure()) 5066 return Result; 5067 assert(!Result.isEllipsis() && 5068 "Sub-initialization cannot result in ellipsis conversion."); 5069 5070 // Can we even bind to a temporary? 5071 if (ToType->isRValueReferenceType() || 5072 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5073 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5074 Result.UserDefined.After; 5075 SCS.ReferenceBinding = true; 5076 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5077 SCS.BindsToRvalue = true; 5078 SCS.BindsToFunctionLvalue = false; 5079 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5080 SCS.ObjCLifetimeConversionBinding = false; 5081 } else 5082 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5083 From, ToType); 5084 return Result; 5085 } 5086 5087 // C++14 [over.ics.list]p7: 5088 // C++11 [over.ics.list]p6: 5089 // Otherwise, if the parameter type is not a class: 5090 if (!ToType->isRecordType()) { 5091 // - if the initializer list has one element that is not itself an 5092 // initializer list, the implicit conversion sequence is the one 5093 // required to convert the element to the parameter type. 5094 unsigned NumInits = From->getNumInits(); 5095 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5096 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5097 SuppressUserConversions, 5098 InOverloadResolution, 5099 AllowObjCWritebackConversion); 5100 // - if the initializer list has no elements, the implicit conversion 5101 // sequence is the identity conversion. 5102 else if (NumInits == 0) { 5103 Result.setStandard(); 5104 Result.Standard.setAsIdentityConversion(); 5105 Result.Standard.setFromType(ToType); 5106 Result.Standard.setAllToTypes(ToType); 5107 } 5108 return Result; 5109 } 5110 5111 // C++14 [over.ics.list]p8: 5112 // C++11 [over.ics.list]p7: 5113 // In all cases other than those enumerated above, no conversion is possible 5114 return Result; 5115 } 5116 5117 /// TryCopyInitialization - Try to copy-initialize a value of type 5118 /// ToType from the expression From. Return the implicit conversion 5119 /// sequence required to pass this argument, which may be a bad 5120 /// conversion sequence (meaning that the argument cannot be passed to 5121 /// a parameter of this type). If @p SuppressUserConversions, then we 5122 /// do not permit any user-defined conversion sequences. 5123 static ImplicitConversionSequence 5124 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5125 bool SuppressUserConversions, 5126 bool InOverloadResolution, 5127 bool AllowObjCWritebackConversion, 5128 bool AllowExplicit) { 5129 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5130 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5131 InOverloadResolution,AllowObjCWritebackConversion); 5132 5133 if (ToType->isReferenceType()) 5134 return TryReferenceInit(S, From, ToType, 5135 /*FIXME:*/ From->getBeginLoc(), 5136 SuppressUserConversions, AllowExplicit); 5137 5138 return TryImplicitConversion(S, From, ToType, 5139 SuppressUserConversions, 5140 /*AllowExplicit=*/false, 5141 InOverloadResolution, 5142 /*CStyle=*/false, 5143 AllowObjCWritebackConversion, 5144 /*AllowObjCConversionOnExplicit=*/false); 5145 } 5146 5147 static bool TryCopyInitialization(const CanQualType FromQTy, 5148 const CanQualType ToQTy, 5149 Sema &S, 5150 SourceLocation Loc, 5151 ExprValueKind FromVK) { 5152 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5153 ImplicitConversionSequence ICS = 5154 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5155 5156 return !ICS.isBad(); 5157 } 5158 5159 /// TryObjectArgumentInitialization - Try to initialize the object 5160 /// parameter of the given member function (@c Method) from the 5161 /// expression @p From. 5162 static ImplicitConversionSequence 5163 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5164 Expr::Classification FromClassification, 5165 CXXMethodDecl *Method, 5166 CXXRecordDecl *ActingContext) { 5167 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5168 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5169 // const volatile object. 5170 Qualifiers Quals = Method->getMethodQualifiers(); 5171 if (isa<CXXDestructorDecl>(Method)) { 5172 Quals.addConst(); 5173 Quals.addVolatile(); 5174 } 5175 5176 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5177 5178 // Set up the conversion sequence as a "bad" conversion, to allow us 5179 // to exit early. 5180 ImplicitConversionSequence ICS; 5181 5182 // We need to have an object of class type. 5183 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5184 FromType = PT->getPointeeType(); 5185 5186 // When we had a pointer, it's implicitly dereferenced, so we 5187 // better have an lvalue. 5188 assert(FromClassification.isLValue()); 5189 } 5190 5191 assert(FromType->isRecordType()); 5192 5193 // C++0x [over.match.funcs]p4: 5194 // For non-static member functions, the type of the implicit object 5195 // parameter is 5196 // 5197 // - "lvalue reference to cv X" for functions declared without a 5198 // ref-qualifier or with the & ref-qualifier 5199 // - "rvalue reference to cv X" for functions declared with the && 5200 // ref-qualifier 5201 // 5202 // where X is the class of which the function is a member and cv is the 5203 // cv-qualification on the member function declaration. 5204 // 5205 // However, when finding an implicit conversion sequence for the argument, we 5206 // are not allowed to perform user-defined conversions 5207 // (C++ [over.match.funcs]p5). We perform a simplified version of 5208 // reference binding here, that allows class rvalues to bind to 5209 // non-constant references. 5210 5211 // First check the qualifiers. 5212 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5213 if (ImplicitParamType.getCVRQualifiers() 5214 != FromTypeCanon.getLocalCVRQualifiers() && 5215 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5216 ICS.setBad(BadConversionSequence::bad_qualifiers, 5217 FromType, ImplicitParamType); 5218 return ICS; 5219 } 5220 5221 if (FromTypeCanon.getQualifiers().hasAddressSpace()) { 5222 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5223 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5224 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5225 ICS.setBad(BadConversionSequence::bad_qualifiers, 5226 FromType, ImplicitParamType); 5227 return ICS; 5228 } 5229 } 5230 5231 // Check that we have either the same type or a derived type. It 5232 // affects the conversion rank. 5233 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5234 ImplicitConversionKind SecondKind; 5235 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5236 SecondKind = ICK_Identity; 5237 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5238 SecondKind = ICK_Derived_To_Base; 5239 else { 5240 ICS.setBad(BadConversionSequence::unrelated_class, 5241 FromType, ImplicitParamType); 5242 return ICS; 5243 } 5244 5245 // Check the ref-qualifier. 5246 switch (Method->getRefQualifier()) { 5247 case RQ_None: 5248 // Do nothing; we don't care about lvalueness or rvalueness. 5249 break; 5250 5251 case RQ_LValue: 5252 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5253 // non-const lvalue reference cannot bind to an rvalue 5254 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5255 ImplicitParamType); 5256 return ICS; 5257 } 5258 break; 5259 5260 case RQ_RValue: 5261 if (!FromClassification.isRValue()) { 5262 // rvalue reference cannot bind to an lvalue 5263 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5264 ImplicitParamType); 5265 return ICS; 5266 } 5267 break; 5268 } 5269 5270 // Success. Mark this as a reference binding. 5271 ICS.setStandard(); 5272 ICS.Standard.setAsIdentityConversion(); 5273 ICS.Standard.Second = SecondKind; 5274 ICS.Standard.setFromType(FromType); 5275 ICS.Standard.setAllToTypes(ImplicitParamType); 5276 ICS.Standard.ReferenceBinding = true; 5277 ICS.Standard.DirectBinding = true; 5278 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5279 ICS.Standard.BindsToFunctionLvalue = false; 5280 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5281 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5282 = (Method->getRefQualifier() == RQ_None); 5283 return ICS; 5284 } 5285 5286 /// PerformObjectArgumentInitialization - Perform initialization of 5287 /// the implicit object parameter for the given Method with the given 5288 /// expression. 5289 ExprResult 5290 Sema::PerformObjectArgumentInitialization(Expr *From, 5291 NestedNameSpecifier *Qualifier, 5292 NamedDecl *FoundDecl, 5293 CXXMethodDecl *Method) { 5294 QualType FromRecordType, DestType; 5295 QualType ImplicitParamRecordType = 5296 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5297 5298 Expr::Classification FromClassification; 5299 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5300 FromRecordType = PT->getPointeeType(); 5301 DestType = Method->getThisType(); 5302 FromClassification = Expr::Classification::makeSimpleLValue(); 5303 } else { 5304 FromRecordType = From->getType(); 5305 DestType = ImplicitParamRecordType; 5306 FromClassification = From->Classify(Context); 5307 5308 // When performing member access on an rvalue, materialize a temporary. 5309 if (From->isRValue()) { 5310 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5311 Method->getRefQualifier() != 5312 RefQualifierKind::RQ_RValue); 5313 } 5314 } 5315 5316 // Note that we always use the true parent context when performing 5317 // the actual argument initialization. 5318 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5319 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5320 Method->getParent()); 5321 if (ICS.isBad()) { 5322 switch (ICS.Bad.Kind) { 5323 case BadConversionSequence::bad_qualifiers: { 5324 Qualifiers FromQs = FromRecordType.getQualifiers(); 5325 Qualifiers ToQs = DestType.getQualifiers(); 5326 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5327 if (CVR) { 5328 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5329 << Method->getDeclName() << FromRecordType << (CVR - 1) 5330 << From->getSourceRange(); 5331 Diag(Method->getLocation(), diag::note_previous_decl) 5332 << Method->getDeclName(); 5333 return ExprError(); 5334 } 5335 break; 5336 } 5337 5338 case BadConversionSequence::lvalue_ref_to_rvalue: 5339 case BadConversionSequence::rvalue_ref_to_lvalue: { 5340 bool IsRValueQualified = 5341 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5342 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5343 << Method->getDeclName() << FromClassification.isRValue() 5344 << IsRValueQualified; 5345 Diag(Method->getLocation(), diag::note_previous_decl) 5346 << Method->getDeclName(); 5347 return ExprError(); 5348 } 5349 5350 case BadConversionSequence::no_conversion: 5351 case BadConversionSequence::unrelated_class: 5352 break; 5353 } 5354 5355 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5356 << ImplicitParamRecordType << FromRecordType 5357 << From->getSourceRange(); 5358 } 5359 5360 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5361 ExprResult FromRes = 5362 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5363 if (FromRes.isInvalid()) 5364 return ExprError(); 5365 From = FromRes.get(); 5366 } 5367 5368 if (!Context.hasSameType(From->getType(), DestType)) { 5369 CastKind CK; 5370 if (FromRecordType.getAddressSpace() != DestType.getAddressSpace()) 5371 CK = CK_AddressSpaceConversion; 5372 else 5373 CK = CK_NoOp; 5374 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5375 } 5376 return From; 5377 } 5378 5379 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5380 /// expression From to bool (C++0x [conv]p3). 5381 static ImplicitConversionSequence 5382 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5383 return TryImplicitConversion(S, From, S.Context.BoolTy, 5384 /*SuppressUserConversions=*/false, 5385 /*AllowExplicit=*/true, 5386 /*InOverloadResolution=*/false, 5387 /*CStyle=*/false, 5388 /*AllowObjCWritebackConversion=*/false, 5389 /*AllowObjCConversionOnExplicit=*/false); 5390 } 5391 5392 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5393 /// of the expression From to bool (C++0x [conv]p3). 5394 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5395 if (checkPlaceholderForOverload(*this, From)) 5396 return ExprError(); 5397 5398 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5399 if (!ICS.isBad()) 5400 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5401 5402 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5403 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5404 << From->getType() << From->getSourceRange(); 5405 return ExprError(); 5406 } 5407 5408 /// Check that the specified conversion is permitted in a converted constant 5409 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5410 /// is acceptable. 5411 static bool CheckConvertedConstantConversions(Sema &S, 5412 StandardConversionSequence &SCS) { 5413 // Since we know that the target type is an integral or unscoped enumeration 5414 // type, most conversion kinds are impossible. All possible First and Third 5415 // conversions are fine. 5416 switch (SCS.Second) { 5417 case ICK_Identity: 5418 case ICK_Function_Conversion: 5419 case ICK_Integral_Promotion: 5420 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5421 case ICK_Zero_Queue_Conversion: 5422 return true; 5423 5424 case ICK_Boolean_Conversion: 5425 // Conversion from an integral or unscoped enumeration type to bool is 5426 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5427 // conversion, so we allow it in a converted constant expression. 5428 // 5429 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5430 // a lot of popular code. We should at least add a warning for this 5431 // (non-conforming) extension. 5432 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5433 SCS.getToType(2)->isBooleanType(); 5434 5435 case ICK_Pointer_Conversion: 5436 case ICK_Pointer_Member: 5437 // C++1z: null pointer conversions and null member pointer conversions are 5438 // only permitted if the source type is std::nullptr_t. 5439 return SCS.getFromType()->isNullPtrType(); 5440 5441 case ICK_Floating_Promotion: 5442 case ICK_Complex_Promotion: 5443 case ICK_Floating_Conversion: 5444 case ICK_Complex_Conversion: 5445 case ICK_Floating_Integral: 5446 case ICK_Compatible_Conversion: 5447 case ICK_Derived_To_Base: 5448 case ICK_Vector_Conversion: 5449 case ICK_Vector_Splat: 5450 case ICK_Complex_Real: 5451 case ICK_Block_Pointer_Conversion: 5452 case ICK_TransparentUnionConversion: 5453 case ICK_Writeback_Conversion: 5454 case ICK_Zero_Event_Conversion: 5455 case ICK_C_Only_Conversion: 5456 case ICK_Incompatible_Pointer_Conversion: 5457 return false; 5458 5459 case ICK_Lvalue_To_Rvalue: 5460 case ICK_Array_To_Pointer: 5461 case ICK_Function_To_Pointer: 5462 llvm_unreachable("found a first conversion kind in Second"); 5463 5464 case ICK_Qualification: 5465 llvm_unreachable("found a third conversion kind in Second"); 5466 5467 case ICK_Num_Conversion_Kinds: 5468 break; 5469 } 5470 5471 llvm_unreachable("unknown conversion kind"); 5472 } 5473 5474 /// CheckConvertedConstantExpression - Check that the expression From is a 5475 /// converted constant expression of type T, perform the conversion and produce 5476 /// the converted expression, per C++11 [expr.const]p3. 5477 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5478 QualType T, APValue &Value, 5479 Sema::CCEKind CCE, 5480 bool RequireInt) { 5481 assert(S.getLangOpts().CPlusPlus11 && 5482 "converted constant expression outside C++11"); 5483 5484 if (checkPlaceholderForOverload(S, From)) 5485 return ExprError(); 5486 5487 // C++1z [expr.const]p3: 5488 // A converted constant expression of type T is an expression, 5489 // implicitly converted to type T, where the converted 5490 // expression is a constant expression and the implicit conversion 5491 // sequence contains only [... list of conversions ...]. 5492 // C++1z [stmt.if]p2: 5493 // If the if statement is of the form if constexpr, the value of the 5494 // condition shall be a contextually converted constant expression of type 5495 // bool. 5496 ImplicitConversionSequence ICS = 5497 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5498 ? TryContextuallyConvertToBool(S, From) 5499 : TryCopyInitialization(S, From, T, 5500 /*SuppressUserConversions=*/false, 5501 /*InOverloadResolution=*/false, 5502 /*AllowObjCWritebackConversion=*/false, 5503 /*AllowExplicit=*/false); 5504 StandardConversionSequence *SCS = nullptr; 5505 switch (ICS.getKind()) { 5506 case ImplicitConversionSequence::StandardConversion: 5507 SCS = &ICS.Standard; 5508 break; 5509 case ImplicitConversionSequence::UserDefinedConversion: 5510 // We are converting to a non-class type, so the Before sequence 5511 // must be trivial. 5512 SCS = &ICS.UserDefined.After; 5513 break; 5514 case ImplicitConversionSequence::AmbiguousConversion: 5515 case ImplicitConversionSequence::BadConversion: 5516 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5517 return S.Diag(From->getBeginLoc(), 5518 diag::err_typecheck_converted_constant_expression) 5519 << From->getType() << From->getSourceRange() << T; 5520 return ExprError(); 5521 5522 case ImplicitConversionSequence::EllipsisConversion: 5523 llvm_unreachable("ellipsis conversion in converted constant expression"); 5524 } 5525 5526 // Check that we would only use permitted conversions. 5527 if (!CheckConvertedConstantConversions(S, *SCS)) { 5528 return S.Diag(From->getBeginLoc(), 5529 diag::err_typecheck_converted_constant_expression_disallowed) 5530 << From->getType() << From->getSourceRange() << T; 5531 } 5532 // [...] and where the reference binding (if any) binds directly. 5533 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5534 return S.Diag(From->getBeginLoc(), 5535 diag::err_typecheck_converted_constant_expression_indirect) 5536 << From->getType() << From->getSourceRange() << T; 5537 } 5538 5539 ExprResult Result = 5540 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5541 if (Result.isInvalid()) 5542 return Result; 5543 5544 // C++2a [intro.execution]p5: 5545 // A full-expression is [...] a constant-expression [...] 5546 Result = 5547 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5548 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5549 if (Result.isInvalid()) 5550 return Result; 5551 5552 // Check for a narrowing implicit conversion. 5553 APValue PreNarrowingValue; 5554 QualType PreNarrowingType; 5555 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5556 PreNarrowingType)) { 5557 case NK_Dependent_Narrowing: 5558 // Implicit conversion to a narrower type, but the expression is 5559 // value-dependent so we can't tell whether it's actually narrowing. 5560 case NK_Variable_Narrowing: 5561 // Implicit conversion to a narrower type, and the value is not a constant 5562 // expression. We'll diagnose this in a moment. 5563 case NK_Not_Narrowing: 5564 break; 5565 5566 case NK_Constant_Narrowing: 5567 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5568 << CCE << /*Constant*/ 1 5569 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5570 break; 5571 5572 case NK_Type_Narrowing: 5573 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5574 << CCE << /*Constant*/ 0 << From->getType() << T; 5575 break; 5576 } 5577 5578 if (Result.get()->isValueDependent()) { 5579 Value = APValue(); 5580 return Result; 5581 } 5582 5583 // Check the expression is a constant expression. 5584 SmallVector<PartialDiagnosticAt, 8> Notes; 5585 Expr::EvalResult Eval; 5586 Eval.Diag = &Notes; 5587 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5588 ? Expr::EvaluateForMangling 5589 : Expr::EvaluateForCodeGen; 5590 5591 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5592 (RequireInt && !Eval.Val.isInt())) { 5593 // The expression can't be folded, so we can't keep it at this position in 5594 // the AST. 5595 Result = ExprError(); 5596 } else { 5597 Value = Eval.Val; 5598 5599 if (Notes.empty()) { 5600 // It's a constant expression. 5601 return ConstantExpr::Create(S.Context, Result.get(), Value); 5602 } 5603 } 5604 5605 // It's not a constant expression. Produce an appropriate diagnostic. 5606 if (Notes.size() == 1 && 5607 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5608 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5609 else { 5610 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5611 << CCE << From->getSourceRange(); 5612 for (unsigned I = 0; I < Notes.size(); ++I) 5613 S.Diag(Notes[I].first, Notes[I].second); 5614 } 5615 return ExprError(); 5616 } 5617 5618 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5619 APValue &Value, CCEKind CCE) { 5620 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5621 } 5622 5623 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5624 llvm::APSInt &Value, 5625 CCEKind CCE) { 5626 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5627 5628 APValue V; 5629 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5630 if (!R.isInvalid() && !R.get()->isValueDependent()) 5631 Value = V.getInt(); 5632 return R; 5633 } 5634 5635 5636 /// dropPointerConversions - If the given standard conversion sequence 5637 /// involves any pointer conversions, remove them. This may change 5638 /// the result type of the conversion sequence. 5639 static void dropPointerConversion(StandardConversionSequence &SCS) { 5640 if (SCS.Second == ICK_Pointer_Conversion) { 5641 SCS.Second = ICK_Identity; 5642 SCS.Third = ICK_Identity; 5643 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5644 } 5645 } 5646 5647 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5648 /// convert the expression From to an Objective-C pointer type. 5649 static ImplicitConversionSequence 5650 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5651 // Do an implicit conversion to 'id'. 5652 QualType Ty = S.Context.getObjCIdType(); 5653 ImplicitConversionSequence ICS 5654 = TryImplicitConversion(S, From, Ty, 5655 // FIXME: Are these flags correct? 5656 /*SuppressUserConversions=*/false, 5657 /*AllowExplicit=*/true, 5658 /*InOverloadResolution=*/false, 5659 /*CStyle=*/false, 5660 /*AllowObjCWritebackConversion=*/false, 5661 /*AllowObjCConversionOnExplicit=*/true); 5662 5663 // Strip off any final conversions to 'id'. 5664 switch (ICS.getKind()) { 5665 case ImplicitConversionSequence::BadConversion: 5666 case ImplicitConversionSequence::AmbiguousConversion: 5667 case ImplicitConversionSequence::EllipsisConversion: 5668 break; 5669 5670 case ImplicitConversionSequence::UserDefinedConversion: 5671 dropPointerConversion(ICS.UserDefined.After); 5672 break; 5673 5674 case ImplicitConversionSequence::StandardConversion: 5675 dropPointerConversion(ICS.Standard); 5676 break; 5677 } 5678 5679 return ICS; 5680 } 5681 5682 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5683 /// conversion of the expression From to an Objective-C pointer type. 5684 /// Returns a valid but null ExprResult if no conversion sequence exists. 5685 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5686 if (checkPlaceholderForOverload(*this, From)) 5687 return ExprError(); 5688 5689 QualType Ty = Context.getObjCIdType(); 5690 ImplicitConversionSequence ICS = 5691 TryContextuallyConvertToObjCPointer(*this, From); 5692 if (!ICS.isBad()) 5693 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5694 return ExprResult(); 5695 } 5696 5697 /// Determine whether the provided type is an integral type, or an enumeration 5698 /// type of a permitted flavor. 5699 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5700 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5701 : T->isIntegralOrUnscopedEnumerationType(); 5702 } 5703 5704 static ExprResult 5705 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5706 Sema::ContextualImplicitConverter &Converter, 5707 QualType T, UnresolvedSetImpl &ViableConversions) { 5708 5709 if (Converter.Suppress) 5710 return ExprError(); 5711 5712 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5713 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5714 CXXConversionDecl *Conv = 5715 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5716 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5717 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5718 } 5719 return From; 5720 } 5721 5722 static bool 5723 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5724 Sema::ContextualImplicitConverter &Converter, 5725 QualType T, bool HadMultipleCandidates, 5726 UnresolvedSetImpl &ExplicitConversions) { 5727 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5728 DeclAccessPair Found = ExplicitConversions[0]; 5729 CXXConversionDecl *Conversion = 5730 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5731 5732 // The user probably meant to invoke the given explicit 5733 // conversion; use it. 5734 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5735 std::string TypeStr; 5736 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5737 5738 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5739 << FixItHint::CreateInsertion(From->getBeginLoc(), 5740 "static_cast<" + TypeStr + ">(") 5741 << FixItHint::CreateInsertion( 5742 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5743 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5744 5745 // If we aren't in a SFINAE context, build a call to the 5746 // explicit conversion function. 5747 if (SemaRef.isSFINAEContext()) 5748 return true; 5749 5750 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5751 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5752 HadMultipleCandidates); 5753 if (Result.isInvalid()) 5754 return true; 5755 // Record usage of conversion in an implicit cast. 5756 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5757 CK_UserDefinedConversion, Result.get(), 5758 nullptr, Result.get()->getValueKind()); 5759 } 5760 return false; 5761 } 5762 5763 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5764 Sema::ContextualImplicitConverter &Converter, 5765 QualType T, bool HadMultipleCandidates, 5766 DeclAccessPair &Found) { 5767 CXXConversionDecl *Conversion = 5768 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5769 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5770 5771 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5772 if (!Converter.SuppressConversion) { 5773 if (SemaRef.isSFINAEContext()) 5774 return true; 5775 5776 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5777 << From->getSourceRange(); 5778 } 5779 5780 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5781 HadMultipleCandidates); 5782 if (Result.isInvalid()) 5783 return true; 5784 // Record usage of conversion in an implicit cast. 5785 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5786 CK_UserDefinedConversion, Result.get(), 5787 nullptr, Result.get()->getValueKind()); 5788 return false; 5789 } 5790 5791 static ExprResult finishContextualImplicitConversion( 5792 Sema &SemaRef, SourceLocation Loc, Expr *From, 5793 Sema::ContextualImplicitConverter &Converter) { 5794 if (!Converter.match(From->getType()) && !Converter.Suppress) 5795 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5796 << From->getSourceRange(); 5797 5798 return SemaRef.DefaultLvalueConversion(From); 5799 } 5800 5801 static void 5802 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5803 UnresolvedSetImpl &ViableConversions, 5804 OverloadCandidateSet &CandidateSet) { 5805 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5806 DeclAccessPair FoundDecl = ViableConversions[I]; 5807 NamedDecl *D = FoundDecl.getDecl(); 5808 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5809 if (isa<UsingShadowDecl>(D)) 5810 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5811 5812 CXXConversionDecl *Conv; 5813 FunctionTemplateDecl *ConvTemplate; 5814 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5815 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5816 else 5817 Conv = cast<CXXConversionDecl>(D); 5818 5819 if (ConvTemplate) 5820 SemaRef.AddTemplateConversionCandidate( 5821 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5822 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5823 else 5824 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5825 ToType, CandidateSet, 5826 /*AllowObjCConversionOnExplicit=*/false, 5827 /*AllowExplicit*/ true); 5828 } 5829 } 5830 5831 /// Attempt to convert the given expression to a type which is accepted 5832 /// by the given converter. 5833 /// 5834 /// This routine will attempt to convert an expression of class type to a 5835 /// type accepted by the specified converter. In C++11 and before, the class 5836 /// must have a single non-explicit conversion function converting to a matching 5837 /// type. In C++1y, there can be multiple such conversion functions, but only 5838 /// one target type. 5839 /// 5840 /// \param Loc The source location of the construct that requires the 5841 /// conversion. 5842 /// 5843 /// \param From The expression we're converting from. 5844 /// 5845 /// \param Converter Used to control and diagnose the conversion process. 5846 /// 5847 /// \returns The expression, converted to an integral or enumeration type if 5848 /// successful. 5849 ExprResult Sema::PerformContextualImplicitConversion( 5850 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5851 // We can't perform any more checking for type-dependent expressions. 5852 if (From->isTypeDependent()) 5853 return From; 5854 5855 // Process placeholders immediately. 5856 if (From->hasPlaceholderType()) { 5857 ExprResult result = CheckPlaceholderExpr(From); 5858 if (result.isInvalid()) 5859 return result; 5860 From = result.get(); 5861 } 5862 5863 // If the expression already has a matching type, we're golden. 5864 QualType T = From->getType(); 5865 if (Converter.match(T)) 5866 return DefaultLvalueConversion(From); 5867 5868 // FIXME: Check for missing '()' if T is a function type? 5869 5870 // We can only perform contextual implicit conversions on objects of class 5871 // type. 5872 const RecordType *RecordTy = T->getAs<RecordType>(); 5873 if (!RecordTy || !getLangOpts().CPlusPlus) { 5874 if (!Converter.Suppress) 5875 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5876 return From; 5877 } 5878 5879 // We must have a complete class type. 5880 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5881 ContextualImplicitConverter &Converter; 5882 Expr *From; 5883 5884 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5885 : Converter(Converter), From(From) {} 5886 5887 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5888 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5889 } 5890 } IncompleteDiagnoser(Converter, From); 5891 5892 if (Converter.Suppress ? !isCompleteType(Loc, T) 5893 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5894 return From; 5895 5896 // Look for a conversion to an integral or enumeration type. 5897 UnresolvedSet<4> 5898 ViableConversions; // These are *potentially* viable in C++1y. 5899 UnresolvedSet<4> ExplicitConversions; 5900 const auto &Conversions = 5901 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5902 5903 bool HadMultipleCandidates = 5904 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5905 5906 // To check that there is only one target type, in C++1y: 5907 QualType ToType; 5908 bool HasUniqueTargetType = true; 5909 5910 // Collect explicit or viable (potentially in C++1y) conversions. 5911 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5912 NamedDecl *D = (*I)->getUnderlyingDecl(); 5913 CXXConversionDecl *Conversion; 5914 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5915 if (ConvTemplate) { 5916 if (getLangOpts().CPlusPlus14) 5917 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5918 else 5919 continue; // C++11 does not consider conversion operator templates(?). 5920 } else 5921 Conversion = cast<CXXConversionDecl>(D); 5922 5923 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5924 "Conversion operator templates are considered potentially " 5925 "viable in C++1y"); 5926 5927 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5928 if (Converter.match(CurToType) || ConvTemplate) { 5929 5930 if (Conversion->isExplicit()) { 5931 // FIXME: For C++1y, do we need this restriction? 5932 // cf. diagnoseNoViableConversion() 5933 if (!ConvTemplate) 5934 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5935 } else { 5936 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5937 if (ToType.isNull()) 5938 ToType = CurToType.getUnqualifiedType(); 5939 else if (HasUniqueTargetType && 5940 (CurToType.getUnqualifiedType() != ToType)) 5941 HasUniqueTargetType = false; 5942 } 5943 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5944 } 5945 } 5946 } 5947 5948 if (getLangOpts().CPlusPlus14) { 5949 // C++1y [conv]p6: 5950 // ... An expression e of class type E appearing in such a context 5951 // is said to be contextually implicitly converted to a specified 5952 // type T and is well-formed if and only if e can be implicitly 5953 // converted to a type T that is determined as follows: E is searched 5954 // for conversion functions whose return type is cv T or reference to 5955 // cv T such that T is allowed by the context. There shall be 5956 // exactly one such T. 5957 5958 // If no unique T is found: 5959 if (ToType.isNull()) { 5960 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5961 HadMultipleCandidates, 5962 ExplicitConversions)) 5963 return ExprError(); 5964 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5965 } 5966 5967 // If more than one unique Ts are found: 5968 if (!HasUniqueTargetType) 5969 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5970 ViableConversions); 5971 5972 // If one unique T is found: 5973 // First, build a candidate set from the previously recorded 5974 // potentially viable conversions. 5975 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5976 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5977 CandidateSet); 5978 5979 // Then, perform overload resolution over the candidate set. 5980 OverloadCandidateSet::iterator Best; 5981 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5982 case OR_Success: { 5983 // Apply this conversion. 5984 DeclAccessPair Found = 5985 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5986 if (recordConversion(*this, Loc, From, Converter, T, 5987 HadMultipleCandidates, Found)) 5988 return ExprError(); 5989 break; 5990 } 5991 case OR_Ambiguous: 5992 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5993 ViableConversions); 5994 case OR_No_Viable_Function: 5995 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5996 HadMultipleCandidates, 5997 ExplicitConversions)) 5998 return ExprError(); 5999 LLVM_FALLTHROUGH; 6000 case OR_Deleted: 6001 // We'll complain below about a non-integral condition type. 6002 break; 6003 } 6004 } else { 6005 switch (ViableConversions.size()) { 6006 case 0: { 6007 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6008 HadMultipleCandidates, 6009 ExplicitConversions)) 6010 return ExprError(); 6011 6012 // We'll complain below about a non-integral condition type. 6013 break; 6014 } 6015 case 1: { 6016 // Apply this conversion. 6017 DeclAccessPair Found = ViableConversions[0]; 6018 if (recordConversion(*this, Loc, From, Converter, T, 6019 HadMultipleCandidates, Found)) 6020 return ExprError(); 6021 break; 6022 } 6023 default: 6024 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6025 ViableConversions); 6026 } 6027 } 6028 6029 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6030 } 6031 6032 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6033 /// an acceptable non-member overloaded operator for a call whose 6034 /// arguments have types T1 (and, if non-empty, T2). This routine 6035 /// implements the check in C++ [over.match.oper]p3b2 concerning 6036 /// enumeration types. 6037 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6038 FunctionDecl *Fn, 6039 ArrayRef<Expr *> Args) { 6040 QualType T1 = Args[0]->getType(); 6041 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6042 6043 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6044 return true; 6045 6046 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6047 return true; 6048 6049 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 6050 if (Proto->getNumParams() < 1) 6051 return false; 6052 6053 if (T1->isEnumeralType()) { 6054 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6055 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6056 return true; 6057 } 6058 6059 if (Proto->getNumParams() < 2) 6060 return false; 6061 6062 if (!T2.isNull() && T2->isEnumeralType()) { 6063 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6064 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6065 return true; 6066 } 6067 6068 return false; 6069 } 6070 6071 /// AddOverloadCandidate - Adds the given function to the set of 6072 /// candidate functions, using the given function call arguments. If 6073 /// @p SuppressUserConversions, then don't allow user-defined 6074 /// conversions via constructors or conversion operators. 6075 /// 6076 /// \param PartialOverloading true if we are performing "partial" overloading 6077 /// based on an incomplete set of function arguments. This feature is used by 6078 /// code completion. 6079 void Sema::AddOverloadCandidate( 6080 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6081 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6082 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6083 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6084 OverloadCandidateParamOrder PO) { 6085 const FunctionProtoType *Proto 6086 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6087 assert(Proto && "Functions without a prototype cannot be overloaded"); 6088 assert(!Function->getDescribedFunctionTemplate() && 6089 "Use AddTemplateOverloadCandidate for function templates"); 6090 6091 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6092 if (!isa<CXXConstructorDecl>(Method)) { 6093 // If we get here, it's because we're calling a member function 6094 // that is named without a member access expression (e.g., 6095 // "this->f") that was either written explicitly or created 6096 // implicitly. This can happen with a qualified call to a member 6097 // function, e.g., X::f(). We use an empty type for the implied 6098 // object argument (C++ [over.call.func]p3), and the acting context 6099 // is irrelevant. 6100 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6101 Expr::Classification::makeSimpleLValue(), Args, 6102 CandidateSet, SuppressUserConversions, 6103 PartialOverloading, EarlyConversions, PO); 6104 return; 6105 } 6106 // We treat a constructor like a non-member function, since its object 6107 // argument doesn't participate in overload resolution. 6108 } 6109 6110 if (!CandidateSet.isNewCandidate(Function, PO)) 6111 return; 6112 6113 // C++11 [class.copy]p11: [DR1402] 6114 // A defaulted move constructor that is defined as deleted is ignored by 6115 // overload resolution. 6116 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6117 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6118 Constructor->isMoveConstructor()) 6119 return; 6120 6121 // Overload resolution is always an unevaluated context. 6122 EnterExpressionEvaluationContext Unevaluated( 6123 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6124 6125 // C++ [over.match.oper]p3: 6126 // if no operand has a class type, only those non-member functions in the 6127 // lookup set that have a first parameter of type T1 or "reference to 6128 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6129 // is a right operand) a second parameter of type T2 or "reference to 6130 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6131 // candidate functions. 6132 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6133 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6134 return; 6135 6136 // Add this candidate 6137 OverloadCandidate &Candidate = 6138 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6139 Candidate.FoundDecl = FoundDecl; 6140 Candidate.Function = Function; 6141 Candidate.Viable = true; 6142 Candidate.RewriteKind = 6143 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6144 Candidate.IsSurrogate = false; 6145 Candidate.IsADLCandidate = IsADLCandidate; 6146 Candidate.IgnoreObjectArgument = false; 6147 Candidate.ExplicitCallArguments = Args.size(); 6148 6149 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6150 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6151 Candidate.Viable = false; 6152 Candidate.FailureKind = ovl_non_default_multiversion_function; 6153 return; 6154 } 6155 6156 if (Constructor) { 6157 // C++ [class.copy]p3: 6158 // A member function template is never instantiated to perform the copy 6159 // of a class object to an object of its class type. 6160 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6161 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6162 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6163 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6164 ClassType))) { 6165 Candidate.Viable = false; 6166 Candidate.FailureKind = ovl_fail_illegal_constructor; 6167 return; 6168 } 6169 6170 // C++ [over.match.funcs]p8: (proposed DR resolution) 6171 // A constructor inherited from class type C that has a first parameter 6172 // of type "reference to P" (including such a constructor instantiated 6173 // from a template) is excluded from the set of candidate functions when 6174 // constructing an object of type cv D if the argument list has exactly 6175 // one argument and D is reference-related to P and P is reference-related 6176 // to C. 6177 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6178 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6179 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6180 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6181 QualType C = Context.getRecordType(Constructor->getParent()); 6182 QualType D = Context.getRecordType(Shadow->getParent()); 6183 SourceLocation Loc = Args.front()->getExprLoc(); 6184 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6185 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6186 Candidate.Viable = false; 6187 Candidate.FailureKind = ovl_fail_inhctor_slice; 6188 return; 6189 } 6190 } 6191 6192 // Check that the constructor is capable of constructing an object in the 6193 // destination address space. 6194 if (!Qualifiers::isAddressSpaceSupersetOf( 6195 Constructor->getMethodQualifiers().getAddressSpace(), 6196 CandidateSet.getDestAS())) { 6197 Candidate.Viable = false; 6198 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6199 } 6200 } 6201 6202 unsigned NumParams = Proto->getNumParams(); 6203 6204 // (C++ 13.3.2p2): A candidate function having fewer than m 6205 // parameters is viable only if it has an ellipsis in its parameter 6206 // list (8.3.5). 6207 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6208 !Proto->isVariadic()) { 6209 Candidate.Viable = false; 6210 Candidate.FailureKind = ovl_fail_too_many_arguments; 6211 return; 6212 } 6213 6214 // (C++ 13.3.2p2): A candidate function having more than m parameters 6215 // is viable only if the (m+1)st parameter has a default argument 6216 // (8.3.6). For the purposes of overload resolution, the 6217 // parameter list is truncated on the right, so that there are 6218 // exactly m parameters. 6219 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6220 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6221 // Not enough arguments. 6222 Candidate.Viable = false; 6223 Candidate.FailureKind = ovl_fail_too_few_arguments; 6224 return; 6225 } 6226 6227 // (CUDA B.1): Check for invalid calls between targets. 6228 if (getLangOpts().CUDA) 6229 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6230 // Skip the check for callers that are implicit members, because in this 6231 // case we may not yet know what the member's target is; the target is 6232 // inferred for the member automatically, based on the bases and fields of 6233 // the class. 6234 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6235 Candidate.Viable = false; 6236 Candidate.FailureKind = ovl_fail_bad_target; 6237 return; 6238 } 6239 6240 // Determine the implicit conversion sequences for each of the 6241 // arguments. 6242 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6243 unsigned ConvIdx = 6244 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6245 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6246 // We already formed a conversion sequence for this parameter during 6247 // template argument deduction. 6248 } else if (ArgIdx < NumParams) { 6249 // (C++ 13.3.2p3): for F to be a viable function, there shall 6250 // exist for each argument an implicit conversion sequence 6251 // (13.3.3.1) that converts that argument to the corresponding 6252 // parameter of F. 6253 QualType ParamType = Proto->getParamType(ArgIdx); 6254 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6255 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6256 /*InOverloadResolution=*/true, 6257 /*AllowObjCWritebackConversion=*/ 6258 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6259 if (Candidate.Conversions[ConvIdx].isBad()) { 6260 Candidate.Viable = false; 6261 Candidate.FailureKind = ovl_fail_bad_conversion; 6262 return; 6263 } 6264 } else { 6265 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6266 // argument for which there is no corresponding parameter is 6267 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6268 Candidate.Conversions[ConvIdx].setEllipsis(); 6269 } 6270 } 6271 6272 if (!AllowExplicit) { 6273 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); 6274 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { 6275 Candidate.Viable = false; 6276 Candidate.FailureKind = ovl_fail_explicit_resolved; 6277 return; 6278 } 6279 } 6280 6281 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6282 Candidate.Viable = false; 6283 Candidate.FailureKind = ovl_fail_enable_if; 6284 Candidate.DeductionFailure.Data = FailedAttr; 6285 return; 6286 } 6287 6288 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6289 Candidate.Viable = false; 6290 Candidate.FailureKind = ovl_fail_ext_disabled; 6291 return; 6292 } 6293 } 6294 6295 ObjCMethodDecl * 6296 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6297 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6298 if (Methods.size() <= 1) 6299 return nullptr; 6300 6301 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6302 bool Match = true; 6303 ObjCMethodDecl *Method = Methods[b]; 6304 unsigned NumNamedArgs = Sel.getNumArgs(); 6305 // Method might have more arguments than selector indicates. This is due 6306 // to addition of c-style arguments in method. 6307 if (Method->param_size() > NumNamedArgs) 6308 NumNamedArgs = Method->param_size(); 6309 if (Args.size() < NumNamedArgs) 6310 continue; 6311 6312 for (unsigned i = 0; i < NumNamedArgs; i++) { 6313 // We can't do any type-checking on a type-dependent argument. 6314 if (Args[i]->isTypeDependent()) { 6315 Match = false; 6316 break; 6317 } 6318 6319 ParmVarDecl *param = Method->parameters()[i]; 6320 Expr *argExpr = Args[i]; 6321 assert(argExpr && "SelectBestMethod(): missing expression"); 6322 6323 // Strip the unbridged-cast placeholder expression off unless it's 6324 // a consumed argument. 6325 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6326 !param->hasAttr<CFConsumedAttr>()) 6327 argExpr = stripARCUnbridgedCast(argExpr); 6328 6329 // If the parameter is __unknown_anytype, move on to the next method. 6330 if (param->getType() == Context.UnknownAnyTy) { 6331 Match = false; 6332 break; 6333 } 6334 6335 ImplicitConversionSequence ConversionState 6336 = TryCopyInitialization(*this, argExpr, param->getType(), 6337 /*SuppressUserConversions*/false, 6338 /*InOverloadResolution=*/true, 6339 /*AllowObjCWritebackConversion=*/ 6340 getLangOpts().ObjCAutoRefCount, 6341 /*AllowExplicit*/false); 6342 // This function looks for a reasonably-exact match, so we consider 6343 // incompatible pointer conversions to be a failure here. 6344 if (ConversionState.isBad() || 6345 (ConversionState.isStandard() && 6346 ConversionState.Standard.Second == 6347 ICK_Incompatible_Pointer_Conversion)) { 6348 Match = false; 6349 break; 6350 } 6351 } 6352 // Promote additional arguments to variadic methods. 6353 if (Match && Method->isVariadic()) { 6354 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6355 if (Args[i]->isTypeDependent()) { 6356 Match = false; 6357 break; 6358 } 6359 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6360 nullptr); 6361 if (Arg.isInvalid()) { 6362 Match = false; 6363 break; 6364 } 6365 } 6366 } else { 6367 // Check for extra arguments to non-variadic methods. 6368 if (Args.size() != NumNamedArgs) 6369 Match = false; 6370 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6371 // Special case when selectors have no argument. In this case, select 6372 // one with the most general result type of 'id'. 6373 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6374 QualType ReturnT = Methods[b]->getReturnType(); 6375 if (ReturnT->isObjCIdType()) 6376 return Methods[b]; 6377 } 6378 } 6379 } 6380 6381 if (Match) 6382 return Method; 6383 } 6384 return nullptr; 6385 } 6386 6387 static bool 6388 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6389 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6390 bool MissingImplicitThis, Expr *&ConvertedThis, 6391 SmallVectorImpl<Expr *> &ConvertedArgs) { 6392 if (ThisArg) { 6393 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6394 assert(!isa<CXXConstructorDecl>(Method) && 6395 "Shouldn't have `this` for ctors!"); 6396 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6397 ExprResult R = S.PerformObjectArgumentInitialization( 6398 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6399 if (R.isInvalid()) 6400 return false; 6401 ConvertedThis = R.get(); 6402 } else { 6403 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6404 (void)MD; 6405 assert((MissingImplicitThis || MD->isStatic() || 6406 isa<CXXConstructorDecl>(MD)) && 6407 "Expected `this` for non-ctor instance methods"); 6408 } 6409 ConvertedThis = nullptr; 6410 } 6411 6412 // Ignore any variadic arguments. Converting them is pointless, since the 6413 // user can't refer to them in the function condition. 6414 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6415 6416 // Convert the arguments. 6417 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6418 ExprResult R; 6419 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6420 S.Context, Function->getParamDecl(I)), 6421 SourceLocation(), Args[I]); 6422 6423 if (R.isInvalid()) 6424 return false; 6425 6426 ConvertedArgs.push_back(R.get()); 6427 } 6428 6429 if (Trap.hasErrorOccurred()) 6430 return false; 6431 6432 // Push default arguments if needed. 6433 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6434 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6435 ParmVarDecl *P = Function->getParamDecl(i); 6436 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6437 ? P->getUninstantiatedDefaultArg() 6438 : P->getDefaultArg(); 6439 // This can only happen in code completion, i.e. when PartialOverloading 6440 // is true. 6441 if (!DefArg) 6442 return false; 6443 ExprResult R = 6444 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6445 S.Context, Function->getParamDecl(i)), 6446 SourceLocation(), DefArg); 6447 if (R.isInvalid()) 6448 return false; 6449 ConvertedArgs.push_back(R.get()); 6450 } 6451 6452 if (Trap.hasErrorOccurred()) 6453 return false; 6454 } 6455 return true; 6456 } 6457 6458 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6459 bool MissingImplicitThis) { 6460 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6461 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6462 return nullptr; 6463 6464 SFINAETrap Trap(*this); 6465 SmallVector<Expr *, 16> ConvertedArgs; 6466 // FIXME: We should look into making enable_if late-parsed. 6467 Expr *DiscardedThis; 6468 if (!convertArgsForAvailabilityChecks( 6469 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6470 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6471 return *EnableIfAttrs.begin(); 6472 6473 for (auto *EIA : EnableIfAttrs) { 6474 APValue Result; 6475 // FIXME: This doesn't consider value-dependent cases, because doing so is 6476 // very difficult. Ideally, we should handle them more gracefully. 6477 if (EIA->getCond()->isValueDependent() || 6478 !EIA->getCond()->EvaluateWithSubstitution( 6479 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6480 return EIA; 6481 6482 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6483 return EIA; 6484 } 6485 return nullptr; 6486 } 6487 6488 template <typename CheckFn> 6489 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6490 bool ArgDependent, SourceLocation Loc, 6491 CheckFn &&IsSuccessful) { 6492 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6493 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6494 if (ArgDependent == DIA->getArgDependent()) 6495 Attrs.push_back(DIA); 6496 } 6497 6498 // Common case: No diagnose_if attributes, so we can quit early. 6499 if (Attrs.empty()) 6500 return false; 6501 6502 auto WarningBegin = std::stable_partition( 6503 Attrs.begin(), Attrs.end(), 6504 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6505 6506 // Note that diagnose_if attributes are late-parsed, so they appear in the 6507 // correct order (unlike enable_if attributes). 6508 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6509 IsSuccessful); 6510 if (ErrAttr != WarningBegin) { 6511 const DiagnoseIfAttr *DIA = *ErrAttr; 6512 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6513 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6514 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6515 return true; 6516 } 6517 6518 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6519 if (IsSuccessful(DIA)) { 6520 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6521 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6522 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6523 } 6524 6525 return false; 6526 } 6527 6528 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6529 const Expr *ThisArg, 6530 ArrayRef<const Expr *> Args, 6531 SourceLocation Loc) { 6532 return diagnoseDiagnoseIfAttrsWith( 6533 *this, Function, /*ArgDependent=*/true, Loc, 6534 [&](const DiagnoseIfAttr *DIA) { 6535 APValue Result; 6536 // It's sane to use the same Args for any redecl of this function, since 6537 // EvaluateWithSubstitution only cares about the position of each 6538 // argument in the arg list, not the ParmVarDecl* it maps to. 6539 if (!DIA->getCond()->EvaluateWithSubstitution( 6540 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6541 return false; 6542 return Result.isInt() && Result.getInt().getBoolValue(); 6543 }); 6544 } 6545 6546 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6547 SourceLocation Loc) { 6548 return diagnoseDiagnoseIfAttrsWith( 6549 *this, ND, /*ArgDependent=*/false, Loc, 6550 [&](const DiagnoseIfAttr *DIA) { 6551 bool Result; 6552 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6553 Result; 6554 }); 6555 } 6556 6557 /// Add all of the function declarations in the given function set to 6558 /// the overload candidate set. 6559 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6560 ArrayRef<Expr *> Args, 6561 OverloadCandidateSet &CandidateSet, 6562 TemplateArgumentListInfo *ExplicitTemplateArgs, 6563 bool SuppressUserConversions, 6564 bool PartialOverloading, 6565 bool FirstArgumentIsBase) { 6566 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6567 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6568 ArrayRef<Expr *> FunctionArgs = Args; 6569 6570 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6571 FunctionDecl *FD = 6572 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6573 6574 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6575 QualType ObjectType; 6576 Expr::Classification ObjectClassification; 6577 if (Args.size() > 0) { 6578 if (Expr *E = Args[0]) { 6579 // Use the explicit base to restrict the lookup: 6580 ObjectType = E->getType(); 6581 // Pointers in the object arguments are implicitly dereferenced, so we 6582 // always classify them as l-values. 6583 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6584 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6585 else 6586 ObjectClassification = E->Classify(Context); 6587 } // .. else there is an implicit base. 6588 FunctionArgs = Args.slice(1); 6589 } 6590 if (FunTmpl) { 6591 AddMethodTemplateCandidate( 6592 FunTmpl, F.getPair(), 6593 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6594 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6595 FunctionArgs, CandidateSet, SuppressUserConversions, 6596 PartialOverloading); 6597 } else { 6598 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6599 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6600 ObjectClassification, FunctionArgs, CandidateSet, 6601 SuppressUserConversions, PartialOverloading); 6602 } 6603 } else { 6604 // This branch handles both standalone functions and static methods. 6605 6606 // Slice the first argument (which is the base) when we access 6607 // static method as non-static. 6608 if (Args.size() > 0 && 6609 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6610 !isa<CXXConstructorDecl>(FD)))) { 6611 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6612 FunctionArgs = Args.slice(1); 6613 } 6614 if (FunTmpl) { 6615 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6616 ExplicitTemplateArgs, FunctionArgs, 6617 CandidateSet, SuppressUserConversions, 6618 PartialOverloading); 6619 } else { 6620 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6621 SuppressUserConversions, PartialOverloading); 6622 } 6623 } 6624 } 6625 } 6626 6627 /// AddMethodCandidate - Adds a named decl (which is some kind of 6628 /// method) as a method candidate to the given overload set. 6629 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6630 Expr::Classification ObjectClassification, 6631 ArrayRef<Expr *> Args, 6632 OverloadCandidateSet &CandidateSet, 6633 bool SuppressUserConversions, 6634 OverloadCandidateParamOrder PO) { 6635 NamedDecl *Decl = FoundDecl.getDecl(); 6636 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6637 6638 if (isa<UsingShadowDecl>(Decl)) 6639 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6640 6641 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6642 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6643 "Expected a member function template"); 6644 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6645 /*ExplicitArgs*/ nullptr, ObjectType, 6646 ObjectClassification, Args, CandidateSet, 6647 SuppressUserConversions, false, PO); 6648 } else { 6649 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6650 ObjectType, ObjectClassification, Args, CandidateSet, 6651 SuppressUserConversions, false, None, PO); 6652 } 6653 } 6654 6655 /// AddMethodCandidate - Adds the given C++ member function to the set 6656 /// of candidate functions, using the given function call arguments 6657 /// and the object argument (@c Object). For example, in a call 6658 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6659 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6660 /// allow user-defined conversions via constructors or conversion 6661 /// operators. 6662 void 6663 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6664 CXXRecordDecl *ActingContext, QualType ObjectType, 6665 Expr::Classification ObjectClassification, 6666 ArrayRef<Expr *> Args, 6667 OverloadCandidateSet &CandidateSet, 6668 bool SuppressUserConversions, 6669 bool PartialOverloading, 6670 ConversionSequenceList EarlyConversions, 6671 OverloadCandidateParamOrder PO) { 6672 const FunctionProtoType *Proto 6673 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6674 assert(Proto && "Methods without a prototype cannot be overloaded"); 6675 assert(!isa<CXXConstructorDecl>(Method) && 6676 "Use AddOverloadCandidate for constructors"); 6677 6678 if (!CandidateSet.isNewCandidate(Method, PO)) 6679 return; 6680 6681 // C++11 [class.copy]p23: [DR1402] 6682 // A defaulted move assignment operator that is defined as deleted is 6683 // ignored by overload resolution. 6684 if (Method->isDefaulted() && Method->isDeleted() && 6685 Method->isMoveAssignmentOperator()) 6686 return; 6687 6688 // Overload resolution is always an unevaluated context. 6689 EnterExpressionEvaluationContext Unevaluated( 6690 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6691 6692 // Add this candidate 6693 OverloadCandidate &Candidate = 6694 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6695 Candidate.FoundDecl = FoundDecl; 6696 Candidate.Function = Method; 6697 Candidate.RewriteKind = 6698 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6699 Candidate.IsSurrogate = false; 6700 Candidate.IgnoreObjectArgument = false; 6701 Candidate.ExplicitCallArguments = Args.size(); 6702 6703 unsigned NumParams = Proto->getNumParams(); 6704 6705 // (C++ 13.3.2p2): A candidate function having fewer than m 6706 // parameters is viable only if it has an ellipsis in its parameter 6707 // list (8.3.5). 6708 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6709 !Proto->isVariadic()) { 6710 Candidate.Viable = false; 6711 Candidate.FailureKind = ovl_fail_too_many_arguments; 6712 return; 6713 } 6714 6715 // (C++ 13.3.2p2): A candidate function having more than m parameters 6716 // is viable only if the (m+1)st parameter has a default argument 6717 // (8.3.6). For the purposes of overload resolution, the 6718 // parameter list is truncated on the right, so that there are 6719 // exactly m parameters. 6720 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6721 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6722 // Not enough arguments. 6723 Candidate.Viable = false; 6724 Candidate.FailureKind = ovl_fail_too_few_arguments; 6725 return; 6726 } 6727 6728 Candidate.Viable = true; 6729 6730 if (Method->isStatic() || ObjectType.isNull()) 6731 // The implicit object argument is ignored. 6732 Candidate.IgnoreObjectArgument = true; 6733 else { 6734 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6735 // Determine the implicit conversion sequence for the object 6736 // parameter. 6737 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6738 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6739 Method, ActingContext); 6740 if (Candidate.Conversions[ConvIdx].isBad()) { 6741 Candidate.Viable = false; 6742 Candidate.FailureKind = ovl_fail_bad_conversion; 6743 return; 6744 } 6745 } 6746 6747 // (CUDA B.1): Check for invalid calls between targets. 6748 if (getLangOpts().CUDA) 6749 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6750 if (!IsAllowedCUDACall(Caller, Method)) { 6751 Candidate.Viable = false; 6752 Candidate.FailureKind = ovl_fail_bad_target; 6753 return; 6754 } 6755 6756 // Determine the implicit conversion sequences for each of the 6757 // arguments. 6758 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6759 unsigned ConvIdx = 6760 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6761 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6762 // We already formed a conversion sequence for this parameter during 6763 // template argument deduction. 6764 } else if (ArgIdx < NumParams) { 6765 // (C++ 13.3.2p3): for F to be a viable function, there shall 6766 // exist for each argument an implicit conversion sequence 6767 // (13.3.3.1) that converts that argument to the corresponding 6768 // parameter of F. 6769 QualType ParamType = Proto->getParamType(ArgIdx); 6770 Candidate.Conversions[ConvIdx] 6771 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6772 SuppressUserConversions, 6773 /*InOverloadResolution=*/true, 6774 /*AllowObjCWritebackConversion=*/ 6775 getLangOpts().ObjCAutoRefCount); 6776 if (Candidate.Conversions[ConvIdx].isBad()) { 6777 Candidate.Viable = false; 6778 Candidate.FailureKind = ovl_fail_bad_conversion; 6779 return; 6780 } 6781 } else { 6782 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6783 // argument for which there is no corresponding parameter is 6784 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6785 Candidate.Conversions[ConvIdx].setEllipsis(); 6786 } 6787 } 6788 6789 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6790 Candidate.Viable = false; 6791 Candidate.FailureKind = ovl_fail_enable_if; 6792 Candidate.DeductionFailure.Data = FailedAttr; 6793 return; 6794 } 6795 6796 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6797 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6798 Candidate.Viable = false; 6799 Candidate.FailureKind = ovl_non_default_multiversion_function; 6800 } 6801 } 6802 6803 /// Add a C++ member function template as a candidate to the candidate 6804 /// set, using template argument deduction to produce an appropriate member 6805 /// function template specialization. 6806 void Sema::AddMethodTemplateCandidate( 6807 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6808 CXXRecordDecl *ActingContext, 6809 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6810 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6811 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6812 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6813 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6814 return; 6815 6816 // C++ [over.match.funcs]p7: 6817 // In each case where a candidate is a function template, candidate 6818 // function template specializations are generated using template argument 6819 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6820 // candidate functions in the usual way.113) A given name can refer to one 6821 // or more function templates and also to a set of overloaded non-template 6822 // functions. In such a case, the candidate functions generated from each 6823 // function template are combined with the set of non-template candidate 6824 // functions. 6825 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6826 FunctionDecl *Specialization = nullptr; 6827 ConversionSequenceList Conversions; 6828 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6829 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6830 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6831 return CheckNonDependentConversions( 6832 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6833 SuppressUserConversions, ActingContext, ObjectType, 6834 ObjectClassification, PO); 6835 })) { 6836 OverloadCandidate &Candidate = 6837 CandidateSet.addCandidate(Conversions.size(), Conversions); 6838 Candidate.FoundDecl = FoundDecl; 6839 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6840 Candidate.Viable = false; 6841 Candidate.RewriteKind = 6842 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6843 Candidate.IsSurrogate = false; 6844 Candidate.IgnoreObjectArgument = 6845 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6846 ObjectType.isNull(); 6847 Candidate.ExplicitCallArguments = Args.size(); 6848 if (Result == TDK_NonDependentConversionFailure) 6849 Candidate.FailureKind = ovl_fail_bad_conversion; 6850 else { 6851 Candidate.FailureKind = ovl_fail_bad_deduction; 6852 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6853 Info); 6854 } 6855 return; 6856 } 6857 6858 // Add the function template specialization produced by template argument 6859 // deduction as a candidate. 6860 assert(Specialization && "Missing member function template specialization?"); 6861 assert(isa<CXXMethodDecl>(Specialization) && 6862 "Specialization is not a member function?"); 6863 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6864 ActingContext, ObjectType, ObjectClassification, Args, 6865 CandidateSet, SuppressUserConversions, PartialOverloading, 6866 Conversions, PO); 6867 } 6868 6869 /// Add a C++ function template specialization as a candidate 6870 /// in the candidate set, using template argument deduction to produce 6871 /// an appropriate function template specialization. 6872 void Sema::AddTemplateOverloadCandidate( 6873 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6874 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6875 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6876 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6877 OverloadCandidateParamOrder PO) { 6878 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6879 return; 6880 6881 // C++ [over.match.funcs]p7: 6882 // In each case where a candidate is a function template, candidate 6883 // function template specializations are generated using template argument 6884 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6885 // candidate functions in the usual way.113) A given name can refer to one 6886 // or more function templates and also to a set of overloaded non-template 6887 // functions. In such a case, the candidate functions generated from each 6888 // function template are combined with the set of non-template candidate 6889 // functions. 6890 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6891 FunctionDecl *Specialization = nullptr; 6892 ConversionSequenceList Conversions; 6893 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6894 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6895 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6896 return CheckNonDependentConversions( 6897 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 6898 SuppressUserConversions, nullptr, QualType(), {}, PO); 6899 })) { 6900 OverloadCandidate &Candidate = 6901 CandidateSet.addCandidate(Conversions.size(), Conversions); 6902 Candidate.FoundDecl = FoundDecl; 6903 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6904 Candidate.Viable = false; 6905 Candidate.RewriteKind = 6906 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6907 Candidate.IsSurrogate = false; 6908 Candidate.IsADLCandidate = IsADLCandidate; 6909 // Ignore the object argument if there is one, since we don't have an object 6910 // type. 6911 Candidate.IgnoreObjectArgument = 6912 isa<CXXMethodDecl>(Candidate.Function) && 6913 !isa<CXXConstructorDecl>(Candidate.Function); 6914 Candidate.ExplicitCallArguments = Args.size(); 6915 if (Result == TDK_NonDependentConversionFailure) 6916 Candidate.FailureKind = ovl_fail_bad_conversion; 6917 else { 6918 Candidate.FailureKind = ovl_fail_bad_deduction; 6919 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6920 Info); 6921 } 6922 return; 6923 } 6924 6925 // Add the function template specialization produced by template argument 6926 // deduction as a candidate. 6927 assert(Specialization && "Missing function template specialization?"); 6928 AddOverloadCandidate( 6929 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 6930 PartialOverloading, AllowExplicit, 6931 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 6932 } 6933 6934 /// Check that implicit conversion sequences can be formed for each argument 6935 /// whose corresponding parameter has a non-dependent type, per DR1391's 6936 /// [temp.deduct.call]p10. 6937 bool Sema::CheckNonDependentConversions( 6938 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6939 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6940 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6941 CXXRecordDecl *ActingContext, QualType ObjectType, 6942 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 6943 // FIXME: The cases in which we allow explicit conversions for constructor 6944 // arguments never consider calling a constructor template. It's not clear 6945 // that is correct. 6946 const bool AllowExplicit = false; 6947 6948 auto *FD = FunctionTemplate->getTemplatedDecl(); 6949 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6950 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6951 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6952 6953 Conversions = 6954 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6955 6956 // Overload resolution is always an unevaluated context. 6957 EnterExpressionEvaluationContext Unevaluated( 6958 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6959 6960 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6961 // require that, but this check should never result in a hard error, and 6962 // overload resolution is permitted to sidestep instantiations. 6963 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6964 !ObjectType.isNull()) { 6965 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6966 Conversions[ConvIdx] = TryObjectArgumentInitialization( 6967 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6968 Method, ActingContext); 6969 if (Conversions[ConvIdx].isBad()) 6970 return true; 6971 } 6972 6973 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6974 ++I) { 6975 QualType ParamType = ParamTypes[I]; 6976 if (!ParamType->isDependentType()) { 6977 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 6978 ? 0 6979 : (ThisConversions + I); 6980 Conversions[ConvIdx] 6981 = TryCopyInitialization(*this, Args[I], ParamType, 6982 SuppressUserConversions, 6983 /*InOverloadResolution=*/true, 6984 /*AllowObjCWritebackConversion=*/ 6985 getLangOpts().ObjCAutoRefCount, 6986 AllowExplicit); 6987 if (Conversions[ConvIdx].isBad()) 6988 return true; 6989 } 6990 } 6991 6992 return false; 6993 } 6994 6995 /// Determine whether this is an allowable conversion from the result 6996 /// of an explicit conversion operator to the expected type, per C++ 6997 /// [over.match.conv]p1 and [over.match.ref]p1. 6998 /// 6999 /// \param ConvType The return type of the conversion function. 7000 /// 7001 /// \param ToType The type we are converting to. 7002 /// 7003 /// \param AllowObjCPointerConversion Allow a conversion from one 7004 /// Objective-C pointer to another. 7005 /// 7006 /// \returns true if the conversion is allowable, false otherwise. 7007 static bool isAllowableExplicitConversion(Sema &S, 7008 QualType ConvType, QualType ToType, 7009 bool AllowObjCPointerConversion) { 7010 QualType ToNonRefType = ToType.getNonReferenceType(); 7011 7012 // Easy case: the types are the same. 7013 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7014 return true; 7015 7016 // Allow qualification conversions. 7017 bool ObjCLifetimeConversion; 7018 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7019 ObjCLifetimeConversion)) 7020 return true; 7021 7022 // If we're not allowed to consider Objective-C pointer conversions, 7023 // we're done. 7024 if (!AllowObjCPointerConversion) 7025 return false; 7026 7027 // Is this an Objective-C pointer conversion? 7028 bool IncompatibleObjC = false; 7029 QualType ConvertedType; 7030 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7031 IncompatibleObjC); 7032 } 7033 7034 /// AddConversionCandidate - Add a C++ conversion function as a 7035 /// candidate in the candidate set (C++ [over.match.conv], 7036 /// C++ [over.match.copy]). From is the expression we're converting from, 7037 /// and ToType is the type that we're eventually trying to convert to 7038 /// (which may or may not be the same type as the type that the 7039 /// conversion function produces). 7040 void Sema::AddConversionCandidate( 7041 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7042 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7043 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7044 bool AllowExplicit, bool AllowResultConversion) { 7045 assert(!Conversion->getDescribedFunctionTemplate() && 7046 "Conversion function templates use AddTemplateConversionCandidate"); 7047 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7048 if (!CandidateSet.isNewCandidate(Conversion)) 7049 return; 7050 7051 // If the conversion function has an undeduced return type, trigger its 7052 // deduction now. 7053 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7054 if (DeduceReturnType(Conversion, From->getExprLoc())) 7055 return; 7056 ConvType = Conversion->getConversionType().getNonReferenceType(); 7057 } 7058 7059 // If we don't allow any conversion of the result type, ignore conversion 7060 // functions that don't convert to exactly (possibly cv-qualified) T. 7061 if (!AllowResultConversion && 7062 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7063 return; 7064 7065 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7066 // operator is only a candidate if its return type is the target type or 7067 // can be converted to the target type with a qualification conversion. 7068 if (Conversion->isExplicit() && 7069 !isAllowableExplicitConversion(*this, ConvType, ToType, 7070 AllowObjCConversionOnExplicit)) 7071 return; 7072 7073 // Overload resolution is always an unevaluated context. 7074 EnterExpressionEvaluationContext Unevaluated( 7075 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7076 7077 // Add this candidate 7078 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7079 Candidate.FoundDecl = FoundDecl; 7080 Candidate.Function = Conversion; 7081 Candidate.IsSurrogate = false; 7082 Candidate.IgnoreObjectArgument = false; 7083 Candidate.FinalConversion.setAsIdentityConversion(); 7084 Candidate.FinalConversion.setFromType(ConvType); 7085 Candidate.FinalConversion.setAllToTypes(ToType); 7086 Candidate.Viable = true; 7087 Candidate.ExplicitCallArguments = 1; 7088 7089 // C++ [over.match.funcs]p4: 7090 // For conversion functions, the function is considered to be a member of 7091 // the class of the implicit implied object argument for the purpose of 7092 // defining the type of the implicit object parameter. 7093 // 7094 // Determine the implicit conversion sequence for the implicit 7095 // object parameter. 7096 QualType ImplicitParamType = From->getType(); 7097 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7098 ImplicitParamType = FromPtrType->getPointeeType(); 7099 CXXRecordDecl *ConversionContext 7100 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7101 7102 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7103 *this, CandidateSet.getLocation(), From->getType(), 7104 From->Classify(Context), Conversion, ConversionContext); 7105 7106 if (Candidate.Conversions[0].isBad()) { 7107 Candidate.Viable = false; 7108 Candidate.FailureKind = ovl_fail_bad_conversion; 7109 return; 7110 } 7111 7112 // We won't go through a user-defined type conversion function to convert a 7113 // derived to base as such conversions are given Conversion Rank. They only 7114 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7115 QualType FromCanon 7116 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7117 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7118 if (FromCanon == ToCanon || 7119 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7120 Candidate.Viable = false; 7121 Candidate.FailureKind = ovl_fail_trivial_conversion; 7122 return; 7123 } 7124 7125 // To determine what the conversion from the result of calling the 7126 // conversion function to the type we're eventually trying to 7127 // convert to (ToType), we need to synthesize a call to the 7128 // conversion function and attempt copy initialization from it. This 7129 // makes sure that we get the right semantics with respect to 7130 // lvalues/rvalues and the type. Fortunately, we can allocate this 7131 // call on the stack and we don't need its arguments to be 7132 // well-formed. 7133 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7134 VK_LValue, From->getBeginLoc()); 7135 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7136 Context.getPointerType(Conversion->getType()), 7137 CK_FunctionToPointerDecay, 7138 &ConversionRef, VK_RValue); 7139 7140 QualType ConversionType = Conversion->getConversionType(); 7141 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7142 Candidate.Viable = false; 7143 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7144 return; 7145 } 7146 7147 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7148 7149 // Note that it is safe to allocate CallExpr on the stack here because 7150 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7151 // allocator). 7152 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7153 7154 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7155 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7156 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7157 7158 ImplicitConversionSequence ICS = 7159 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7160 /*SuppressUserConversions=*/true, 7161 /*InOverloadResolution=*/false, 7162 /*AllowObjCWritebackConversion=*/false); 7163 7164 switch (ICS.getKind()) { 7165 case ImplicitConversionSequence::StandardConversion: 7166 Candidate.FinalConversion = ICS.Standard; 7167 7168 // C++ [over.ics.user]p3: 7169 // If the user-defined conversion is specified by a specialization of a 7170 // conversion function template, the second standard conversion sequence 7171 // shall have exact match rank. 7172 if (Conversion->getPrimaryTemplate() && 7173 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7174 Candidate.Viable = false; 7175 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7176 return; 7177 } 7178 7179 // C++0x [dcl.init.ref]p5: 7180 // In the second case, if the reference is an rvalue reference and 7181 // the second standard conversion sequence of the user-defined 7182 // conversion sequence includes an lvalue-to-rvalue conversion, the 7183 // program is ill-formed. 7184 if (ToType->isRValueReferenceType() && 7185 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7186 Candidate.Viable = false; 7187 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7188 return; 7189 } 7190 break; 7191 7192 case ImplicitConversionSequence::BadConversion: 7193 Candidate.Viable = false; 7194 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7195 return; 7196 7197 default: 7198 llvm_unreachable( 7199 "Can only end up with a standard conversion sequence or failure"); 7200 } 7201 7202 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != 7203 ExplicitSpecKind::ResolvedFalse) { 7204 Candidate.Viable = false; 7205 Candidate.FailureKind = ovl_fail_explicit_resolved; 7206 return; 7207 } 7208 7209 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7210 Candidate.Viable = false; 7211 Candidate.FailureKind = ovl_fail_enable_if; 7212 Candidate.DeductionFailure.Data = FailedAttr; 7213 return; 7214 } 7215 7216 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7217 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7218 Candidate.Viable = false; 7219 Candidate.FailureKind = ovl_non_default_multiversion_function; 7220 } 7221 } 7222 7223 /// Adds a conversion function template specialization 7224 /// candidate to the overload set, using template argument deduction 7225 /// to deduce the template arguments of the conversion function 7226 /// template from the type that we are converting to (C++ 7227 /// [temp.deduct.conv]). 7228 void Sema::AddTemplateConversionCandidate( 7229 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7230 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7231 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7232 bool AllowExplicit, bool AllowResultConversion) { 7233 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7234 "Only conversion function templates permitted here"); 7235 7236 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7237 return; 7238 7239 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7240 CXXConversionDecl *Specialization = nullptr; 7241 if (TemplateDeductionResult Result 7242 = DeduceTemplateArguments(FunctionTemplate, ToType, 7243 Specialization, Info)) { 7244 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7245 Candidate.FoundDecl = FoundDecl; 7246 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7247 Candidate.Viable = false; 7248 Candidate.FailureKind = ovl_fail_bad_deduction; 7249 Candidate.IsSurrogate = false; 7250 Candidate.IgnoreObjectArgument = false; 7251 Candidate.ExplicitCallArguments = 1; 7252 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7253 Info); 7254 return; 7255 } 7256 7257 // Add the conversion function template specialization produced by 7258 // template argument deduction as a candidate. 7259 assert(Specialization && "Missing function template specialization?"); 7260 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7261 CandidateSet, AllowObjCConversionOnExplicit, 7262 AllowExplicit, AllowResultConversion); 7263 } 7264 7265 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7266 /// converts the given @c Object to a function pointer via the 7267 /// conversion function @c Conversion, and then attempts to call it 7268 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7269 /// the type of function that we'll eventually be calling. 7270 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7271 DeclAccessPair FoundDecl, 7272 CXXRecordDecl *ActingContext, 7273 const FunctionProtoType *Proto, 7274 Expr *Object, 7275 ArrayRef<Expr *> Args, 7276 OverloadCandidateSet& CandidateSet) { 7277 if (!CandidateSet.isNewCandidate(Conversion)) 7278 return; 7279 7280 // Overload resolution is always an unevaluated context. 7281 EnterExpressionEvaluationContext Unevaluated( 7282 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7283 7284 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7285 Candidate.FoundDecl = FoundDecl; 7286 Candidate.Function = nullptr; 7287 Candidate.Surrogate = Conversion; 7288 Candidate.Viable = true; 7289 Candidate.IsSurrogate = true; 7290 Candidate.IgnoreObjectArgument = false; 7291 Candidate.ExplicitCallArguments = Args.size(); 7292 7293 // Determine the implicit conversion sequence for the implicit 7294 // object parameter. 7295 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7296 *this, CandidateSet.getLocation(), Object->getType(), 7297 Object->Classify(Context), Conversion, ActingContext); 7298 if (ObjectInit.isBad()) { 7299 Candidate.Viable = false; 7300 Candidate.FailureKind = ovl_fail_bad_conversion; 7301 Candidate.Conversions[0] = ObjectInit; 7302 return; 7303 } 7304 7305 // The first conversion is actually a user-defined conversion whose 7306 // first conversion is ObjectInit's standard conversion (which is 7307 // effectively a reference binding). Record it as such. 7308 Candidate.Conversions[0].setUserDefined(); 7309 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7310 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7311 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7312 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7313 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7314 Candidate.Conversions[0].UserDefined.After 7315 = Candidate.Conversions[0].UserDefined.Before; 7316 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7317 7318 // Find the 7319 unsigned NumParams = Proto->getNumParams(); 7320 7321 // (C++ 13.3.2p2): A candidate function having fewer than m 7322 // parameters is viable only if it has an ellipsis in its parameter 7323 // list (8.3.5). 7324 if (Args.size() > NumParams && !Proto->isVariadic()) { 7325 Candidate.Viable = false; 7326 Candidate.FailureKind = ovl_fail_too_many_arguments; 7327 return; 7328 } 7329 7330 // Function types don't have any default arguments, so just check if 7331 // we have enough arguments. 7332 if (Args.size() < NumParams) { 7333 // Not enough arguments. 7334 Candidate.Viable = false; 7335 Candidate.FailureKind = ovl_fail_too_few_arguments; 7336 return; 7337 } 7338 7339 // Determine the implicit conversion sequences for each of the 7340 // arguments. 7341 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7342 if (ArgIdx < NumParams) { 7343 // (C++ 13.3.2p3): for F to be a viable function, there shall 7344 // exist for each argument an implicit conversion sequence 7345 // (13.3.3.1) that converts that argument to the corresponding 7346 // parameter of F. 7347 QualType ParamType = Proto->getParamType(ArgIdx); 7348 Candidate.Conversions[ArgIdx + 1] 7349 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7350 /*SuppressUserConversions=*/false, 7351 /*InOverloadResolution=*/false, 7352 /*AllowObjCWritebackConversion=*/ 7353 getLangOpts().ObjCAutoRefCount); 7354 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7355 Candidate.Viable = false; 7356 Candidate.FailureKind = ovl_fail_bad_conversion; 7357 return; 7358 } 7359 } else { 7360 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7361 // argument for which there is no corresponding parameter is 7362 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7363 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7364 } 7365 } 7366 7367 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7368 Candidate.Viable = false; 7369 Candidate.FailureKind = ovl_fail_enable_if; 7370 Candidate.DeductionFailure.Data = FailedAttr; 7371 return; 7372 } 7373 } 7374 7375 /// Add all of the non-member operator function declarations in the given 7376 /// function set to the overload candidate set. 7377 void Sema::AddNonMemberOperatorCandidates( 7378 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7379 OverloadCandidateSet &CandidateSet, 7380 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7381 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7382 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7383 ArrayRef<Expr *> FunctionArgs = Args; 7384 7385 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7386 FunctionDecl *FD = 7387 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7388 7389 // Don't consider rewritten functions if we're not rewriting. 7390 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7391 continue; 7392 7393 assert(!isa<CXXMethodDecl>(FD) && 7394 "unqualified operator lookup found a member function"); 7395 7396 if (FunTmpl) { 7397 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7398 FunctionArgs, CandidateSet); 7399 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7400 AddTemplateOverloadCandidate( 7401 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7402 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7403 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7404 } else { 7405 if (ExplicitTemplateArgs) 7406 continue; 7407 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7408 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7409 AddOverloadCandidate(FD, F.getPair(), 7410 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7411 false, false, true, false, ADLCallKind::NotADL, 7412 None, OverloadCandidateParamOrder::Reversed); 7413 } 7414 } 7415 } 7416 7417 /// Add overload candidates for overloaded operators that are 7418 /// member functions. 7419 /// 7420 /// Add the overloaded operator candidates that are member functions 7421 /// for the operator Op that was used in an operator expression such 7422 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7423 /// CandidateSet will store the added overload candidates. (C++ 7424 /// [over.match.oper]). 7425 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7426 SourceLocation OpLoc, 7427 ArrayRef<Expr *> Args, 7428 OverloadCandidateSet &CandidateSet, 7429 OverloadCandidateParamOrder PO) { 7430 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7431 7432 // C++ [over.match.oper]p3: 7433 // For a unary operator @ with an operand of a type whose 7434 // cv-unqualified version is T1, and for a binary operator @ with 7435 // a left operand of a type whose cv-unqualified version is T1 and 7436 // a right operand of a type whose cv-unqualified version is T2, 7437 // three sets of candidate functions, designated member 7438 // candidates, non-member candidates and built-in candidates, are 7439 // constructed as follows: 7440 QualType T1 = Args[0]->getType(); 7441 7442 // -- If T1 is a complete class type or a class currently being 7443 // defined, the set of member candidates is the result of the 7444 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7445 // the set of member candidates is empty. 7446 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7447 // Complete the type if it can be completed. 7448 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7449 return; 7450 // If the type is neither complete nor being defined, bail out now. 7451 if (!T1Rec->getDecl()->getDefinition()) 7452 return; 7453 7454 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7455 LookupQualifiedName(Operators, T1Rec->getDecl()); 7456 Operators.suppressDiagnostics(); 7457 7458 for (LookupResult::iterator Oper = Operators.begin(), 7459 OperEnd = Operators.end(); 7460 Oper != OperEnd; 7461 ++Oper) 7462 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7463 Args[0]->Classify(Context), Args.slice(1), 7464 CandidateSet, /*SuppressUserConversion=*/false, PO); 7465 } 7466 } 7467 7468 /// AddBuiltinCandidate - Add a candidate for a built-in 7469 /// operator. ResultTy and ParamTys are the result and parameter types 7470 /// of the built-in candidate, respectively. Args and NumArgs are the 7471 /// arguments being passed to the candidate. IsAssignmentOperator 7472 /// should be true when this built-in candidate is an assignment 7473 /// operator. NumContextualBoolArguments is the number of arguments 7474 /// (at the beginning of the argument list) that will be contextually 7475 /// converted to bool. 7476 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7477 OverloadCandidateSet& CandidateSet, 7478 bool IsAssignmentOperator, 7479 unsigned NumContextualBoolArguments) { 7480 // Overload resolution is always an unevaluated context. 7481 EnterExpressionEvaluationContext Unevaluated( 7482 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7483 7484 // Add this candidate 7485 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7486 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7487 Candidate.Function = nullptr; 7488 Candidate.IsSurrogate = false; 7489 Candidate.IgnoreObjectArgument = false; 7490 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7491 7492 // Determine the implicit conversion sequences for each of the 7493 // arguments. 7494 Candidate.Viable = true; 7495 Candidate.ExplicitCallArguments = Args.size(); 7496 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7497 // C++ [over.match.oper]p4: 7498 // For the built-in assignment operators, conversions of the 7499 // left operand are restricted as follows: 7500 // -- no temporaries are introduced to hold the left operand, and 7501 // -- no user-defined conversions are applied to the left 7502 // operand to achieve a type match with the left-most 7503 // parameter of a built-in candidate. 7504 // 7505 // We block these conversions by turning off user-defined 7506 // conversions, since that is the only way that initialization of 7507 // a reference to a non-class type can occur from something that 7508 // is not of the same type. 7509 if (ArgIdx < NumContextualBoolArguments) { 7510 assert(ParamTys[ArgIdx] == Context.BoolTy && 7511 "Contextual conversion to bool requires bool type"); 7512 Candidate.Conversions[ArgIdx] 7513 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7514 } else { 7515 Candidate.Conversions[ArgIdx] 7516 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7517 ArgIdx == 0 && IsAssignmentOperator, 7518 /*InOverloadResolution=*/false, 7519 /*AllowObjCWritebackConversion=*/ 7520 getLangOpts().ObjCAutoRefCount); 7521 } 7522 if (Candidate.Conversions[ArgIdx].isBad()) { 7523 Candidate.Viable = false; 7524 Candidate.FailureKind = ovl_fail_bad_conversion; 7525 break; 7526 } 7527 } 7528 } 7529 7530 namespace { 7531 7532 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7533 /// candidate operator functions for built-in operators (C++ 7534 /// [over.built]). The types are separated into pointer types and 7535 /// enumeration types. 7536 class BuiltinCandidateTypeSet { 7537 /// TypeSet - A set of types. 7538 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7539 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7540 7541 /// PointerTypes - The set of pointer types that will be used in the 7542 /// built-in candidates. 7543 TypeSet PointerTypes; 7544 7545 /// MemberPointerTypes - The set of member pointer types that will be 7546 /// used in the built-in candidates. 7547 TypeSet MemberPointerTypes; 7548 7549 /// EnumerationTypes - The set of enumeration types that will be 7550 /// used in the built-in candidates. 7551 TypeSet EnumerationTypes; 7552 7553 /// The set of vector types that will be used in the built-in 7554 /// candidates. 7555 TypeSet VectorTypes; 7556 7557 /// A flag indicating non-record types are viable candidates 7558 bool HasNonRecordTypes; 7559 7560 /// A flag indicating whether either arithmetic or enumeration types 7561 /// were present in the candidate set. 7562 bool HasArithmeticOrEnumeralTypes; 7563 7564 /// A flag indicating whether the nullptr type was present in the 7565 /// candidate set. 7566 bool HasNullPtrType; 7567 7568 /// Sema - The semantic analysis instance where we are building the 7569 /// candidate type set. 7570 Sema &SemaRef; 7571 7572 /// Context - The AST context in which we will build the type sets. 7573 ASTContext &Context; 7574 7575 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7576 const Qualifiers &VisibleQuals); 7577 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7578 7579 public: 7580 /// iterator - Iterates through the types that are part of the set. 7581 typedef TypeSet::iterator iterator; 7582 7583 BuiltinCandidateTypeSet(Sema &SemaRef) 7584 : HasNonRecordTypes(false), 7585 HasArithmeticOrEnumeralTypes(false), 7586 HasNullPtrType(false), 7587 SemaRef(SemaRef), 7588 Context(SemaRef.Context) { } 7589 7590 void AddTypesConvertedFrom(QualType Ty, 7591 SourceLocation Loc, 7592 bool AllowUserConversions, 7593 bool AllowExplicitConversions, 7594 const Qualifiers &VisibleTypeConversionsQuals); 7595 7596 /// pointer_begin - First pointer type found; 7597 iterator pointer_begin() { return PointerTypes.begin(); } 7598 7599 /// pointer_end - Past the last pointer type found; 7600 iterator pointer_end() { return PointerTypes.end(); } 7601 7602 /// member_pointer_begin - First member pointer type found; 7603 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7604 7605 /// member_pointer_end - Past the last member pointer type found; 7606 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7607 7608 /// enumeration_begin - First enumeration type found; 7609 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7610 7611 /// enumeration_end - Past the last enumeration type found; 7612 iterator enumeration_end() { return EnumerationTypes.end(); } 7613 7614 iterator vector_begin() { return VectorTypes.begin(); } 7615 iterator vector_end() { return VectorTypes.end(); } 7616 7617 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7618 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7619 bool hasNullPtrType() const { return HasNullPtrType; } 7620 }; 7621 7622 } // end anonymous namespace 7623 7624 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7625 /// the set of pointer types along with any more-qualified variants of 7626 /// that type. For example, if @p Ty is "int const *", this routine 7627 /// will add "int const *", "int const volatile *", "int const 7628 /// restrict *", and "int const volatile restrict *" to the set of 7629 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7630 /// false otherwise. 7631 /// 7632 /// FIXME: what to do about extended qualifiers? 7633 bool 7634 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7635 const Qualifiers &VisibleQuals) { 7636 7637 // Insert this type. 7638 if (!PointerTypes.insert(Ty)) 7639 return false; 7640 7641 QualType PointeeTy; 7642 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7643 bool buildObjCPtr = false; 7644 if (!PointerTy) { 7645 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7646 PointeeTy = PTy->getPointeeType(); 7647 buildObjCPtr = true; 7648 } else { 7649 PointeeTy = PointerTy->getPointeeType(); 7650 } 7651 7652 // Don't add qualified variants of arrays. For one, they're not allowed 7653 // (the qualifier would sink to the element type), and for another, the 7654 // only overload situation where it matters is subscript or pointer +- int, 7655 // and those shouldn't have qualifier variants anyway. 7656 if (PointeeTy->isArrayType()) 7657 return true; 7658 7659 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7660 bool hasVolatile = VisibleQuals.hasVolatile(); 7661 bool hasRestrict = VisibleQuals.hasRestrict(); 7662 7663 // Iterate through all strict supersets of BaseCVR. 7664 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7665 if ((CVR | BaseCVR) != CVR) continue; 7666 // Skip over volatile if no volatile found anywhere in the types. 7667 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7668 7669 // Skip over restrict if no restrict found anywhere in the types, or if 7670 // the type cannot be restrict-qualified. 7671 if ((CVR & Qualifiers::Restrict) && 7672 (!hasRestrict || 7673 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7674 continue; 7675 7676 // Build qualified pointee type. 7677 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7678 7679 // Build qualified pointer type. 7680 QualType QPointerTy; 7681 if (!buildObjCPtr) 7682 QPointerTy = Context.getPointerType(QPointeeTy); 7683 else 7684 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7685 7686 // Insert qualified pointer type. 7687 PointerTypes.insert(QPointerTy); 7688 } 7689 7690 return true; 7691 } 7692 7693 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7694 /// to the set of pointer types along with any more-qualified variants of 7695 /// that type. For example, if @p Ty is "int const *", this routine 7696 /// will add "int const *", "int const volatile *", "int const 7697 /// restrict *", and "int const volatile restrict *" to the set of 7698 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7699 /// false otherwise. 7700 /// 7701 /// FIXME: what to do about extended qualifiers? 7702 bool 7703 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7704 QualType Ty) { 7705 // Insert this type. 7706 if (!MemberPointerTypes.insert(Ty)) 7707 return false; 7708 7709 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7710 assert(PointerTy && "type was not a member pointer type!"); 7711 7712 QualType PointeeTy = PointerTy->getPointeeType(); 7713 // Don't add qualified variants of arrays. For one, they're not allowed 7714 // (the qualifier would sink to the element type), and for another, the 7715 // only overload situation where it matters is subscript or pointer +- int, 7716 // and those shouldn't have qualifier variants anyway. 7717 if (PointeeTy->isArrayType()) 7718 return true; 7719 const Type *ClassTy = PointerTy->getClass(); 7720 7721 // Iterate through all strict supersets of the pointee type's CVR 7722 // qualifiers. 7723 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7724 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7725 if ((CVR | BaseCVR) != CVR) continue; 7726 7727 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7728 MemberPointerTypes.insert( 7729 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7730 } 7731 7732 return true; 7733 } 7734 7735 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7736 /// Ty can be implicit converted to the given set of @p Types. We're 7737 /// primarily interested in pointer types and enumeration types. We also 7738 /// take member pointer types, for the conditional operator. 7739 /// AllowUserConversions is true if we should look at the conversion 7740 /// functions of a class type, and AllowExplicitConversions if we 7741 /// should also include the explicit conversion functions of a class 7742 /// type. 7743 void 7744 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7745 SourceLocation Loc, 7746 bool AllowUserConversions, 7747 bool AllowExplicitConversions, 7748 const Qualifiers &VisibleQuals) { 7749 // Only deal with canonical types. 7750 Ty = Context.getCanonicalType(Ty); 7751 7752 // Look through reference types; they aren't part of the type of an 7753 // expression for the purposes of conversions. 7754 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7755 Ty = RefTy->getPointeeType(); 7756 7757 // If we're dealing with an array type, decay to the pointer. 7758 if (Ty->isArrayType()) 7759 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7760 7761 // Otherwise, we don't care about qualifiers on the type. 7762 Ty = Ty.getLocalUnqualifiedType(); 7763 7764 // Flag if we ever add a non-record type. 7765 const RecordType *TyRec = Ty->getAs<RecordType>(); 7766 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7767 7768 // Flag if we encounter an arithmetic type. 7769 HasArithmeticOrEnumeralTypes = 7770 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7771 7772 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7773 PointerTypes.insert(Ty); 7774 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7775 // Insert our type, and its more-qualified variants, into the set 7776 // of types. 7777 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7778 return; 7779 } else if (Ty->isMemberPointerType()) { 7780 // Member pointers are far easier, since the pointee can't be converted. 7781 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7782 return; 7783 } else if (Ty->isEnumeralType()) { 7784 HasArithmeticOrEnumeralTypes = true; 7785 EnumerationTypes.insert(Ty); 7786 } else if (Ty->isVectorType()) { 7787 // We treat vector types as arithmetic types in many contexts as an 7788 // extension. 7789 HasArithmeticOrEnumeralTypes = true; 7790 VectorTypes.insert(Ty); 7791 } else if (Ty->isNullPtrType()) { 7792 HasNullPtrType = true; 7793 } else if (AllowUserConversions && TyRec) { 7794 // No conversion functions in incomplete types. 7795 if (!SemaRef.isCompleteType(Loc, Ty)) 7796 return; 7797 7798 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7799 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7800 if (isa<UsingShadowDecl>(D)) 7801 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7802 7803 // Skip conversion function templates; they don't tell us anything 7804 // about which builtin types we can convert to. 7805 if (isa<FunctionTemplateDecl>(D)) 7806 continue; 7807 7808 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7809 if (AllowExplicitConversions || !Conv->isExplicit()) { 7810 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7811 VisibleQuals); 7812 } 7813 } 7814 } 7815 } 7816 /// Helper function for adjusting address spaces for the pointer or reference 7817 /// operands of builtin operators depending on the argument. 7818 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7819 Expr *Arg) { 7820 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7821 } 7822 7823 /// Helper function for AddBuiltinOperatorCandidates() that adds 7824 /// the volatile- and non-volatile-qualified assignment operators for the 7825 /// given type to the candidate set. 7826 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7827 QualType T, 7828 ArrayRef<Expr *> Args, 7829 OverloadCandidateSet &CandidateSet) { 7830 QualType ParamTypes[2]; 7831 7832 // T& operator=(T&, T) 7833 ParamTypes[0] = S.Context.getLValueReferenceType( 7834 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7835 ParamTypes[1] = T; 7836 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7837 /*IsAssignmentOperator=*/true); 7838 7839 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7840 // volatile T& operator=(volatile T&, T) 7841 ParamTypes[0] = S.Context.getLValueReferenceType( 7842 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7843 Args[0])); 7844 ParamTypes[1] = T; 7845 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7846 /*IsAssignmentOperator=*/true); 7847 } 7848 } 7849 7850 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7851 /// if any, found in visible type conversion functions found in ArgExpr's type. 7852 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7853 Qualifiers VRQuals; 7854 const RecordType *TyRec; 7855 if (const MemberPointerType *RHSMPType = 7856 ArgExpr->getType()->getAs<MemberPointerType>()) 7857 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7858 else 7859 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7860 if (!TyRec) { 7861 // Just to be safe, assume the worst case. 7862 VRQuals.addVolatile(); 7863 VRQuals.addRestrict(); 7864 return VRQuals; 7865 } 7866 7867 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7868 if (!ClassDecl->hasDefinition()) 7869 return VRQuals; 7870 7871 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7872 if (isa<UsingShadowDecl>(D)) 7873 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7874 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7875 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7876 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7877 CanTy = ResTypeRef->getPointeeType(); 7878 // Need to go down the pointer/mempointer chain and add qualifiers 7879 // as see them. 7880 bool done = false; 7881 while (!done) { 7882 if (CanTy.isRestrictQualified()) 7883 VRQuals.addRestrict(); 7884 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7885 CanTy = ResTypePtr->getPointeeType(); 7886 else if (const MemberPointerType *ResTypeMPtr = 7887 CanTy->getAs<MemberPointerType>()) 7888 CanTy = ResTypeMPtr->getPointeeType(); 7889 else 7890 done = true; 7891 if (CanTy.isVolatileQualified()) 7892 VRQuals.addVolatile(); 7893 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7894 return VRQuals; 7895 } 7896 } 7897 } 7898 return VRQuals; 7899 } 7900 7901 namespace { 7902 7903 /// Helper class to manage the addition of builtin operator overload 7904 /// candidates. It provides shared state and utility methods used throughout 7905 /// the process, as well as a helper method to add each group of builtin 7906 /// operator overloads from the standard to a candidate set. 7907 class BuiltinOperatorOverloadBuilder { 7908 // Common instance state available to all overload candidate addition methods. 7909 Sema &S; 7910 ArrayRef<Expr *> Args; 7911 Qualifiers VisibleTypeConversionsQuals; 7912 bool HasArithmeticOrEnumeralCandidateType; 7913 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7914 OverloadCandidateSet &CandidateSet; 7915 7916 static constexpr int ArithmeticTypesCap = 24; 7917 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7918 7919 // Define some indices used to iterate over the arithmetic types in 7920 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7921 // types are that preserved by promotion (C++ [over.built]p2). 7922 unsigned FirstIntegralType, 7923 LastIntegralType; 7924 unsigned FirstPromotedIntegralType, 7925 LastPromotedIntegralType; 7926 unsigned FirstPromotedArithmeticType, 7927 LastPromotedArithmeticType; 7928 unsigned NumArithmeticTypes; 7929 7930 void InitArithmeticTypes() { 7931 // Start of promoted types. 7932 FirstPromotedArithmeticType = 0; 7933 ArithmeticTypes.push_back(S.Context.FloatTy); 7934 ArithmeticTypes.push_back(S.Context.DoubleTy); 7935 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7936 if (S.Context.getTargetInfo().hasFloat128Type()) 7937 ArithmeticTypes.push_back(S.Context.Float128Ty); 7938 7939 // Start of integral types. 7940 FirstIntegralType = ArithmeticTypes.size(); 7941 FirstPromotedIntegralType = ArithmeticTypes.size(); 7942 ArithmeticTypes.push_back(S.Context.IntTy); 7943 ArithmeticTypes.push_back(S.Context.LongTy); 7944 ArithmeticTypes.push_back(S.Context.LongLongTy); 7945 if (S.Context.getTargetInfo().hasInt128Type()) 7946 ArithmeticTypes.push_back(S.Context.Int128Ty); 7947 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7948 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7949 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7950 if (S.Context.getTargetInfo().hasInt128Type()) 7951 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7952 LastPromotedIntegralType = ArithmeticTypes.size(); 7953 LastPromotedArithmeticType = ArithmeticTypes.size(); 7954 // End of promoted types. 7955 7956 ArithmeticTypes.push_back(S.Context.BoolTy); 7957 ArithmeticTypes.push_back(S.Context.CharTy); 7958 ArithmeticTypes.push_back(S.Context.WCharTy); 7959 if (S.Context.getLangOpts().Char8) 7960 ArithmeticTypes.push_back(S.Context.Char8Ty); 7961 ArithmeticTypes.push_back(S.Context.Char16Ty); 7962 ArithmeticTypes.push_back(S.Context.Char32Ty); 7963 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7964 ArithmeticTypes.push_back(S.Context.ShortTy); 7965 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7966 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7967 LastIntegralType = ArithmeticTypes.size(); 7968 NumArithmeticTypes = ArithmeticTypes.size(); 7969 // End of integral types. 7970 // FIXME: What about complex? What about half? 7971 7972 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7973 "Enough inline storage for all arithmetic types."); 7974 } 7975 7976 /// Helper method to factor out the common pattern of adding overloads 7977 /// for '++' and '--' builtin operators. 7978 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7979 bool HasVolatile, 7980 bool HasRestrict) { 7981 QualType ParamTypes[2] = { 7982 S.Context.getLValueReferenceType(CandidateTy), 7983 S.Context.IntTy 7984 }; 7985 7986 // Non-volatile version. 7987 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7988 7989 // Use a heuristic to reduce number of builtin candidates in the set: 7990 // add volatile version only if there are conversions to a volatile type. 7991 if (HasVolatile) { 7992 ParamTypes[0] = 7993 S.Context.getLValueReferenceType( 7994 S.Context.getVolatileType(CandidateTy)); 7995 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7996 } 7997 7998 // Add restrict version only if there are conversions to a restrict type 7999 // and our candidate type is a non-restrict-qualified pointer. 8000 if (HasRestrict && CandidateTy->isAnyPointerType() && 8001 !CandidateTy.isRestrictQualified()) { 8002 ParamTypes[0] 8003 = S.Context.getLValueReferenceType( 8004 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8005 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8006 8007 if (HasVolatile) { 8008 ParamTypes[0] 8009 = S.Context.getLValueReferenceType( 8010 S.Context.getCVRQualifiedType(CandidateTy, 8011 (Qualifiers::Volatile | 8012 Qualifiers::Restrict))); 8013 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8014 } 8015 } 8016 8017 } 8018 8019 public: 8020 BuiltinOperatorOverloadBuilder( 8021 Sema &S, ArrayRef<Expr *> Args, 8022 Qualifiers VisibleTypeConversionsQuals, 8023 bool HasArithmeticOrEnumeralCandidateType, 8024 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8025 OverloadCandidateSet &CandidateSet) 8026 : S(S), Args(Args), 8027 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8028 HasArithmeticOrEnumeralCandidateType( 8029 HasArithmeticOrEnumeralCandidateType), 8030 CandidateTypes(CandidateTypes), 8031 CandidateSet(CandidateSet) { 8032 8033 InitArithmeticTypes(); 8034 } 8035 8036 // Increment is deprecated for bool since C++17. 8037 // 8038 // C++ [over.built]p3: 8039 // 8040 // For every pair (T, VQ), where T is an arithmetic type other 8041 // than bool, and VQ is either volatile or empty, there exist 8042 // candidate operator functions of the form 8043 // 8044 // VQ T& operator++(VQ T&); 8045 // T operator++(VQ T&, int); 8046 // 8047 // C++ [over.built]p4: 8048 // 8049 // For every pair (T, VQ), where T is an arithmetic type other 8050 // than bool, and VQ is either volatile or empty, there exist 8051 // candidate operator functions of the form 8052 // 8053 // VQ T& operator--(VQ T&); 8054 // T operator--(VQ T&, int); 8055 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8056 if (!HasArithmeticOrEnumeralCandidateType) 8057 return; 8058 8059 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8060 const auto TypeOfT = ArithmeticTypes[Arith]; 8061 if (TypeOfT == S.Context.BoolTy) { 8062 if (Op == OO_MinusMinus) 8063 continue; 8064 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8065 continue; 8066 } 8067 addPlusPlusMinusMinusStyleOverloads( 8068 TypeOfT, 8069 VisibleTypeConversionsQuals.hasVolatile(), 8070 VisibleTypeConversionsQuals.hasRestrict()); 8071 } 8072 } 8073 8074 // C++ [over.built]p5: 8075 // 8076 // For every pair (T, VQ), where T is a cv-qualified or 8077 // cv-unqualified object type, and VQ is either volatile or 8078 // empty, there exist candidate operator functions of the form 8079 // 8080 // T*VQ& operator++(T*VQ&); 8081 // T*VQ& operator--(T*VQ&); 8082 // T* operator++(T*VQ&, int); 8083 // T* operator--(T*VQ&, int); 8084 void addPlusPlusMinusMinusPointerOverloads() { 8085 for (BuiltinCandidateTypeSet::iterator 8086 Ptr = CandidateTypes[0].pointer_begin(), 8087 PtrEnd = CandidateTypes[0].pointer_end(); 8088 Ptr != PtrEnd; ++Ptr) { 8089 // Skip pointer types that aren't pointers to object types. 8090 if (!(*Ptr)->getPointeeType()->isObjectType()) 8091 continue; 8092 8093 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8094 (!(*Ptr).isVolatileQualified() && 8095 VisibleTypeConversionsQuals.hasVolatile()), 8096 (!(*Ptr).isRestrictQualified() && 8097 VisibleTypeConversionsQuals.hasRestrict())); 8098 } 8099 } 8100 8101 // C++ [over.built]p6: 8102 // For every cv-qualified or cv-unqualified object type T, there 8103 // exist candidate operator functions of the form 8104 // 8105 // T& operator*(T*); 8106 // 8107 // C++ [over.built]p7: 8108 // For every function type T that does not have cv-qualifiers or a 8109 // ref-qualifier, there exist candidate operator functions of the form 8110 // T& operator*(T*); 8111 void addUnaryStarPointerOverloads() { 8112 for (BuiltinCandidateTypeSet::iterator 8113 Ptr = CandidateTypes[0].pointer_begin(), 8114 PtrEnd = CandidateTypes[0].pointer_end(); 8115 Ptr != PtrEnd; ++Ptr) { 8116 QualType ParamTy = *Ptr; 8117 QualType PointeeTy = ParamTy->getPointeeType(); 8118 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8119 continue; 8120 8121 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8122 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8123 continue; 8124 8125 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8126 } 8127 } 8128 8129 // C++ [over.built]p9: 8130 // For every promoted arithmetic type T, there exist candidate 8131 // operator functions of the form 8132 // 8133 // T operator+(T); 8134 // T operator-(T); 8135 void addUnaryPlusOrMinusArithmeticOverloads() { 8136 if (!HasArithmeticOrEnumeralCandidateType) 8137 return; 8138 8139 for (unsigned Arith = FirstPromotedArithmeticType; 8140 Arith < LastPromotedArithmeticType; ++Arith) { 8141 QualType ArithTy = ArithmeticTypes[Arith]; 8142 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8143 } 8144 8145 // Extension: We also add these operators for vector types. 8146 for (BuiltinCandidateTypeSet::iterator 8147 Vec = CandidateTypes[0].vector_begin(), 8148 VecEnd = CandidateTypes[0].vector_end(); 8149 Vec != VecEnd; ++Vec) { 8150 QualType VecTy = *Vec; 8151 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8152 } 8153 } 8154 8155 // C++ [over.built]p8: 8156 // For every type T, there exist candidate operator functions of 8157 // the form 8158 // 8159 // T* operator+(T*); 8160 void addUnaryPlusPointerOverloads() { 8161 for (BuiltinCandidateTypeSet::iterator 8162 Ptr = CandidateTypes[0].pointer_begin(), 8163 PtrEnd = CandidateTypes[0].pointer_end(); 8164 Ptr != PtrEnd; ++Ptr) { 8165 QualType ParamTy = *Ptr; 8166 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8167 } 8168 } 8169 8170 // C++ [over.built]p10: 8171 // For every promoted integral type T, there exist candidate 8172 // operator functions of the form 8173 // 8174 // T operator~(T); 8175 void addUnaryTildePromotedIntegralOverloads() { 8176 if (!HasArithmeticOrEnumeralCandidateType) 8177 return; 8178 8179 for (unsigned Int = FirstPromotedIntegralType; 8180 Int < LastPromotedIntegralType; ++Int) { 8181 QualType IntTy = ArithmeticTypes[Int]; 8182 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8183 } 8184 8185 // Extension: We also add this operator for vector types. 8186 for (BuiltinCandidateTypeSet::iterator 8187 Vec = CandidateTypes[0].vector_begin(), 8188 VecEnd = CandidateTypes[0].vector_end(); 8189 Vec != VecEnd; ++Vec) { 8190 QualType VecTy = *Vec; 8191 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8192 } 8193 } 8194 8195 // C++ [over.match.oper]p16: 8196 // For every pointer to member type T or type std::nullptr_t, there 8197 // exist candidate operator functions of the form 8198 // 8199 // bool operator==(T,T); 8200 // bool operator!=(T,T); 8201 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8202 /// Set of (canonical) types that we've already handled. 8203 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8204 8205 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8206 for (BuiltinCandidateTypeSet::iterator 8207 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8208 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8209 MemPtr != MemPtrEnd; 8210 ++MemPtr) { 8211 // Don't add the same builtin candidate twice. 8212 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8213 continue; 8214 8215 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8216 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8217 } 8218 8219 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8220 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8221 if (AddedTypes.insert(NullPtrTy).second) { 8222 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8223 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8224 } 8225 } 8226 } 8227 } 8228 8229 // C++ [over.built]p15: 8230 // 8231 // For every T, where T is an enumeration type or a pointer type, 8232 // there exist candidate operator functions of the form 8233 // 8234 // bool operator<(T, T); 8235 // bool operator>(T, T); 8236 // bool operator<=(T, T); 8237 // bool operator>=(T, T); 8238 // bool operator==(T, T); 8239 // bool operator!=(T, T); 8240 // R operator<=>(T, T) 8241 void addGenericBinaryPointerOrEnumeralOverloads() { 8242 // C++ [over.match.oper]p3: 8243 // [...]the built-in candidates include all of the candidate operator 8244 // functions defined in 13.6 that, compared to the given operator, [...] 8245 // do not have the same parameter-type-list as any non-template non-member 8246 // candidate. 8247 // 8248 // Note that in practice, this only affects enumeration types because there 8249 // aren't any built-in candidates of record type, and a user-defined operator 8250 // must have an operand of record or enumeration type. Also, the only other 8251 // overloaded operator with enumeration arguments, operator=, 8252 // cannot be overloaded for enumeration types, so this is the only place 8253 // where we must suppress candidates like this. 8254 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8255 UserDefinedBinaryOperators; 8256 8257 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8258 if (CandidateTypes[ArgIdx].enumeration_begin() != 8259 CandidateTypes[ArgIdx].enumeration_end()) { 8260 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8261 CEnd = CandidateSet.end(); 8262 C != CEnd; ++C) { 8263 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8264 continue; 8265 8266 if (C->Function->isFunctionTemplateSpecialization()) 8267 continue; 8268 8269 // We interpret "same parameter-type-list" as applying to the 8270 // "synthesized candidate, with the order of the two parameters 8271 // reversed", not to the original function. 8272 bool Reversed = C->RewriteKind & CRK_Reversed; 8273 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8274 ->getType() 8275 .getUnqualifiedType(); 8276 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8277 ->getType() 8278 .getUnqualifiedType(); 8279 8280 // Skip if either parameter isn't of enumeral type. 8281 if (!FirstParamType->isEnumeralType() || 8282 !SecondParamType->isEnumeralType()) 8283 continue; 8284 8285 // Add this operator to the set of known user-defined operators. 8286 UserDefinedBinaryOperators.insert( 8287 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8288 S.Context.getCanonicalType(SecondParamType))); 8289 } 8290 } 8291 } 8292 8293 /// Set of (canonical) types that we've already handled. 8294 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8295 8296 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8297 for (BuiltinCandidateTypeSet::iterator 8298 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8299 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8300 Ptr != PtrEnd; ++Ptr) { 8301 // Don't add the same builtin candidate twice. 8302 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8303 continue; 8304 8305 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8306 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8307 } 8308 for (BuiltinCandidateTypeSet::iterator 8309 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8310 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8311 Enum != EnumEnd; ++Enum) { 8312 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8313 8314 // Don't add the same builtin candidate twice, or if a user defined 8315 // candidate exists. 8316 if (!AddedTypes.insert(CanonType).second || 8317 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8318 CanonType))) 8319 continue; 8320 QualType ParamTypes[2] = { *Enum, *Enum }; 8321 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8322 } 8323 } 8324 } 8325 8326 // C++ [over.built]p13: 8327 // 8328 // For every cv-qualified or cv-unqualified object type T 8329 // there exist candidate operator functions of the form 8330 // 8331 // T* operator+(T*, ptrdiff_t); 8332 // T& operator[](T*, ptrdiff_t); [BELOW] 8333 // T* operator-(T*, ptrdiff_t); 8334 // T* operator+(ptrdiff_t, T*); 8335 // T& operator[](ptrdiff_t, T*); [BELOW] 8336 // 8337 // C++ [over.built]p14: 8338 // 8339 // For every T, where T is a pointer to object type, there 8340 // exist candidate operator functions of the form 8341 // 8342 // ptrdiff_t operator-(T, T); 8343 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8344 /// Set of (canonical) types that we've already handled. 8345 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8346 8347 for (int Arg = 0; Arg < 2; ++Arg) { 8348 QualType AsymmetricParamTypes[2] = { 8349 S.Context.getPointerDiffType(), 8350 S.Context.getPointerDiffType(), 8351 }; 8352 for (BuiltinCandidateTypeSet::iterator 8353 Ptr = CandidateTypes[Arg].pointer_begin(), 8354 PtrEnd = CandidateTypes[Arg].pointer_end(); 8355 Ptr != PtrEnd; ++Ptr) { 8356 QualType PointeeTy = (*Ptr)->getPointeeType(); 8357 if (!PointeeTy->isObjectType()) 8358 continue; 8359 8360 AsymmetricParamTypes[Arg] = *Ptr; 8361 if (Arg == 0 || Op == OO_Plus) { 8362 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8363 // T* operator+(ptrdiff_t, T*); 8364 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8365 } 8366 if (Op == OO_Minus) { 8367 // ptrdiff_t operator-(T, T); 8368 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8369 continue; 8370 8371 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8372 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8373 } 8374 } 8375 } 8376 } 8377 8378 // C++ [over.built]p12: 8379 // 8380 // For every pair of promoted arithmetic types L and R, there 8381 // exist candidate operator functions of the form 8382 // 8383 // LR operator*(L, R); 8384 // LR operator/(L, R); 8385 // LR operator+(L, R); 8386 // LR operator-(L, R); 8387 // bool operator<(L, R); 8388 // bool operator>(L, R); 8389 // bool operator<=(L, R); 8390 // bool operator>=(L, R); 8391 // bool operator==(L, R); 8392 // bool operator!=(L, R); 8393 // 8394 // where LR is the result of the usual arithmetic conversions 8395 // between types L and R. 8396 // 8397 // C++ [over.built]p24: 8398 // 8399 // For every pair of promoted arithmetic types L and R, there exist 8400 // candidate operator functions of the form 8401 // 8402 // LR operator?(bool, L, R); 8403 // 8404 // where LR is the result of the usual arithmetic conversions 8405 // between types L and R. 8406 // Our candidates ignore the first parameter. 8407 void addGenericBinaryArithmeticOverloads() { 8408 if (!HasArithmeticOrEnumeralCandidateType) 8409 return; 8410 8411 for (unsigned Left = FirstPromotedArithmeticType; 8412 Left < LastPromotedArithmeticType; ++Left) { 8413 for (unsigned Right = FirstPromotedArithmeticType; 8414 Right < LastPromotedArithmeticType; ++Right) { 8415 QualType LandR[2] = { ArithmeticTypes[Left], 8416 ArithmeticTypes[Right] }; 8417 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8418 } 8419 } 8420 8421 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8422 // conditional operator for vector types. 8423 for (BuiltinCandidateTypeSet::iterator 8424 Vec1 = CandidateTypes[0].vector_begin(), 8425 Vec1End = CandidateTypes[0].vector_end(); 8426 Vec1 != Vec1End; ++Vec1) { 8427 for (BuiltinCandidateTypeSet::iterator 8428 Vec2 = CandidateTypes[1].vector_begin(), 8429 Vec2End = CandidateTypes[1].vector_end(); 8430 Vec2 != Vec2End; ++Vec2) { 8431 QualType LandR[2] = { *Vec1, *Vec2 }; 8432 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8433 } 8434 } 8435 } 8436 8437 // C++2a [over.built]p14: 8438 // 8439 // For every integral type T there exists a candidate operator function 8440 // of the form 8441 // 8442 // std::strong_ordering operator<=>(T, T) 8443 // 8444 // C++2a [over.built]p15: 8445 // 8446 // For every pair of floating-point types L and R, there exists a candidate 8447 // operator function of the form 8448 // 8449 // std::partial_ordering operator<=>(L, R); 8450 // 8451 // FIXME: The current specification for integral types doesn't play nice with 8452 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8453 // comparisons. Under the current spec this can lead to ambiguity during 8454 // overload resolution. For example: 8455 // 8456 // enum A : int {a}; 8457 // auto x = (a <=> (long)42); 8458 // 8459 // error: call is ambiguous for arguments 'A' and 'long'. 8460 // note: candidate operator<=>(int, int) 8461 // note: candidate operator<=>(long, long) 8462 // 8463 // To avoid this error, this function deviates from the specification and adds 8464 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8465 // arithmetic types (the same as the generic relational overloads). 8466 // 8467 // For now this function acts as a placeholder. 8468 void addThreeWayArithmeticOverloads() { 8469 addGenericBinaryArithmeticOverloads(); 8470 } 8471 8472 // C++ [over.built]p17: 8473 // 8474 // For every pair of promoted integral types L and R, there 8475 // exist candidate operator functions of the form 8476 // 8477 // LR operator%(L, R); 8478 // LR operator&(L, R); 8479 // LR operator^(L, R); 8480 // LR operator|(L, R); 8481 // L operator<<(L, R); 8482 // L operator>>(L, R); 8483 // 8484 // where LR is the result of the usual arithmetic conversions 8485 // between types L and R. 8486 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8487 if (!HasArithmeticOrEnumeralCandidateType) 8488 return; 8489 8490 for (unsigned Left = FirstPromotedIntegralType; 8491 Left < LastPromotedIntegralType; ++Left) { 8492 for (unsigned Right = FirstPromotedIntegralType; 8493 Right < LastPromotedIntegralType; ++Right) { 8494 QualType LandR[2] = { ArithmeticTypes[Left], 8495 ArithmeticTypes[Right] }; 8496 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8497 } 8498 } 8499 } 8500 8501 // C++ [over.built]p20: 8502 // 8503 // For every pair (T, VQ), where T is an enumeration or 8504 // pointer to member type and VQ is either volatile or 8505 // empty, there exist candidate operator functions of the form 8506 // 8507 // VQ T& operator=(VQ T&, T); 8508 void addAssignmentMemberPointerOrEnumeralOverloads() { 8509 /// Set of (canonical) types that we've already handled. 8510 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8511 8512 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8513 for (BuiltinCandidateTypeSet::iterator 8514 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8515 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8516 Enum != EnumEnd; ++Enum) { 8517 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8518 continue; 8519 8520 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8521 } 8522 8523 for (BuiltinCandidateTypeSet::iterator 8524 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8525 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8526 MemPtr != MemPtrEnd; ++MemPtr) { 8527 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8528 continue; 8529 8530 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8531 } 8532 } 8533 } 8534 8535 // C++ [over.built]p19: 8536 // 8537 // For every pair (T, VQ), where T is any type and VQ is either 8538 // volatile or empty, there exist candidate operator functions 8539 // of the form 8540 // 8541 // T*VQ& operator=(T*VQ&, T*); 8542 // 8543 // C++ [over.built]p21: 8544 // 8545 // For every pair (T, VQ), where T is a cv-qualified or 8546 // cv-unqualified object type and VQ is either volatile or 8547 // empty, there exist candidate operator functions of the form 8548 // 8549 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8550 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8551 void addAssignmentPointerOverloads(bool isEqualOp) { 8552 /// Set of (canonical) types that we've already handled. 8553 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8554 8555 for (BuiltinCandidateTypeSet::iterator 8556 Ptr = CandidateTypes[0].pointer_begin(), 8557 PtrEnd = CandidateTypes[0].pointer_end(); 8558 Ptr != PtrEnd; ++Ptr) { 8559 // If this is operator=, keep track of the builtin candidates we added. 8560 if (isEqualOp) 8561 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8562 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8563 continue; 8564 8565 // non-volatile version 8566 QualType ParamTypes[2] = { 8567 S.Context.getLValueReferenceType(*Ptr), 8568 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8569 }; 8570 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8571 /*IsAssignmentOperator=*/ isEqualOp); 8572 8573 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8574 VisibleTypeConversionsQuals.hasVolatile(); 8575 if (NeedVolatile) { 8576 // volatile version 8577 ParamTypes[0] = 8578 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8579 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8580 /*IsAssignmentOperator=*/isEqualOp); 8581 } 8582 8583 if (!(*Ptr).isRestrictQualified() && 8584 VisibleTypeConversionsQuals.hasRestrict()) { 8585 // restrict version 8586 ParamTypes[0] 8587 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8588 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8589 /*IsAssignmentOperator=*/isEqualOp); 8590 8591 if (NeedVolatile) { 8592 // volatile restrict version 8593 ParamTypes[0] 8594 = S.Context.getLValueReferenceType( 8595 S.Context.getCVRQualifiedType(*Ptr, 8596 (Qualifiers::Volatile | 8597 Qualifiers::Restrict))); 8598 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8599 /*IsAssignmentOperator=*/isEqualOp); 8600 } 8601 } 8602 } 8603 8604 if (isEqualOp) { 8605 for (BuiltinCandidateTypeSet::iterator 8606 Ptr = CandidateTypes[1].pointer_begin(), 8607 PtrEnd = CandidateTypes[1].pointer_end(); 8608 Ptr != PtrEnd; ++Ptr) { 8609 // Make sure we don't add the same candidate twice. 8610 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8611 continue; 8612 8613 QualType ParamTypes[2] = { 8614 S.Context.getLValueReferenceType(*Ptr), 8615 *Ptr, 8616 }; 8617 8618 // non-volatile version 8619 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8620 /*IsAssignmentOperator=*/true); 8621 8622 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8623 VisibleTypeConversionsQuals.hasVolatile(); 8624 if (NeedVolatile) { 8625 // volatile version 8626 ParamTypes[0] = 8627 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8628 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8629 /*IsAssignmentOperator=*/true); 8630 } 8631 8632 if (!(*Ptr).isRestrictQualified() && 8633 VisibleTypeConversionsQuals.hasRestrict()) { 8634 // restrict version 8635 ParamTypes[0] 8636 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8637 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8638 /*IsAssignmentOperator=*/true); 8639 8640 if (NeedVolatile) { 8641 // volatile restrict version 8642 ParamTypes[0] 8643 = S.Context.getLValueReferenceType( 8644 S.Context.getCVRQualifiedType(*Ptr, 8645 (Qualifiers::Volatile | 8646 Qualifiers::Restrict))); 8647 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8648 /*IsAssignmentOperator=*/true); 8649 } 8650 } 8651 } 8652 } 8653 } 8654 8655 // C++ [over.built]p18: 8656 // 8657 // For every triple (L, VQ, R), where L is an arithmetic type, 8658 // VQ is either volatile or empty, and R is a promoted 8659 // arithmetic type, there exist candidate operator functions of 8660 // the form 8661 // 8662 // VQ L& operator=(VQ L&, R); 8663 // VQ L& operator*=(VQ L&, R); 8664 // VQ L& operator/=(VQ L&, R); 8665 // VQ L& operator+=(VQ L&, R); 8666 // VQ L& operator-=(VQ L&, R); 8667 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8668 if (!HasArithmeticOrEnumeralCandidateType) 8669 return; 8670 8671 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8672 for (unsigned Right = FirstPromotedArithmeticType; 8673 Right < LastPromotedArithmeticType; ++Right) { 8674 QualType ParamTypes[2]; 8675 ParamTypes[1] = ArithmeticTypes[Right]; 8676 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8677 S, ArithmeticTypes[Left], Args[0]); 8678 // Add this built-in operator as a candidate (VQ is empty). 8679 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8680 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8681 /*IsAssignmentOperator=*/isEqualOp); 8682 8683 // Add this built-in operator as a candidate (VQ is 'volatile'). 8684 if (VisibleTypeConversionsQuals.hasVolatile()) { 8685 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8686 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8687 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8688 /*IsAssignmentOperator=*/isEqualOp); 8689 } 8690 } 8691 } 8692 8693 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8694 for (BuiltinCandidateTypeSet::iterator 8695 Vec1 = CandidateTypes[0].vector_begin(), 8696 Vec1End = CandidateTypes[0].vector_end(); 8697 Vec1 != Vec1End; ++Vec1) { 8698 for (BuiltinCandidateTypeSet::iterator 8699 Vec2 = CandidateTypes[1].vector_begin(), 8700 Vec2End = CandidateTypes[1].vector_end(); 8701 Vec2 != Vec2End; ++Vec2) { 8702 QualType ParamTypes[2]; 8703 ParamTypes[1] = *Vec2; 8704 // Add this built-in operator as a candidate (VQ is empty). 8705 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8706 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8707 /*IsAssignmentOperator=*/isEqualOp); 8708 8709 // Add this built-in operator as a candidate (VQ is 'volatile'). 8710 if (VisibleTypeConversionsQuals.hasVolatile()) { 8711 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8712 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8713 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8714 /*IsAssignmentOperator=*/isEqualOp); 8715 } 8716 } 8717 } 8718 } 8719 8720 // C++ [over.built]p22: 8721 // 8722 // For every triple (L, VQ, R), where L is an integral type, VQ 8723 // is either volatile or empty, and R is a promoted integral 8724 // type, there exist candidate operator functions of the form 8725 // 8726 // VQ L& operator%=(VQ L&, R); 8727 // VQ L& operator<<=(VQ L&, R); 8728 // VQ L& operator>>=(VQ L&, R); 8729 // VQ L& operator&=(VQ L&, R); 8730 // VQ L& operator^=(VQ L&, R); 8731 // VQ L& operator|=(VQ L&, R); 8732 void addAssignmentIntegralOverloads() { 8733 if (!HasArithmeticOrEnumeralCandidateType) 8734 return; 8735 8736 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8737 for (unsigned Right = FirstPromotedIntegralType; 8738 Right < LastPromotedIntegralType; ++Right) { 8739 QualType ParamTypes[2]; 8740 ParamTypes[1] = ArithmeticTypes[Right]; 8741 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8742 S, ArithmeticTypes[Left], Args[0]); 8743 // Add this built-in operator as a candidate (VQ is empty). 8744 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8745 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8746 if (VisibleTypeConversionsQuals.hasVolatile()) { 8747 // Add this built-in operator as a candidate (VQ is 'volatile'). 8748 ParamTypes[0] = LeftBaseTy; 8749 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8750 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8751 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8752 } 8753 } 8754 } 8755 } 8756 8757 // C++ [over.operator]p23: 8758 // 8759 // There also exist candidate operator functions of the form 8760 // 8761 // bool operator!(bool); 8762 // bool operator&&(bool, bool); 8763 // bool operator||(bool, bool); 8764 void addExclaimOverload() { 8765 QualType ParamTy = S.Context.BoolTy; 8766 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8767 /*IsAssignmentOperator=*/false, 8768 /*NumContextualBoolArguments=*/1); 8769 } 8770 void addAmpAmpOrPipePipeOverload() { 8771 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8772 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8773 /*IsAssignmentOperator=*/false, 8774 /*NumContextualBoolArguments=*/2); 8775 } 8776 8777 // C++ [over.built]p13: 8778 // 8779 // For every cv-qualified or cv-unqualified object type T there 8780 // exist candidate operator functions of the form 8781 // 8782 // T* operator+(T*, ptrdiff_t); [ABOVE] 8783 // T& operator[](T*, ptrdiff_t); 8784 // T* operator-(T*, ptrdiff_t); [ABOVE] 8785 // T* operator+(ptrdiff_t, T*); [ABOVE] 8786 // T& operator[](ptrdiff_t, T*); 8787 void addSubscriptOverloads() { 8788 for (BuiltinCandidateTypeSet::iterator 8789 Ptr = CandidateTypes[0].pointer_begin(), 8790 PtrEnd = CandidateTypes[0].pointer_end(); 8791 Ptr != PtrEnd; ++Ptr) { 8792 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8793 QualType PointeeType = (*Ptr)->getPointeeType(); 8794 if (!PointeeType->isObjectType()) 8795 continue; 8796 8797 // T& operator[](T*, ptrdiff_t) 8798 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8799 } 8800 8801 for (BuiltinCandidateTypeSet::iterator 8802 Ptr = CandidateTypes[1].pointer_begin(), 8803 PtrEnd = CandidateTypes[1].pointer_end(); 8804 Ptr != PtrEnd; ++Ptr) { 8805 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8806 QualType PointeeType = (*Ptr)->getPointeeType(); 8807 if (!PointeeType->isObjectType()) 8808 continue; 8809 8810 // T& operator[](ptrdiff_t, T*) 8811 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8812 } 8813 } 8814 8815 // C++ [over.built]p11: 8816 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8817 // C1 is the same type as C2 or is a derived class of C2, T is an object 8818 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8819 // there exist candidate operator functions of the form 8820 // 8821 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8822 // 8823 // where CV12 is the union of CV1 and CV2. 8824 void addArrowStarOverloads() { 8825 for (BuiltinCandidateTypeSet::iterator 8826 Ptr = CandidateTypes[0].pointer_begin(), 8827 PtrEnd = CandidateTypes[0].pointer_end(); 8828 Ptr != PtrEnd; ++Ptr) { 8829 QualType C1Ty = (*Ptr); 8830 QualType C1; 8831 QualifierCollector Q1; 8832 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8833 if (!isa<RecordType>(C1)) 8834 continue; 8835 // heuristic to reduce number of builtin candidates in the set. 8836 // Add volatile/restrict version only if there are conversions to a 8837 // volatile/restrict type. 8838 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8839 continue; 8840 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8841 continue; 8842 for (BuiltinCandidateTypeSet::iterator 8843 MemPtr = CandidateTypes[1].member_pointer_begin(), 8844 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8845 MemPtr != MemPtrEnd; ++MemPtr) { 8846 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8847 QualType C2 = QualType(mptr->getClass(), 0); 8848 C2 = C2.getUnqualifiedType(); 8849 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8850 break; 8851 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8852 // build CV12 T& 8853 QualType T = mptr->getPointeeType(); 8854 if (!VisibleTypeConversionsQuals.hasVolatile() && 8855 T.isVolatileQualified()) 8856 continue; 8857 if (!VisibleTypeConversionsQuals.hasRestrict() && 8858 T.isRestrictQualified()) 8859 continue; 8860 T = Q1.apply(S.Context, T); 8861 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8862 } 8863 } 8864 } 8865 8866 // Note that we don't consider the first argument, since it has been 8867 // contextually converted to bool long ago. The candidates below are 8868 // therefore added as binary. 8869 // 8870 // C++ [over.built]p25: 8871 // For every type T, where T is a pointer, pointer-to-member, or scoped 8872 // enumeration type, there exist candidate operator functions of the form 8873 // 8874 // T operator?(bool, T, T); 8875 // 8876 void addConditionalOperatorOverloads() { 8877 /// Set of (canonical) types that we've already handled. 8878 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8879 8880 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8881 for (BuiltinCandidateTypeSet::iterator 8882 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8883 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8884 Ptr != PtrEnd; ++Ptr) { 8885 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8886 continue; 8887 8888 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8889 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8890 } 8891 8892 for (BuiltinCandidateTypeSet::iterator 8893 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8894 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8895 MemPtr != MemPtrEnd; ++MemPtr) { 8896 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8897 continue; 8898 8899 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8900 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8901 } 8902 8903 if (S.getLangOpts().CPlusPlus11) { 8904 for (BuiltinCandidateTypeSet::iterator 8905 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8906 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8907 Enum != EnumEnd; ++Enum) { 8908 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 8909 continue; 8910 8911 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8912 continue; 8913 8914 QualType ParamTypes[2] = { *Enum, *Enum }; 8915 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8916 } 8917 } 8918 } 8919 } 8920 }; 8921 8922 } // end anonymous namespace 8923 8924 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8925 /// operator overloads to the candidate set (C++ [over.built]), based 8926 /// on the operator @p Op and the arguments given. For example, if the 8927 /// operator is a binary '+', this routine might add "int 8928 /// operator+(int, int)" to cover integer addition. 8929 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8930 SourceLocation OpLoc, 8931 ArrayRef<Expr *> Args, 8932 OverloadCandidateSet &CandidateSet) { 8933 // Find all of the types that the arguments can convert to, but only 8934 // if the operator we're looking at has built-in operator candidates 8935 // that make use of these types. Also record whether we encounter non-record 8936 // candidate types or either arithmetic or enumeral candidate types. 8937 Qualifiers VisibleTypeConversionsQuals; 8938 VisibleTypeConversionsQuals.addConst(); 8939 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8940 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8941 8942 bool HasNonRecordCandidateType = false; 8943 bool HasArithmeticOrEnumeralCandidateType = false; 8944 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8945 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8946 CandidateTypes.emplace_back(*this); 8947 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8948 OpLoc, 8949 true, 8950 (Op == OO_Exclaim || 8951 Op == OO_AmpAmp || 8952 Op == OO_PipePipe), 8953 VisibleTypeConversionsQuals); 8954 HasNonRecordCandidateType = HasNonRecordCandidateType || 8955 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8956 HasArithmeticOrEnumeralCandidateType = 8957 HasArithmeticOrEnumeralCandidateType || 8958 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8959 } 8960 8961 // Exit early when no non-record types have been added to the candidate set 8962 // for any of the arguments to the operator. 8963 // 8964 // We can't exit early for !, ||, or &&, since there we have always have 8965 // 'bool' overloads. 8966 if (!HasNonRecordCandidateType && 8967 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8968 return; 8969 8970 // Setup an object to manage the common state for building overloads. 8971 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8972 VisibleTypeConversionsQuals, 8973 HasArithmeticOrEnumeralCandidateType, 8974 CandidateTypes, CandidateSet); 8975 8976 // Dispatch over the operation to add in only those overloads which apply. 8977 switch (Op) { 8978 case OO_None: 8979 case NUM_OVERLOADED_OPERATORS: 8980 llvm_unreachable("Expected an overloaded operator"); 8981 8982 case OO_New: 8983 case OO_Delete: 8984 case OO_Array_New: 8985 case OO_Array_Delete: 8986 case OO_Call: 8987 llvm_unreachable( 8988 "Special operators don't use AddBuiltinOperatorCandidates"); 8989 8990 case OO_Comma: 8991 case OO_Arrow: 8992 case OO_Coawait: 8993 // C++ [over.match.oper]p3: 8994 // -- For the operator ',', the unary operator '&', the 8995 // operator '->', or the operator 'co_await', the 8996 // built-in candidates set is empty. 8997 break; 8998 8999 case OO_Plus: // '+' is either unary or binary 9000 if (Args.size() == 1) 9001 OpBuilder.addUnaryPlusPointerOverloads(); 9002 LLVM_FALLTHROUGH; 9003 9004 case OO_Minus: // '-' is either unary or binary 9005 if (Args.size() == 1) { 9006 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9007 } else { 9008 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9009 OpBuilder.addGenericBinaryArithmeticOverloads(); 9010 } 9011 break; 9012 9013 case OO_Star: // '*' is either unary or binary 9014 if (Args.size() == 1) 9015 OpBuilder.addUnaryStarPointerOverloads(); 9016 else 9017 OpBuilder.addGenericBinaryArithmeticOverloads(); 9018 break; 9019 9020 case OO_Slash: 9021 OpBuilder.addGenericBinaryArithmeticOverloads(); 9022 break; 9023 9024 case OO_PlusPlus: 9025 case OO_MinusMinus: 9026 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9027 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9028 break; 9029 9030 case OO_EqualEqual: 9031 case OO_ExclaimEqual: 9032 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9033 LLVM_FALLTHROUGH; 9034 9035 case OO_Less: 9036 case OO_Greater: 9037 case OO_LessEqual: 9038 case OO_GreaterEqual: 9039 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9040 OpBuilder.addGenericBinaryArithmeticOverloads(); 9041 break; 9042 9043 case OO_Spaceship: 9044 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9045 OpBuilder.addThreeWayArithmeticOverloads(); 9046 break; 9047 9048 case OO_Percent: 9049 case OO_Caret: 9050 case OO_Pipe: 9051 case OO_LessLess: 9052 case OO_GreaterGreater: 9053 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9054 break; 9055 9056 case OO_Amp: // '&' is either unary or binary 9057 if (Args.size() == 1) 9058 // C++ [over.match.oper]p3: 9059 // -- For the operator ',', the unary operator '&', or the 9060 // operator '->', the built-in candidates set is empty. 9061 break; 9062 9063 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9064 break; 9065 9066 case OO_Tilde: 9067 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9068 break; 9069 9070 case OO_Equal: 9071 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9072 LLVM_FALLTHROUGH; 9073 9074 case OO_PlusEqual: 9075 case OO_MinusEqual: 9076 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9077 LLVM_FALLTHROUGH; 9078 9079 case OO_StarEqual: 9080 case OO_SlashEqual: 9081 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9082 break; 9083 9084 case OO_PercentEqual: 9085 case OO_LessLessEqual: 9086 case OO_GreaterGreaterEqual: 9087 case OO_AmpEqual: 9088 case OO_CaretEqual: 9089 case OO_PipeEqual: 9090 OpBuilder.addAssignmentIntegralOverloads(); 9091 break; 9092 9093 case OO_Exclaim: 9094 OpBuilder.addExclaimOverload(); 9095 break; 9096 9097 case OO_AmpAmp: 9098 case OO_PipePipe: 9099 OpBuilder.addAmpAmpOrPipePipeOverload(); 9100 break; 9101 9102 case OO_Subscript: 9103 OpBuilder.addSubscriptOverloads(); 9104 break; 9105 9106 case OO_ArrowStar: 9107 OpBuilder.addArrowStarOverloads(); 9108 break; 9109 9110 case OO_Conditional: 9111 OpBuilder.addConditionalOperatorOverloads(); 9112 OpBuilder.addGenericBinaryArithmeticOverloads(); 9113 break; 9114 } 9115 } 9116 9117 /// Add function candidates found via argument-dependent lookup 9118 /// to the set of overloading candidates. 9119 /// 9120 /// This routine performs argument-dependent name lookup based on the 9121 /// given function name (which may also be an operator name) and adds 9122 /// all of the overload candidates found by ADL to the overload 9123 /// candidate set (C++ [basic.lookup.argdep]). 9124 void 9125 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9126 SourceLocation Loc, 9127 ArrayRef<Expr *> Args, 9128 TemplateArgumentListInfo *ExplicitTemplateArgs, 9129 OverloadCandidateSet& CandidateSet, 9130 bool PartialOverloading) { 9131 ADLResult Fns; 9132 9133 // FIXME: This approach for uniquing ADL results (and removing 9134 // redundant candidates from the set) relies on pointer-equality, 9135 // which means we need to key off the canonical decl. However, 9136 // always going back to the canonical decl might not get us the 9137 // right set of default arguments. What default arguments are 9138 // we supposed to consider on ADL candidates, anyway? 9139 9140 // FIXME: Pass in the explicit template arguments? 9141 ArgumentDependentLookup(Name, Loc, Args, Fns); 9142 9143 // Erase all of the candidates we already knew about. 9144 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9145 CandEnd = CandidateSet.end(); 9146 Cand != CandEnd; ++Cand) 9147 if (Cand->Function) { 9148 Fns.erase(Cand->Function); 9149 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9150 Fns.erase(FunTmpl); 9151 } 9152 9153 // For each of the ADL candidates we found, add it to the overload 9154 // set. 9155 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9156 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9157 9158 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9159 if (ExplicitTemplateArgs) 9160 continue; 9161 9162 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9163 /*SuppressUserConversions=*/false, PartialOverloading, 9164 /*AllowExplicit*/ true, 9165 /*AllowExplicitConversions*/ false, 9166 ADLCallKind::UsesADL); 9167 } else { 9168 AddTemplateOverloadCandidate( 9169 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9170 CandidateSet, 9171 /*SuppressUserConversions=*/false, PartialOverloading, 9172 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9173 } 9174 } 9175 } 9176 9177 namespace { 9178 enum class Comparison { Equal, Better, Worse }; 9179 } 9180 9181 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9182 /// overload resolution. 9183 /// 9184 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9185 /// Cand1's first N enable_if attributes have precisely the same conditions as 9186 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9187 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9188 /// 9189 /// Note that you can have a pair of candidates such that Cand1's enable_if 9190 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9191 /// worse than Cand1's. 9192 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9193 const FunctionDecl *Cand2) { 9194 // Common case: One (or both) decls don't have enable_if attrs. 9195 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9196 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9197 if (!Cand1Attr || !Cand2Attr) { 9198 if (Cand1Attr == Cand2Attr) 9199 return Comparison::Equal; 9200 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9201 } 9202 9203 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9204 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9205 9206 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9207 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9208 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9209 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9210 9211 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9212 // has fewer enable_if attributes than Cand2, and vice versa. 9213 if (!Cand1A) 9214 return Comparison::Worse; 9215 if (!Cand2A) 9216 return Comparison::Better; 9217 9218 Cand1ID.clear(); 9219 Cand2ID.clear(); 9220 9221 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9222 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9223 if (Cand1ID != Cand2ID) 9224 return Comparison::Worse; 9225 } 9226 9227 return Comparison::Equal; 9228 } 9229 9230 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9231 const OverloadCandidate &Cand2) { 9232 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9233 !Cand2.Function->isMultiVersion()) 9234 return false; 9235 9236 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9237 // is obviously better. 9238 if (Cand1.Function->isInvalidDecl()) return false; 9239 if (Cand2.Function->isInvalidDecl()) return true; 9240 9241 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9242 // cpu_dispatch, else arbitrarily based on the identifiers. 9243 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9244 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9245 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9246 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9247 9248 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9249 return false; 9250 9251 if (Cand1CPUDisp && !Cand2CPUDisp) 9252 return true; 9253 if (Cand2CPUDisp && !Cand1CPUDisp) 9254 return false; 9255 9256 if (Cand1CPUSpec && Cand2CPUSpec) { 9257 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9258 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9259 9260 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9261 FirstDiff = std::mismatch( 9262 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9263 Cand2CPUSpec->cpus_begin(), 9264 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9265 return LHS->getName() == RHS->getName(); 9266 }); 9267 9268 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9269 "Two different cpu-specific versions should not have the same " 9270 "identifier list, otherwise they'd be the same decl!"); 9271 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9272 } 9273 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9274 } 9275 9276 /// isBetterOverloadCandidate - Determines whether the first overload 9277 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9278 bool clang::isBetterOverloadCandidate( 9279 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9280 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9281 // Define viable functions to be better candidates than non-viable 9282 // functions. 9283 if (!Cand2.Viable) 9284 return Cand1.Viable; 9285 else if (!Cand1.Viable) 9286 return false; 9287 9288 // C++ [over.match.best]p1: 9289 // 9290 // -- if F is a static member function, ICS1(F) is defined such 9291 // that ICS1(F) is neither better nor worse than ICS1(G) for 9292 // any function G, and, symmetrically, ICS1(G) is neither 9293 // better nor worse than ICS1(F). 9294 unsigned StartArg = 0; 9295 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9296 StartArg = 1; 9297 9298 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9299 // We don't allow incompatible pointer conversions in C++. 9300 if (!S.getLangOpts().CPlusPlus) 9301 return ICS.isStandard() && 9302 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9303 9304 // The only ill-formed conversion we allow in C++ is the string literal to 9305 // char* conversion, which is only considered ill-formed after C++11. 9306 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9307 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9308 }; 9309 9310 // Define functions that don't require ill-formed conversions for a given 9311 // argument to be better candidates than functions that do. 9312 unsigned NumArgs = Cand1.Conversions.size(); 9313 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9314 bool HasBetterConversion = false; 9315 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9316 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9317 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9318 if (Cand1Bad != Cand2Bad) { 9319 if (Cand1Bad) 9320 return false; 9321 HasBetterConversion = true; 9322 } 9323 } 9324 9325 if (HasBetterConversion) 9326 return true; 9327 9328 // C++ [over.match.best]p1: 9329 // A viable function F1 is defined to be a better function than another 9330 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9331 // conversion sequence than ICSi(F2), and then... 9332 bool HasWorseConversion = false; 9333 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9334 switch (CompareImplicitConversionSequences(S, Loc, 9335 Cand1.Conversions[ArgIdx], 9336 Cand2.Conversions[ArgIdx])) { 9337 case ImplicitConversionSequence::Better: 9338 // Cand1 has a better conversion sequence. 9339 HasBetterConversion = true; 9340 break; 9341 9342 case ImplicitConversionSequence::Worse: 9343 if (Cand1.Function && Cand1.Function == Cand2.Function && 9344 (Cand2.RewriteKind & CRK_Reversed) != 0) { 9345 // Work around large-scale breakage caused by considering reversed 9346 // forms of operator== in C++20: 9347 // 9348 // When comparing a function against its reversed form, if we have a 9349 // better conversion for one argument and a worse conversion for the 9350 // other, we prefer the non-reversed form. 9351 // 9352 // This prevents a conversion function from being considered ambiguous 9353 // with its own reversed form in various where it's only incidentally 9354 // heterogeneous. 9355 // 9356 // We diagnose this as an extension from CreateOverloadedBinOp. 9357 HasWorseConversion = true; 9358 break; 9359 } 9360 9361 // Cand1 can't be better than Cand2. 9362 return false; 9363 9364 case ImplicitConversionSequence::Indistinguishable: 9365 // Do nothing. 9366 break; 9367 } 9368 } 9369 9370 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9371 // ICSj(F2), or, if not that, 9372 if (HasBetterConversion) 9373 return true; 9374 if (HasWorseConversion) 9375 return false; 9376 9377 // -- the context is an initialization by user-defined conversion 9378 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9379 // from the return type of F1 to the destination type (i.e., 9380 // the type of the entity being initialized) is a better 9381 // conversion sequence than the standard conversion sequence 9382 // from the return type of F2 to the destination type. 9383 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9384 Cand1.Function && Cand2.Function && 9385 isa<CXXConversionDecl>(Cand1.Function) && 9386 isa<CXXConversionDecl>(Cand2.Function)) { 9387 // First check whether we prefer one of the conversion functions over the 9388 // other. This only distinguishes the results in non-standard, extension 9389 // cases such as the conversion from a lambda closure type to a function 9390 // pointer or block. 9391 ImplicitConversionSequence::CompareKind Result = 9392 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9393 if (Result == ImplicitConversionSequence::Indistinguishable) 9394 Result = CompareStandardConversionSequences(S, Loc, 9395 Cand1.FinalConversion, 9396 Cand2.FinalConversion); 9397 9398 if (Result != ImplicitConversionSequence::Indistinguishable) 9399 return Result == ImplicitConversionSequence::Better; 9400 9401 // FIXME: Compare kind of reference binding if conversion functions 9402 // convert to a reference type used in direct reference binding, per 9403 // C++14 [over.match.best]p1 section 2 bullet 3. 9404 } 9405 9406 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9407 // as combined with the resolution to CWG issue 243. 9408 // 9409 // When the context is initialization by constructor ([over.match.ctor] or 9410 // either phase of [over.match.list]), a constructor is preferred over 9411 // a conversion function. 9412 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9413 Cand1.Function && Cand2.Function && 9414 isa<CXXConstructorDecl>(Cand1.Function) != 9415 isa<CXXConstructorDecl>(Cand2.Function)) 9416 return isa<CXXConstructorDecl>(Cand1.Function); 9417 9418 // -- F1 is a non-template function and F2 is a function template 9419 // specialization, or, if not that, 9420 bool Cand1IsSpecialization = Cand1.Function && 9421 Cand1.Function->getPrimaryTemplate(); 9422 bool Cand2IsSpecialization = Cand2.Function && 9423 Cand2.Function->getPrimaryTemplate(); 9424 if (Cand1IsSpecialization != Cand2IsSpecialization) 9425 return Cand2IsSpecialization; 9426 9427 // -- F1 and F2 are function template specializations, and the function 9428 // template for F1 is more specialized than the template for F2 9429 // according to the partial ordering rules described in 14.5.5.2, or, 9430 // if not that, 9431 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9432 if (FunctionTemplateDecl *BetterTemplate 9433 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9434 Cand2.Function->getPrimaryTemplate(), 9435 Loc, 9436 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9437 : TPOC_Call, 9438 Cand1.ExplicitCallArguments, 9439 Cand2.ExplicitCallArguments)) 9440 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9441 } 9442 9443 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9444 // class B of D, and for all arguments the corresponding parameters of 9445 // F1 and F2 have the same type. 9446 // FIXME: Implement the "all parameters have the same type" check. 9447 bool Cand1IsInherited = 9448 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9449 bool Cand2IsInherited = 9450 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9451 if (Cand1IsInherited != Cand2IsInherited) 9452 return Cand2IsInherited; 9453 else if (Cand1IsInherited) { 9454 assert(Cand2IsInherited); 9455 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9456 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9457 if (Cand1Class->isDerivedFrom(Cand2Class)) 9458 return true; 9459 if (Cand2Class->isDerivedFrom(Cand1Class)) 9460 return false; 9461 // Inherited from sibling base classes: still ambiguous. 9462 } 9463 9464 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9465 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9466 // with reversed order of parameters and F1 is not 9467 // 9468 // We rank reversed + different operator as worse than just reversed, but 9469 // that comparison can never happen, because we only consider reversing for 9470 // the maximally-rewritten operator (== or <=>). 9471 if (Cand1.RewriteKind != Cand2.RewriteKind) 9472 return Cand1.RewriteKind < Cand2.RewriteKind; 9473 9474 // Check C++17 tie-breakers for deduction guides. 9475 { 9476 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9477 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9478 if (Guide1 && Guide2) { 9479 // -- F1 is generated from a deduction-guide and F2 is not 9480 if (Guide1->isImplicit() != Guide2->isImplicit()) 9481 return Guide2->isImplicit(); 9482 9483 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9484 if (Guide1->isCopyDeductionCandidate()) 9485 return true; 9486 } 9487 } 9488 9489 // Check for enable_if value-based overload resolution. 9490 if (Cand1.Function && Cand2.Function) { 9491 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9492 if (Cmp != Comparison::Equal) 9493 return Cmp == Comparison::Better; 9494 } 9495 9496 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9497 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9498 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9499 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9500 } 9501 9502 bool HasPS1 = Cand1.Function != nullptr && 9503 functionHasPassObjectSizeParams(Cand1.Function); 9504 bool HasPS2 = Cand2.Function != nullptr && 9505 functionHasPassObjectSizeParams(Cand2.Function); 9506 if (HasPS1 != HasPS2 && HasPS1) 9507 return true; 9508 9509 return isBetterMultiversionCandidate(Cand1, Cand2); 9510 } 9511 9512 /// Determine whether two declarations are "equivalent" for the purposes of 9513 /// name lookup and overload resolution. This applies when the same internal/no 9514 /// linkage entity is defined by two modules (probably by textually including 9515 /// the same header). In such a case, we don't consider the declarations to 9516 /// declare the same entity, but we also don't want lookups with both 9517 /// declarations visible to be ambiguous in some cases (this happens when using 9518 /// a modularized libstdc++). 9519 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9520 const NamedDecl *B) { 9521 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9522 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9523 if (!VA || !VB) 9524 return false; 9525 9526 // The declarations must be declaring the same name as an internal linkage 9527 // entity in different modules. 9528 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9529 VB->getDeclContext()->getRedeclContext()) || 9530 getOwningModule(const_cast<ValueDecl *>(VA)) == 9531 getOwningModule(const_cast<ValueDecl *>(VB)) || 9532 VA->isExternallyVisible() || VB->isExternallyVisible()) 9533 return false; 9534 9535 // Check that the declarations appear to be equivalent. 9536 // 9537 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9538 // For constants and functions, we should check the initializer or body is 9539 // the same. For non-constant variables, we shouldn't allow it at all. 9540 if (Context.hasSameType(VA->getType(), VB->getType())) 9541 return true; 9542 9543 // Enum constants within unnamed enumerations will have different types, but 9544 // may still be similar enough to be interchangeable for our purposes. 9545 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9546 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9547 // Only handle anonymous enums. If the enumerations were named and 9548 // equivalent, they would have been merged to the same type. 9549 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9550 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9551 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9552 !Context.hasSameType(EnumA->getIntegerType(), 9553 EnumB->getIntegerType())) 9554 return false; 9555 // Allow this only if the value is the same for both enumerators. 9556 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9557 } 9558 } 9559 9560 // Nothing else is sufficiently similar. 9561 return false; 9562 } 9563 9564 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9565 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9566 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9567 9568 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9569 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9570 << !M << (M ? M->getFullModuleName() : ""); 9571 9572 for (auto *E : Equiv) { 9573 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9574 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9575 << !M << (M ? M->getFullModuleName() : ""); 9576 } 9577 } 9578 9579 /// Computes the best viable function (C++ 13.3.3) 9580 /// within an overload candidate set. 9581 /// 9582 /// \param Loc The location of the function name (or operator symbol) for 9583 /// which overload resolution occurs. 9584 /// 9585 /// \param Best If overload resolution was successful or found a deleted 9586 /// function, \p Best points to the candidate function found. 9587 /// 9588 /// \returns The result of overload resolution. 9589 OverloadingResult 9590 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9591 iterator &Best) { 9592 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9593 std::transform(begin(), end(), std::back_inserter(Candidates), 9594 [](OverloadCandidate &Cand) { return &Cand; }); 9595 9596 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9597 // are accepted by both clang and NVCC. However, during a particular 9598 // compilation mode only one call variant is viable. We need to 9599 // exclude non-viable overload candidates from consideration based 9600 // only on their host/device attributes. Specifically, if one 9601 // candidate call is WrongSide and the other is SameSide, we ignore 9602 // the WrongSide candidate. 9603 if (S.getLangOpts().CUDA) { 9604 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9605 bool ContainsSameSideCandidate = 9606 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9607 // Check viable function only. 9608 return Cand->Viable && Cand->Function && 9609 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9610 Sema::CFP_SameSide; 9611 }); 9612 if (ContainsSameSideCandidate) { 9613 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9614 // Check viable function only to avoid unnecessary data copying/moving. 9615 return Cand->Viable && Cand->Function && 9616 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9617 Sema::CFP_WrongSide; 9618 }; 9619 llvm::erase_if(Candidates, IsWrongSideCandidate); 9620 } 9621 } 9622 9623 // Find the best viable function. 9624 Best = end(); 9625 for (auto *Cand : Candidates) 9626 if (Cand->Viable) 9627 if (Best == end() || 9628 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9629 Best = Cand; 9630 9631 // If we didn't find any viable functions, abort. 9632 if (Best == end()) 9633 return OR_No_Viable_Function; 9634 9635 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9636 9637 // Make sure that this function is better than every other viable 9638 // function. If not, we have an ambiguity. 9639 for (auto *Cand : Candidates) { 9640 if (Cand->Viable && Cand != Best && 9641 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9642 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9643 Cand->Function)) { 9644 EquivalentCands.push_back(Cand->Function); 9645 continue; 9646 } 9647 9648 Best = end(); 9649 return OR_Ambiguous; 9650 } 9651 } 9652 9653 // Best is the best viable function. 9654 if (Best->Function && Best->Function->isDeleted()) 9655 return OR_Deleted; 9656 9657 if (!EquivalentCands.empty()) 9658 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9659 EquivalentCands); 9660 9661 return OR_Success; 9662 } 9663 9664 namespace { 9665 9666 enum OverloadCandidateKind { 9667 oc_function, 9668 oc_method, 9669 oc_reversed_binary_operator, 9670 oc_constructor, 9671 oc_implicit_default_constructor, 9672 oc_implicit_copy_constructor, 9673 oc_implicit_move_constructor, 9674 oc_implicit_copy_assignment, 9675 oc_implicit_move_assignment, 9676 oc_inherited_constructor 9677 }; 9678 9679 enum OverloadCandidateSelect { 9680 ocs_non_template, 9681 ocs_template, 9682 ocs_described_template, 9683 }; 9684 9685 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9686 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9687 OverloadCandidateRewriteKind CRK, 9688 std::string &Description) { 9689 9690 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9691 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9692 isTemplate = true; 9693 Description = S.getTemplateArgumentBindingsText( 9694 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9695 } 9696 9697 OverloadCandidateSelect Select = [&]() { 9698 if (!Description.empty()) 9699 return ocs_described_template; 9700 return isTemplate ? ocs_template : ocs_non_template; 9701 }(); 9702 9703 OverloadCandidateKind Kind = [&]() { 9704 if (CRK & CRK_Reversed) 9705 return oc_reversed_binary_operator; 9706 9707 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9708 if (!Ctor->isImplicit()) { 9709 if (isa<ConstructorUsingShadowDecl>(Found)) 9710 return oc_inherited_constructor; 9711 else 9712 return oc_constructor; 9713 } 9714 9715 if (Ctor->isDefaultConstructor()) 9716 return oc_implicit_default_constructor; 9717 9718 if (Ctor->isMoveConstructor()) 9719 return oc_implicit_move_constructor; 9720 9721 assert(Ctor->isCopyConstructor() && 9722 "unexpected sort of implicit constructor"); 9723 return oc_implicit_copy_constructor; 9724 } 9725 9726 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9727 // This actually gets spelled 'candidate function' for now, but 9728 // it doesn't hurt to split it out. 9729 if (!Meth->isImplicit()) 9730 return oc_method; 9731 9732 if (Meth->isMoveAssignmentOperator()) 9733 return oc_implicit_move_assignment; 9734 9735 if (Meth->isCopyAssignmentOperator()) 9736 return oc_implicit_copy_assignment; 9737 9738 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9739 return oc_method; 9740 } 9741 9742 return oc_function; 9743 }(); 9744 9745 return std::make_pair(Kind, Select); 9746 } 9747 9748 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9749 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9750 // set. 9751 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9752 S.Diag(FoundDecl->getLocation(), 9753 diag::note_ovl_candidate_inherited_constructor) 9754 << Shadow->getNominatedBaseClass(); 9755 } 9756 9757 } // end anonymous namespace 9758 9759 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9760 const FunctionDecl *FD) { 9761 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9762 bool AlwaysTrue; 9763 if (EnableIf->getCond()->isValueDependent() || 9764 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9765 return false; 9766 if (!AlwaysTrue) 9767 return false; 9768 } 9769 return true; 9770 } 9771 9772 /// Returns true if we can take the address of the function. 9773 /// 9774 /// \param Complain - If true, we'll emit a diagnostic 9775 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9776 /// we in overload resolution? 9777 /// \param Loc - The location of the statement we're complaining about. Ignored 9778 /// if we're not complaining, or if we're in overload resolution. 9779 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9780 bool Complain, 9781 bool InOverloadResolution, 9782 SourceLocation Loc) { 9783 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9784 if (Complain) { 9785 if (InOverloadResolution) 9786 S.Diag(FD->getBeginLoc(), 9787 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9788 else 9789 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9790 } 9791 return false; 9792 } 9793 9794 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9795 return P->hasAttr<PassObjectSizeAttr>(); 9796 }); 9797 if (I == FD->param_end()) 9798 return true; 9799 9800 if (Complain) { 9801 // Add one to ParamNo because it's user-facing 9802 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9803 if (InOverloadResolution) 9804 S.Diag(FD->getLocation(), 9805 diag::note_ovl_candidate_has_pass_object_size_params) 9806 << ParamNo; 9807 else 9808 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9809 << FD << ParamNo; 9810 } 9811 return false; 9812 } 9813 9814 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9815 const FunctionDecl *FD) { 9816 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9817 /*InOverloadResolution=*/true, 9818 /*Loc=*/SourceLocation()); 9819 } 9820 9821 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9822 bool Complain, 9823 SourceLocation Loc) { 9824 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9825 /*InOverloadResolution=*/false, 9826 Loc); 9827 } 9828 9829 // Notes the location of an overload candidate. 9830 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9831 OverloadCandidateRewriteKind RewriteKind, 9832 QualType DestType, bool TakingAddress) { 9833 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9834 return; 9835 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9836 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9837 return; 9838 9839 std::string FnDesc; 9840 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9841 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 9842 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9843 << (unsigned)KSPair.first << (unsigned)KSPair.second 9844 << Fn << FnDesc; 9845 9846 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9847 Diag(Fn->getLocation(), PD); 9848 MaybeEmitInheritedConstructorNote(*this, Found); 9849 } 9850 9851 // Notes the location of all overload candidates designated through 9852 // OverloadedExpr 9853 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9854 bool TakingAddress) { 9855 assert(OverloadedExpr->getType() == Context.OverloadTy); 9856 9857 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9858 OverloadExpr *OvlExpr = Ovl.Expression; 9859 9860 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9861 IEnd = OvlExpr->decls_end(); 9862 I != IEnd; ++I) { 9863 if (FunctionTemplateDecl *FunTmpl = 9864 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9865 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 9866 TakingAddress); 9867 } else if (FunctionDecl *Fun 9868 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9869 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 9870 } 9871 } 9872 } 9873 9874 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9875 /// "lead" diagnostic; it will be given two arguments, the source and 9876 /// target types of the conversion. 9877 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9878 Sema &S, 9879 SourceLocation CaretLoc, 9880 const PartialDiagnostic &PDiag) const { 9881 S.Diag(CaretLoc, PDiag) 9882 << Ambiguous.getFromType() << Ambiguous.getToType(); 9883 // FIXME: The note limiting machinery is borrowed from 9884 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9885 // refactoring here. 9886 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9887 unsigned CandsShown = 0; 9888 AmbiguousConversionSequence::const_iterator I, E; 9889 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9890 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9891 break; 9892 ++CandsShown; 9893 S.NoteOverloadCandidate(I->first, I->second); 9894 } 9895 if (I != E) 9896 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9897 } 9898 9899 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9900 unsigned I, bool TakingCandidateAddress) { 9901 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9902 assert(Conv.isBad()); 9903 assert(Cand->Function && "for now, candidate must be a function"); 9904 FunctionDecl *Fn = Cand->Function; 9905 9906 // There's a conversion slot for the object argument if this is a 9907 // non-constructor method. Note that 'I' corresponds the 9908 // conversion-slot index. 9909 bool isObjectArgument = false; 9910 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9911 if (I == 0) 9912 isObjectArgument = true; 9913 else 9914 I--; 9915 } 9916 9917 std::string FnDesc; 9918 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9919 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->RewriteKind, 9920 FnDesc); 9921 9922 Expr *FromExpr = Conv.Bad.FromExpr; 9923 QualType FromTy = Conv.Bad.getFromType(); 9924 QualType ToTy = Conv.Bad.getToType(); 9925 9926 if (FromTy == S.Context.OverloadTy) { 9927 assert(FromExpr && "overload set argument came from implicit argument?"); 9928 Expr *E = FromExpr->IgnoreParens(); 9929 if (isa<UnaryOperator>(E)) 9930 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9931 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9932 9933 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9934 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9935 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9936 << Name << I + 1; 9937 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9938 return; 9939 } 9940 9941 // Do some hand-waving analysis to see if the non-viability is due 9942 // to a qualifier mismatch. 9943 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9944 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9945 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9946 CToTy = RT->getPointeeType(); 9947 else { 9948 // TODO: detect and diagnose the full richness of const mismatches. 9949 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9950 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9951 CFromTy = FromPT->getPointeeType(); 9952 CToTy = ToPT->getPointeeType(); 9953 } 9954 } 9955 9956 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9957 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9958 Qualifiers FromQs = CFromTy.getQualifiers(); 9959 Qualifiers ToQs = CToTy.getQualifiers(); 9960 9961 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9962 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9963 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9964 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9965 << ToTy << (unsigned)isObjectArgument << I + 1; 9966 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9967 return; 9968 } 9969 9970 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9971 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9972 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9973 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9974 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9975 << (unsigned)isObjectArgument << I + 1; 9976 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9977 return; 9978 } 9979 9980 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9981 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9982 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9983 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9984 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9985 << (unsigned)isObjectArgument << I + 1; 9986 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9987 return; 9988 } 9989 9990 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9991 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9992 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9993 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9994 << FromQs.hasUnaligned() << I + 1; 9995 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9996 return; 9997 } 9998 9999 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10000 assert(CVR && "unexpected qualifiers mismatch"); 10001 10002 if (isObjectArgument) { 10003 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10004 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10005 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10006 << (CVR - 1); 10007 } else { 10008 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10009 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10010 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10011 << (CVR - 1) << I + 1; 10012 } 10013 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10014 return; 10015 } 10016 10017 // Special diagnostic for failure to convert an initializer list, since 10018 // telling the user that it has type void is not useful. 10019 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10020 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10021 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10022 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10023 << ToTy << (unsigned)isObjectArgument << I + 1; 10024 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10025 return; 10026 } 10027 10028 // Diagnose references or pointers to incomplete types differently, 10029 // since it's far from impossible that the incompleteness triggered 10030 // the failure. 10031 QualType TempFromTy = FromTy.getNonReferenceType(); 10032 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10033 TempFromTy = PTy->getPointeeType(); 10034 if (TempFromTy->isIncompleteType()) { 10035 // Emit the generic diagnostic and, optionally, add the hints to it. 10036 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10037 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10038 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10039 << ToTy << (unsigned)isObjectArgument << I + 1 10040 << (unsigned)(Cand->Fix.Kind); 10041 10042 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10043 return; 10044 } 10045 10046 // Diagnose base -> derived pointer conversions. 10047 unsigned BaseToDerivedConversion = 0; 10048 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10049 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10050 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10051 FromPtrTy->getPointeeType()) && 10052 !FromPtrTy->getPointeeType()->isIncompleteType() && 10053 !ToPtrTy->getPointeeType()->isIncompleteType() && 10054 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10055 FromPtrTy->getPointeeType())) 10056 BaseToDerivedConversion = 1; 10057 } 10058 } else if (const ObjCObjectPointerType *FromPtrTy 10059 = FromTy->getAs<ObjCObjectPointerType>()) { 10060 if (const ObjCObjectPointerType *ToPtrTy 10061 = ToTy->getAs<ObjCObjectPointerType>()) 10062 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10063 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10064 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10065 FromPtrTy->getPointeeType()) && 10066 FromIface->isSuperClassOf(ToIface)) 10067 BaseToDerivedConversion = 2; 10068 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10069 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10070 !FromTy->isIncompleteType() && 10071 !ToRefTy->getPointeeType()->isIncompleteType() && 10072 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10073 BaseToDerivedConversion = 3; 10074 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10075 ToTy.getNonReferenceType().getCanonicalType() == 10076 FromTy.getNonReferenceType().getCanonicalType()) { 10077 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10078 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10079 << (unsigned)isObjectArgument << I + 1 10080 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10081 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10082 return; 10083 } 10084 } 10085 10086 if (BaseToDerivedConversion) { 10087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10088 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10089 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10090 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10091 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10092 return; 10093 } 10094 10095 if (isa<ObjCObjectPointerType>(CFromTy) && 10096 isa<PointerType>(CToTy)) { 10097 Qualifiers FromQs = CFromTy.getQualifiers(); 10098 Qualifiers ToQs = CToTy.getQualifiers(); 10099 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10101 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10102 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10103 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10104 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10105 return; 10106 } 10107 } 10108 10109 if (TakingCandidateAddress && 10110 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10111 return; 10112 10113 // Emit the generic diagnostic and, optionally, add the hints to it. 10114 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10115 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10116 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10117 << ToTy << (unsigned)isObjectArgument << I + 1 10118 << (unsigned)(Cand->Fix.Kind); 10119 10120 // If we can fix the conversion, suggest the FixIts. 10121 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10122 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10123 FDiag << *HI; 10124 S.Diag(Fn->getLocation(), FDiag); 10125 10126 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10127 } 10128 10129 /// Additional arity mismatch diagnosis specific to a function overload 10130 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10131 /// over a candidate in any candidate set. 10132 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10133 unsigned NumArgs) { 10134 FunctionDecl *Fn = Cand->Function; 10135 unsigned MinParams = Fn->getMinRequiredArguments(); 10136 10137 // With invalid overloaded operators, it's possible that we think we 10138 // have an arity mismatch when in fact it looks like we have the 10139 // right number of arguments, because only overloaded operators have 10140 // the weird behavior of overloading member and non-member functions. 10141 // Just don't report anything. 10142 if (Fn->isInvalidDecl() && 10143 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10144 return true; 10145 10146 if (NumArgs < MinParams) { 10147 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10148 (Cand->FailureKind == ovl_fail_bad_deduction && 10149 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10150 } else { 10151 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10152 (Cand->FailureKind == ovl_fail_bad_deduction && 10153 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10154 } 10155 10156 return false; 10157 } 10158 10159 /// General arity mismatch diagnosis over a candidate in a candidate set. 10160 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10161 unsigned NumFormalArgs) { 10162 assert(isa<FunctionDecl>(D) && 10163 "The templated declaration should at least be a function" 10164 " when diagnosing bad template argument deduction due to too many" 10165 " or too few arguments"); 10166 10167 FunctionDecl *Fn = cast<FunctionDecl>(D); 10168 10169 // TODO: treat calls to a missing default constructor as a special case 10170 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 10171 unsigned MinParams = Fn->getMinRequiredArguments(); 10172 10173 // at least / at most / exactly 10174 unsigned mode, modeCount; 10175 if (NumFormalArgs < MinParams) { 10176 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10177 FnTy->isTemplateVariadic()) 10178 mode = 0; // "at least" 10179 else 10180 mode = 2; // "exactly" 10181 modeCount = MinParams; 10182 } else { 10183 if (MinParams != FnTy->getNumParams()) 10184 mode = 1; // "at most" 10185 else 10186 mode = 2; // "exactly" 10187 modeCount = FnTy->getNumParams(); 10188 } 10189 10190 std::string Description; 10191 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10192 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10193 10194 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10195 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10196 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10197 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10198 else 10199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10200 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10201 << Description << mode << modeCount << NumFormalArgs; 10202 10203 MaybeEmitInheritedConstructorNote(S, Found); 10204 } 10205 10206 /// Arity mismatch diagnosis specific to a function overload candidate. 10207 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10208 unsigned NumFormalArgs) { 10209 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10210 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10211 } 10212 10213 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10214 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10215 return TD; 10216 llvm_unreachable("Unsupported: Getting the described template declaration" 10217 " for bad deduction diagnosis"); 10218 } 10219 10220 /// Diagnose a failed template-argument deduction. 10221 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10222 DeductionFailureInfo &DeductionFailure, 10223 unsigned NumArgs, 10224 bool TakingCandidateAddress) { 10225 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10226 NamedDecl *ParamD; 10227 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10228 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10229 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10230 switch (DeductionFailure.Result) { 10231 case Sema::TDK_Success: 10232 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10233 10234 case Sema::TDK_Incomplete: { 10235 assert(ParamD && "no parameter found for incomplete deduction result"); 10236 S.Diag(Templated->getLocation(), 10237 diag::note_ovl_candidate_incomplete_deduction) 10238 << ParamD->getDeclName(); 10239 MaybeEmitInheritedConstructorNote(S, Found); 10240 return; 10241 } 10242 10243 case Sema::TDK_IncompletePack: { 10244 assert(ParamD && "no parameter found for incomplete deduction result"); 10245 S.Diag(Templated->getLocation(), 10246 diag::note_ovl_candidate_incomplete_deduction_pack) 10247 << ParamD->getDeclName() 10248 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10249 << *DeductionFailure.getFirstArg(); 10250 MaybeEmitInheritedConstructorNote(S, Found); 10251 return; 10252 } 10253 10254 case Sema::TDK_Underqualified: { 10255 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10256 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10257 10258 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10259 10260 // Param will have been canonicalized, but it should just be a 10261 // qualified version of ParamD, so move the qualifiers to that. 10262 QualifierCollector Qs; 10263 Qs.strip(Param); 10264 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10265 assert(S.Context.hasSameType(Param, NonCanonParam)); 10266 10267 // Arg has also been canonicalized, but there's nothing we can do 10268 // about that. It also doesn't matter as much, because it won't 10269 // have any template parameters in it (because deduction isn't 10270 // done on dependent types). 10271 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10272 10273 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10274 << ParamD->getDeclName() << Arg << NonCanonParam; 10275 MaybeEmitInheritedConstructorNote(S, Found); 10276 return; 10277 } 10278 10279 case Sema::TDK_Inconsistent: { 10280 assert(ParamD && "no parameter found for inconsistent deduction result"); 10281 int which = 0; 10282 if (isa<TemplateTypeParmDecl>(ParamD)) 10283 which = 0; 10284 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10285 // Deduction might have failed because we deduced arguments of two 10286 // different types for a non-type template parameter. 10287 // FIXME: Use a different TDK value for this. 10288 QualType T1 = 10289 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10290 QualType T2 = 10291 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10292 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10293 S.Diag(Templated->getLocation(), 10294 diag::note_ovl_candidate_inconsistent_deduction_types) 10295 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10296 << *DeductionFailure.getSecondArg() << T2; 10297 MaybeEmitInheritedConstructorNote(S, Found); 10298 return; 10299 } 10300 10301 which = 1; 10302 } else { 10303 which = 2; 10304 } 10305 10306 S.Diag(Templated->getLocation(), 10307 diag::note_ovl_candidate_inconsistent_deduction) 10308 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10309 << *DeductionFailure.getSecondArg(); 10310 MaybeEmitInheritedConstructorNote(S, Found); 10311 return; 10312 } 10313 10314 case Sema::TDK_InvalidExplicitArguments: 10315 assert(ParamD && "no parameter found for invalid explicit arguments"); 10316 if (ParamD->getDeclName()) 10317 S.Diag(Templated->getLocation(), 10318 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10319 << ParamD->getDeclName(); 10320 else { 10321 int index = 0; 10322 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10323 index = TTP->getIndex(); 10324 else if (NonTypeTemplateParmDecl *NTTP 10325 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10326 index = NTTP->getIndex(); 10327 else 10328 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10329 S.Diag(Templated->getLocation(), 10330 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10331 << (index + 1); 10332 } 10333 MaybeEmitInheritedConstructorNote(S, Found); 10334 return; 10335 10336 case Sema::TDK_TooManyArguments: 10337 case Sema::TDK_TooFewArguments: 10338 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10339 return; 10340 10341 case Sema::TDK_InstantiationDepth: 10342 S.Diag(Templated->getLocation(), 10343 diag::note_ovl_candidate_instantiation_depth); 10344 MaybeEmitInheritedConstructorNote(S, Found); 10345 return; 10346 10347 case Sema::TDK_SubstitutionFailure: { 10348 // Format the template argument list into the argument string. 10349 SmallString<128> TemplateArgString; 10350 if (TemplateArgumentList *Args = 10351 DeductionFailure.getTemplateArgumentList()) { 10352 TemplateArgString = " "; 10353 TemplateArgString += S.getTemplateArgumentBindingsText( 10354 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10355 } 10356 10357 // If this candidate was disabled by enable_if, say so. 10358 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10359 if (PDiag && PDiag->second.getDiagID() == 10360 diag::err_typename_nested_not_found_enable_if) { 10361 // FIXME: Use the source range of the condition, and the fully-qualified 10362 // name of the enable_if template. These are both present in PDiag. 10363 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10364 << "'enable_if'" << TemplateArgString; 10365 return; 10366 } 10367 10368 // We found a specific requirement that disabled the enable_if. 10369 if (PDiag && PDiag->second.getDiagID() == 10370 diag::err_typename_nested_not_found_requirement) { 10371 S.Diag(Templated->getLocation(), 10372 diag::note_ovl_candidate_disabled_by_requirement) 10373 << PDiag->second.getStringArg(0) << TemplateArgString; 10374 return; 10375 } 10376 10377 // Format the SFINAE diagnostic into the argument string. 10378 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10379 // formatted message in another diagnostic. 10380 SmallString<128> SFINAEArgString; 10381 SourceRange R; 10382 if (PDiag) { 10383 SFINAEArgString = ": "; 10384 R = SourceRange(PDiag->first, PDiag->first); 10385 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10386 } 10387 10388 S.Diag(Templated->getLocation(), 10389 diag::note_ovl_candidate_substitution_failure) 10390 << TemplateArgString << SFINAEArgString << R; 10391 MaybeEmitInheritedConstructorNote(S, Found); 10392 return; 10393 } 10394 10395 case Sema::TDK_DeducedMismatch: 10396 case Sema::TDK_DeducedMismatchNested: { 10397 // Format the template argument list into the argument string. 10398 SmallString<128> TemplateArgString; 10399 if (TemplateArgumentList *Args = 10400 DeductionFailure.getTemplateArgumentList()) { 10401 TemplateArgString = " "; 10402 TemplateArgString += S.getTemplateArgumentBindingsText( 10403 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10404 } 10405 10406 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10407 << (*DeductionFailure.getCallArgIndex() + 1) 10408 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10409 << TemplateArgString 10410 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10411 break; 10412 } 10413 10414 case Sema::TDK_NonDeducedMismatch: { 10415 // FIXME: Provide a source location to indicate what we couldn't match. 10416 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10417 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10418 if (FirstTA.getKind() == TemplateArgument::Template && 10419 SecondTA.getKind() == TemplateArgument::Template) { 10420 TemplateName FirstTN = FirstTA.getAsTemplate(); 10421 TemplateName SecondTN = SecondTA.getAsTemplate(); 10422 if (FirstTN.getKind() == TemplateName::Template && 10423 SecondTN.getKind() == TemplateName::Template) { 10424 if (FirstTN.getAsTemplateDecl()->getName() == 10425 SecondTN.getAsTemplateDecl()->getName()) { 10426 // FIXME: This fixes a bad diagnostic where both templates are named 10427 // the same. This particular case is a bit difficult since: 10428 // 1) It is passed as a string to the diagnostic printer. 10429 // 2) The diagnostic printer only attempts to find a better 10430 // name for types, not decls. 10431 // Ideally, this should folded into the diagnostic printer. 10432 S.Diag(Templated->getLocation(), 10433 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10434 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10435 return; 10436 } 10437 } 10438 } 10439 10440 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10441 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10442 return; 10443 10444 // FIXME: For generic lambda parameters, check if the function is a lambda 10445 // call operator, and if so, emit a prettier and more informative 10446 // diagnostic that mentions 'auto' and lambda in addition to 10447 // (or instead of?) the canonical template type parameters. 10448 S.Diag(Templated->getLocation(), 10449 diag::note_ovl_candidate_non_deduced_mismatch) 10450 << FirstTA << SecondTA; 10451 return; 10452 } 10453 // TODO: diagnose these individually, then kill off 10454 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10455 case Sema::TDK_MiscellaneousDeductionFailure: 10456 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10457 MaybeEmitInheritedConstructorNote(S, Found); 10458 return; 10459 case Sema::TDK_CUDATargetMismatch: 10460 S.Diag(Templated->getLocation(), 10461 diag::note_cuda_ovl_candidate_target_mismatch); 10462 return; 10463 } 10464 } 10465 10466 /// Diagnose a failed template-argument deduction, for function calls. 10467 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10468 unsigned NumArgs, 10469 bool TakingCandidateAddress) { 10470 unsigned TDK = Cand->DeductionFailure.Result; 10471 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10472 if (CheckArityMismatch(S, Cand, NumArgs)) 10473 return; 10474 } 10475 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10476 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10477 } 10478 10479 /// CUDA: diagnose an invalid call across targets. 10480 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10481 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10482 FunctionDecl *Callee = Cand->Function; 10483 10484 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10485 CalleeTarget = S.IdentifyCUDATarget(Callee); 10486 10487 std::string FnDesc; 10488 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10489 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, Cand->RewriteKind, 10490 FnDesc); 10491 10492 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10493 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10494 << FnDesc /* Ignored */ 10495 << CalleeTarget << CallerTarget; 10496 10497 // This could be an implicit constructor for which we could not infer the 10498 // target due to a collsion. Diagnose that case. 10499 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10500 if (Meth != nullptr && Meth->isImplicit()) { 10501 CXXRecordDecl *ParentClass = Meth->getParent(); 10502 Sema::CXXSpecialMember CSM; 10503 10504 switch (FnKindPair.first) { 10505 default: 10506 return; 10507 case oc_implicit_default_constructor: 10508 CSM = Sema::CXXDefaultConstructor; 10509 break; 10510 case oc_implicit_copy_constructor: 10511 CSM = Sema::CXXCopyConstructor; 10512 break; 10513 case oc_implicit_move_constructor: 10514 CSM = Sema::CXXMoveConstructor; 10515 break; 10516 case oc_implicit_copy_assignment: 10517 CSM = Sema::CXXCopyAssignment; 10518 break; 10519 case oc_implicit_move_assignment: 10520 CSM = Sema::CXXMoveAssignment; 10521 break; 10522 }; 10523 10524 bool ConstRHS = false; 10525 if (Meth->getNumParams()) { 10526 if (const ReferenceType *RT = 10527 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10528 ConstRHS = RT->getPointeeType().isConstQualified(); 10529 } 10530 } 10531 10532 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10533 /* ConstRHS */ ConstRHS, 10534 /* Diagnose */ true); 10535 } 10536 } 10537 10538 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10539 FunctionDecl *Callee = Cand->Function; 10540 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10541 10542 S.Diag(Callee->getLocation(), 10543 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10544 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10545 } 10546 10547 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10548 ExplicitSpecifier ES; 10549 const char *DeclName; 10550 switch (Cand->Function->getDeclKind()) { 10551 case Decl::Kind::CXXConstructor: 10552 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); 10553 DeclName = "constructor"; 10554 break; 10555 case Decl::Kind::CXXConversion: 10556 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); 10557 DeclName = "conversion operator"; 10558 break; 10559 case Decl::Kind::CXXDeductionGuide: 10560 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); 10561 DeclName = "deductiong guide"; 10562 break; 10563 default: 10564 llvm_unreachable("invalid Decl"); 10565 } 10566 assert(ES.getExpr() && "null expression should be handled before"); 10567 S.Diag(Cand->Function->getLocation(), 10568 diag::note_ovl_candidate_explicit_forbidden) 10569 << DeclName; 10570 S.Diag(ES.getExpr()->getBeginLoc(), 10571 diag::note_explicit_bool_resolved_to_true); 10572 } 10573 10574 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10575 FunctionDecl *Callee = Cand->Function; 10576 10577 S.Diag(Callee->getLocation(), 10578 diag::note_ovl_candidate_disabled_by_extension) 10579 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10580 } 10581 10582 /// Generates a 'note' diagnostic for an overload candidate. We've 10583 /// already generated a primary error at the call site. 10584 /// 10585 /// It really does need to be a single diagnostic with its caret 10586 /// pointed at the candidate declaration. Yes, this creates some 10587 /// major challenges of technical writing. Yes, this makes pointing 10588 /// out problems with specific arguments quite awkward. It's still 10589 /// better than generating twenty screens of text for every failed 10590 /// overload. 10591 /// 10592 /// It would be great to be able to express per-candidate problems 10593 /// more richly for those diagnostic clients that cared, but we'd 10594 /// still have to be just as careful with the default diagnostics. 10595 /// \param CtorDestAS Addr space of object being constructed (for ctor 10596 /// candidates only). 10597 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10598 unsigned NumArgs, 10599 bool TakingCandidateAddress, 10600 LangAS CtorDestAS = LangAS::Default) { 10601 FunctionDecl *Fn = Cand->Function; 10602 10603 // Note deleted candidates, but only if they're viable. 10604 if (Cand->Viable) { 10605 if (Fn->isDeleted()) { 10606 std::string FnDesc; 10607 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10608 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->RewriteKind, 10609 FnDesc); 10610 10611 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10612 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10613 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10614 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10615 return; 10616 } 10617 10618 // We don't really have anything else to say about viable candidates. 10619 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind); 10620 return; 10621 } 10622 10623 switch (Cand->FailureKind) { 10624 case ovl_fail_too_many_arguments: 10625 case ovl_fail_too_few_arguments: 10626 return DiagnoseArityMismatch(S, Cand, NumArgs); 10627 10628 case ovl_fail_bad_deduction: 10629 return DiagnoseBadDeduction(S, Cand, NumArgs, 10630 TakingCandidateAddress); 10631 10632 case ovl_fail_illegal_constructor: { 10633 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10634 << (Fn->getPrimaryTemplate() ? 1 : 0); 10635 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10636 return; 10637 } 10638 10639 case ovl_fail_object_addrspace_mismatch: { 10640 Qualifiers QualsForPrinting; 10641 QualsForPrinting.setAddressSpace(CtorDestAS); 10642 S.Diag(Fn->getLocation(), 10643 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10644 << QualsForPrinting; 10645 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10646 return; 10647 } 10648 10649 case ovl_fail_trivial_conversion: 10650 case ovl_fail_bad_final_conversion: 10651 case ovl_fail_final_conversion_not_exact: 10652 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind); 10653 10654 case ovl_fail_bad_conversion: { 10655 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10656 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10657 if (Cand->Conversions[I].isBad()) 10658 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10659 10660 // FIXME: this currently happens when we're called from SemaInit 10661 // when user-conversion overload fails. Figure out how to handle 10662 // those conditions and diagnose them well. 10663 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind); 10664 } 10665 10666 case ovl_fail_bad_target: 10667 return DiagnoseBadTarget(S, Cand); 10668 10669 case ovl_fail_enable_if: 10670 return DiagnoseFailedEnableIfAttr(S, Cand); 10671 10672 case ovl_fail_explicit_resolved: 10673 return DiagnoseFailedExplicitSpec(S, Cand); 10674 10675 case ovl_fail_ext_disabled: 10676 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10677 10678 case ovl_fail_inhctor_slice: 10679 // It's generally not interesting to note copy/move constructors here. 10680 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10681 return; 10682 S.Diag(Fn->getLocation(), 10683 diag::note_ovl_candidate_inherited_constructor_slice) 10684 << (Fn->getPrimaryTemplate() ? 1 : 0) 10685 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10686 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10687 return; 10688 10689 case ovl_fail_addr_not_available: { 10690 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10691 (void)Available; 10692 assert(!Available); 10693 break; 10694 } 10695 case ovl_non_default_multiversion_function: 10696 // Do nothing, these should simply be ignored. 10697 break; 10698 } 10699 } 10700 10701 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10702 // Desugar the type of the surrogate down to a function type, 10703 // retaining as many typedefs as possible while still showing 10704 // the function type (and, therefore, its parameter types). 10705 QualType FnType = Cand->Surrogate->getConversionType(); 10706 bool isLValueReference = false; 10707 bool isRValueReference = false; 10708 bool isPointer = false; 10709 if (const LValueReferenceType *FnTypeRef = 10710 FnType->getAs<LValueReferenceType>()) { 10711 FnType = FnTypeRef->getPointeeType(); 10712 isLValueReference = true; 10713 } else if (const RValueReferenceType *FnTypeRef = 10714 FnType->getAs<RValueReferenceType>()) { 10715 FnType = FnTypeRef->getPointeeType(); 10716 isRValueReference = true; 10717 } 10718 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10719 FnType = FnTypePtr->getPointeeType(); 10720 isPointer = true; 10721 } 10722 // Desugar down to a function type. 10723 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10724 // Reconstruct the pointer/reference as appropriate. 10725 if (isPointer) FnType = S.Context.getPointerType(FnType); 10726 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10727 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10728 10729 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10730 << FnType; 10731 } 10732 10733 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10734 SourceLocation OpLoc, 10735 OverloadCandidate *Cand) { 10736 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10737 std::string TypeStr("operator"); 10738 TypeStr += Opc; 10739 TypeStr += "("; 10740 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10741 if (Cand->Conversions.size() == 1) { 10742 TypeStr += ")"; 10743 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10744 } else { 10745 TypeStr += ", "; 10746 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10747 TypeStr += ")"; 10748 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10749 } 10750 } 10751 10752 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10753 OverloadCandidate *Cand) { 10754 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10755 if (ICS.isBad()) break; // all meaningless after first invalid 10756 if (!ICS.isAmbiguous()) continue; 10757 10758 ICS.DiagnoseAmbiguousConversion( 10759 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10760 } 10761 } 10762 10763 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10764 if (Cand->Function) 10765 return Cand->Function->getLocation(); 10766 if (Cand->IsSurrogate) 10767 return Cand->Surrogate->getLocation(); 10768 return SourceLocation(); 10769 } 10770 10771 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10772 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10773 case Sema::TDK_Success: 10774 case Sema::TDK_NonDependentConversionFailure: 10775 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10776 10777 case Sema::TDK_Invalid: 10778 case Sema::TDK_Incomplete: 10779 case Sema::TDK_IncompletePack: 10780 return 1; 10781 10782 case Sema::TDK_Underqualified: 10783 case Sema::TDK_Inconsistent: 10784 return 2; 10785 10786 case Sema::TDK_SubstitutionFailure: 10787 case Sema::TDK_DeducedMismatch: 10788 case Sema::TDK_DeducedMismatchNested: 10789 case Sema::TDK_NonDeducedMismatch: 10790 case Sema::TDK_MiscellaneousDeductionFailure: 10791 case Sema::TDK_CUDATargetMismatch: 10792 return 3; 10793 10794 case Sema::TDK_InstantiationDepth: 10795 return 4; 10796 10797 case Sema::TDK_InvalidExplicitArguments: 10798 return 5; 10799 10800 case Sema::TDK_TooManyArguments: 10801 case Sema::TDK_TooFewArguments: 10802 return 6; 10803 } 10804 llvm_unreachable("Unhandled deduction result"); 10805 } 10806 10807 namespace { 10808 struct CompareOverloadCandidatesForDisplay { 10809 Sema &S; 10810 SourceLocation Loc; 10811 size_t NumArgs; 10812 OverloadCandidateSet::CandidateSetKind CSK; 10813 10814 CompareOverloadCandidatesForDisplay( 10815 Sema &S, SourceLocation Loc, size_t NArgs, 10816 OverloadCandidateSet::CandidateSetKind CSK) 10817 : S(S), NumArgs(NArgs), CSK(CSK) {} 10818 10819 bool operator()(const OverloadCandidate *L, 10820 const OverloadCandidate *R) { 10821 // Fast-path this check. 10822 if (L == R) return false; 10823 10824 // Order first by viability. 10825 if (L->Viable) { 10826 if (!R->Viable) return true; 10827 10828 // TODO: introduce a tri-valued comparison for overload 10829 // candidates. Would be more worthwhile if we had a sort 10830 // that could exploit it. 10831 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10832 return true; 10833 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10834 return false; 10835 } else if (R->Viable) 10836 return false; 10837 10838 assert(L->Viable == R->Viable); 10839 10840 // Criteria by which we can sort non-viable candidates: 10841 if (!L->Viable) { 10842 // 1. Arity mismatches come after other candidates. 10843 if (L->FailureKind == ovl_fail_too_many_arguments || 10844 L->FailureKind == ovl_fail_too_few_arguments) { 10845 if (R->FailureKind == ovl_fail_too_many_arguments || 10846 R->FailureKind == ovl_fail_too_few_arguments) { 10847 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10848 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10849 if (LDist == RDist) { 10850 if (L->FailureKind == R->FailureKind) 10851 // Sort non-surrogates before surrogates. 10852 return !L->IsSurrogate && R->IsSurrogate; 10853 // Sort candidates requiring fewer parameters than there were 10854 // arguments given after candidates requiring more parameters 10855 // than there were arguments given. 10856 return L->FailureKind == ovl_fail_too_many_arguments; 10857 } 10858 return LDist < RDist; 10859 } 10860 return false; 10861 } 10862 if (R->FailureKind == ovl_fail_too_many_arguments || 10863 R->FailureKind == ovl_fail_too_few_arguments) 10864 return true; 10865 10866 // 2. Bad conversions come first and are ordered by the number 10867 // of bad conversions and quality of good conversions. 10868 if (L->FailureKind == ovl_fail_bad_conversion) { 10869 if (R->FailureKind != ovl_fail_bad_conversion) 10870 return true; 10871 10872 // The conversion that can be fixed with a smaller number of changes, 10873 // comes first. 10874 unsigned numLFixes = L->Fix.NumConversionsFixed; 10875 unsigned numRFixes = R->Fix.NumConversionsFixed; 10876 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10877 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10878 if (numLFixes != numRFixes) { 10879 return numLFixes < numRFixes; 10880 } 10881 10882 // If there's any ordering between the defined conversions... 10883 // FIXME: this might not be transitive. 10884 assert(L->Conversions.size() == R->Conversions.size()); 10885 10886 int leftBetter = 0; 10887 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10888 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10889 switch (CompareImplicitConversionSequences(S, Loc, 10890 L->Conversions[I], 10891 R->Conversions[I])) { 10892 case ImplicitConversionSequence::Better: 10893 leftBetter++; 10894 break; 10895 10896 case ImplicitConversionSequence::Worse: 10897 leftBetter--; 10898 break; 10899 10900 case ImplicitConversionSequence::Indistinguishable: 10901 break; 10902 } 10903 } 10904 if (leftBetter > 0) return true; 10905 if (leftBetter < 0) return false; 10906 10907 } else if (R->FailureKind == ovl_fail_bad_conversion) 10908 return false; 10909 10910 if (L->FailureKind == ovl_fail_bad_deduction) { 10911 if (R->FailureKind != ovl_fail_bad_deduction) 10912 return true; 10913 10914 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10915 return RankDeductionFailure(L->DeductionFailure) 10916 < RankDeductionFailure(R->DeductionFailure); 10917 } else if (R->FailureKind == ovl_fail_bad_deduction) 10918 return false; 10919 10920 // TODO: others? 10921 } 10922 10923 // Sort everything else by location. 10924 SourceLocation LLoc = GetLocationForCandidate(L); 10925 SourceLocation RLoc = GetLocationForCandidate(R); 10926 10927 // Put candidates without locations (e.g. builtins) at the end. 10928 if (LLoc.isInvalid()) return false; 10929 if (RLoc.isInvalid()) return true; 10930 10931 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10932 } 10933 }; 10934 } 10935 10936 /// CompleteNonViableCandidate - Normally, overload resolution only 10937 /// computes up to the first bad conversion. Produces the FixIt set if 10938 /// possible. 10939 static void 10940 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10941 ArrayRef<Expr *> Args, 10942 OverloadCandidateSet::CandidateSetKind CSK) { 10943 assert(!Cand->Viable); 10944 10945 // Don't do anything on failures other than bad conversion. 10946 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10947 10948 // We only want the FixIts if all the arguments can be corrected. 10949 bool Unfixable = false; 10950 // Use a implicit copy initialization to check conversion fixes. 10951 Cand->Fix.setConversionChecker(TryCopyInitialization); 10952 10953 // Attempt to fix the bad conversion. 10954 unsigned ConvCount = Cand->Conversions.size(); 10955 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10956 ++ConvIdx) { 10957 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10958 if (Cand->Conversions[ConvIdx].isInitialized() && 10959 Cand->Conversions[ConvIdx].isBad()) { 10960 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10961 break; 10962 } 10963 } 10964 10965 // FIXME: this should probably be preserved from the overload 10966 // operation somehow. 10967 bool SuppressUserConversions = false; 10968 10969 unsigned ConvIdx = 0; 10970 unsigned ArgIdx = 0; 10971 ArrayRef<QualType> ParamTypes; 10972 10973 if (Cand->IsSurrogate) { 10974 QualType ConvType 10975 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10976 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10977 ConvType = ConvPtrType->getPointeeType(); 10978 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 10979 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 10980 ConvIdx = 1; 10981 } else if (Cand->Function) { 10982 ParamTypes = 10983 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 10984 if (isa<CXXMethodDecl>(Cand->Function) && 10985 !isa<CXXConstructorDecl>(Cand->Function)) { 10986 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 10987 ConvIdx = 1; 10988 if (CSK == OverloadCandidateSet::CSK_Operator) 10989 // Argument 0 is 'this', which doesn't have a corresponding parameter. 10990 ArgIdx = 1; 10991 } 10992 } else { 10993 // Builtin operator. 10994 assert(ConvCount <= 3); 10995 ParamTypes = Cand->BuiltinParamTypes; 10996 } 10997 10998 // Fill in the rest of the conversions. 10999 bool Reversed = Cand->RewriteKind & CRK_Reversed; 11000 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11001 ConvIdx != ConvCount; 11002 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11003 if (Cand->Conversions[ConvIdx].isInitialized()) { 11004 // We've already checked this conversion. 11005 } else if (ArgIdx < ParamTypes.size()) { 11006 if (ParamTypes[ParamIdx]->isDependentType()) 11007 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11008 Args[ArgIdx]->getType()); 11009 else { 11010 Cand->Conversions[ConvIdx] = 11011 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11012 SuppressUserConversions, 11013 /*InOverloadResolution=*/true, 11014 /*AllowObjCWritebackConversion=*/ 11015 S.getLangOpts().ObjCAutoRefCount); 11016 // Store the FixIt in the candidate if it exists. 11017 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11018 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11019 } 11020 } else 11021 Cand->Conversions[ConvIdx].setEllipsis(); 11022 } 11023 } 11024 11025 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11026 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11027 SourceLocation OpLoc, 11028 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11029 // Sort the candidates by viability and position. Sorting directly would 11030 // be prohibitive, so we make a set of pointers and sort those. 11031 SmallVector<OverloadCandidate*, 32> Cands; 11032 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11033 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11034 if (!Filter(*Cand)) 11035 continue; 11036 if (Cand->Viable) 11037 Cands.push_back(Cand); 11038 else if (OCD == OCD_AllCandidates) { 11039 CompleteNonViableCandidate(S, Cand, Args, Kind); 11040 if (Cand->Function || Cand->IsSurrogate) 11041 Cands.push_back(Cand); 11042 // Otherwise, this a non-viable builtin candidate. We do not, in general, 11043 // want to list every possible builtin candidate. 11044 } 11045 } 11046 11047 llvm::stable_sort( 11048 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11049 11050 return Cands; 11051 } 11052 11053 /// When overload resolution fails, prints diagnostic messages containing the 11054 /// candidates in the candidate set. 11055 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11056 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11057 StringRef Opc, SourceLocation OpLoc, 11058 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11059 11060 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11061 11062 S.Diag(PD.first, PD.second); 11063 11064 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11065 } 11066 11067 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11068 ArrayRef<OverloadCandidate *> Cands, 11069 StringRef Opc, SourceLocation OpLoc) { 11070 bool ReportedAmbiguousConversions = false; 11071 11072 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11073 unsigned CandsShown = 0; 11074 auto I = Cands.begin(), E = Cands.end(); 11075 for (; I != E; ++I) { 11076 OverloadCandidate *Cand = *I; 11077 11078 // Set an arbitrary limit on the number of candidate functions we'll spam 11079 // the user with. FIXME: This limit should depend on details of the 11080 // candidate list. 11081 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11082 break; 11083 } 11084 ++CandsShown; 11085 11086 if (Cand->Function) 11087 NoteFunctionCandidate(S, Cand, Args.size(), 11088 /*TakingCandidateAddress=*/false, DestAS); 11089 else if (Cand->IsSurrogate) 11090 NoteSurrogateCandidate(S, Cand); 11091 else { 11092 assert(Cand->Viable && 11093 "Non-viable built-in candidates are not added to Cands."); 11094 // Generally we only see ambiguities including viable builtin 11095 // operators if overload resolution got screwed up by an 11096 // ambiguous user-defined conversion. 11097 // 11098 // FIXME: It's quite possible for different conversions to see 11099 // different ambiguities, though. 11100 if (!ReportedAmbiguousConversions) { 11101 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11102 ReportedAmbiguousConversions = true; 11103 } 11104 11105 // If this is a viable builtin, print it. 11106 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11107 } 11108 } 11109 11110 if (I != E) 11111 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11112 } 11113 11114 static SourceLocation 11115 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11116 return Cand->Specialization ? Cand->Specialization->getLocation() 11117 : SourceLocation(); 11118 } 11119 11120 namespace { 11121 struct CompareTemplateSpecCandidatesForDisplay { 11122 Sema &S; 11123 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11124 11125 bool operator()(const TemplateSpecCandidate *L, 11126 const TemplateSpecCandidate *R) { 11127 // Fast-path this check. 11128 if (L == R) 11129 return false; 11130 11131 // Assuming that both candidates are not matches... 11132 11133 // Sort by the ranking of deduction failures. 11134 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11135 return RankDeductionFailure(L->DeductionFailure) < 11136 RankDeductionFailure(R->DeductionFailure); 11137 11138 // Sort everything else by location. 11139 SourceLocation LLoc = GetLocationForCandidate(L); 11140 SourceLocation RLoc = GetLocationForCandidate(R); 11141 11142 // Put candidates without locations (e.g. builtins) at the end. 11143 if (LLoc.isInvalid()) 11144 return false; 11145 if (RLoc.isInvalid()) 11146 return true; 11147 11148 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11149 } 11150 }; 11151 } 11152 11153 /// Diagnose a template argument deduction failure. 11154 /// We are treating these failures as overload failures due to bad 11155 /// deductions. 11156 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11157 bool ForTakingAddress) { 11158 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11159 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11160 } 11161 11162 void TemplateSpecCandidateSet::destroyCandidates() { 11163 for (iterator i = begin(), e = end(); i != e; ++i) { 11164 i->DeductionFailure.Destroy(); 11165 } 11166 } 11167 11168 void TemplateSpecCandidateSet::clear() { 11169 destroyCandidates(); 11170 Candidates.clear(); 11171 } 11172 11173 /// NoteCandidates - When no template specialization match is found, prints 11174 /// diagnostic messages containing the non-matching specializations that form 11175 /// the candidate set. 11176 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11177 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11178 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11179 // Sort the candidates by position (assuming no candidate is a match). 11180 // Sorting directly would be prohibitive, so we make a set of pointers 11181 // and sort those. 11182 SmallVector<TemplateSpecCandidate *, 32> Cands; 11183 Cands.reserve(size()); 11184 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11185 if (Cand->Specialization) 11186 Cands.push_back(Cand); 11187 // Otherwise, this is a non-matching builtin candidate. We do not, 11188 // in general, want to list every possible builtin candidate. 11189 } 11190 11191 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11192 11193 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11194 // for generalization purposes (?). 11195 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11196 11197 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11198 unsigned CandsShown = 0; 11199 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11200 TemplateSpecCandidate *Cand = *I; 11201 11202 // Set an arbitrary limit on the number of candidates we'll spam 11203 // the user with. FIXME: This limit should depend on details of the 11204 // candidate list. 11205 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11206 break; 11207 ++CandsShown; 11208 11209 assert(Cand->Specialization && 11210 "Non-matching built-in candidates are not added to Cands."); 11211 Cand->NoteDeductionFailure(S, ForTakingAddress); 11212 } 11213 11214 if (I != E) 11215 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11216 } 11217 11218 // [PossiblyAFunctionType] --> [Return] 11219 // NonFunctionType --> NonFunctionType 11220 // R (A) --> R(A) 11221 // R (*)(A) --> R (A) 11222 // R (&)(A) --> R (A) 11223 // R (S::*)(A) --> R (A) 11224 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11225 QualType Ret = PossiblyAFunctionType; 11226 if (const PointerType *ToTypePtr = 11227 PossiblyAFunctionType->getAs<PointerType>()) 11228 Ret = ToTypePtr->getPointeeType(); 11229 else if (const ReferenceType *ToTypeRef = 11230 PossiblyAFunctionType->getAs<ReferenceType>()) 11231 Ret = ToTypeRef->getPointeeType(); 11232 else if (const MemberPointerType *MemTypePtr = 11233 PossiblyAFunctionType->getAs<MemberPointerType>()) 11234 Ret = MemTypePtr->getPointeeType(); 11235 Ret = 11236 Context.getCanonicalType(Ret).getUnqualifiedType(); 11237 return Ret; 11238 } 11239 11240 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11241 bool Complain = true) { 11242 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11243 S.DeduceReturnType(FD, Loc, Complain)) 11244 return true; 11245 11246 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11247 if (S.getLangOpts().CPlusPlus17 && 11248 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11249 !S.ResolveExceptionSpec(Loc, FPT)) 11250 return true; 11251 11252 return false; 11253 } 11254 11255 namespace { 11256 // A helper class to help with address of function resolution 11257 // - allows us to avoid passing around all those ugly parameters 11258 class AddressOfFunctionResolver { 11259 Sema& S; 11260 Expr* SourceExpr; 11261 const QualType& TargetType; 11262 QualType TargetFunctionType; // Extracted function type from target type 11263 11264 bool Complain; 11265 //DeclAccessPair& ResultFunctionAccessPair; 11266 ASTContext& Context; 11267 11268 bool TargetTypeIsNonStaticMemberFunction; 11269 bool FoundNonTemplateFunction; 11270 bool StaticMemberFunctionFromBoundPointer; 11271 bool HasComplained; 11272 11273 OverloadExpr::FindResult OvlExprInfo; 11274 OverloadExpr *OvlExpr; 11275 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11276 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11277 TemplateSpecCandidateSet FailedCandidates; 11278 11279 public: 11280 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11281 const QualType &TargetType, bool Complain) 11282 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11283 Complain(Complain), Context(S.getASTContext()), 11284 TargetTypeIsNonStaticMemberFunction( 11285 !!TargetType->getAs<MemberPointerType>()), 11286 FoundNonTemplateFunction(false), 11287 StaticMemberFunctionFromBoundPointer(false), 11288 HasComplained(false), 11289 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11290 OvlExpr(OvlExprInfo.Expression), 11291 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11292 ExtractUnqualifiedFunctionTypeFromTargetType(); 11293 11294 if (TargetFunctionType->isFunctionType()) { 11295 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11296 if (!UME->isImplicitAccess() && 11297 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11298 StaticMemberFunctionFromBoundPointer = true; 11299 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11300 DeclAccessPair dap; 11301 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11302 OvlExpr, false, &dap)) { 11303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11304 if (!Method->isStatic()) { 11305 // If the target type is a non-function type and the function found 11306 // is a non-static member function, pretend as if that was the 11307 // target, it's the only possible type to end up with. 11308 TargetTypeIsNonStaticMemberFunction = true; 11309 11310 // And skip adding the function if its not in the proper form. 11311 // We'll diagnose this due to an empty set of functions. 11312 if (!OvlExprInfo.HasFormOfMemberPointer) 11313 return; 11314 } 11315 11316 Matches.push_back(std::make_pair(dap, Fn)); 11317 } 11318 return; 11319 } 11320 11321 if (OvlExpr->hasExplicitTemplateArgs()) 11322 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11323 11324 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11325 // C++ [over.over]p4: 11326 // If more than one function is selected, [...] 11327 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11328 if (FoundNonTemplateFunction) 11329 EliminateAllTemplateMatches(); 11330 else 11331 EliminateAllExceptMostSpecializedTemplate(); 11332 } 11333 } 11334 11335 if (S.getLangOpts().CUDA && Matches.size() > 1) 11336 EliminateSuboptimalCudaMatches(); 11337 } 11338 11339 bool hasComplained() const { return HasComplained; } 11340 11341 private: 11342 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11343 QualType Discard; 11344 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11345 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11346 } 11347 11348 /// \return true if A is considered a better overload candidate for the 11349 /// desired type than B. 11350 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11351 // If A doesn't have exactly the correct type, we don't want to classify it 11352 // as "better" than anything else. This way, the user is required to 11353 // disambiguate for us if there are multiple candidates and no exact match. 11354 return candidateHasExactlyCorrectType(A) && 11355 (!candidateHasExactlyCorrectType(B) || 11356 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11357 } 11358 11359 /// \return true if we were able to eliminate all but one overload candidate, 11360 /// false otherwise. 11361 bool eliminiateSuboptimalOverloadCandidates() { 11362 // Same algorithm as overload resolution -- one pass to pick the "best", 11363 // another pass to be sure that nothing is better than the best. 11364 auto Best = Matches.begin(); 11365 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11366 if (isBetterCandidate(I->second, Best->second)) 11367 Best = I; 11368 11369 const FunctionDecl *BestFn = Best->second; 11370 auto IsBestOrInferiorToBest = [this, BestFn]( 11371 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11372 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11373 }; 11374 11375 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11376 // option, so we can potentially give the user a better error 11377 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11378 return false; 11379 Matches[0] = *Best; 11380 Matches.resize(1); 11381 return true; 11382 } 11383 11384 bool isTargetTypeAFunction() const { 11385 return TargetFunctionType->isFunctionType(); 11386 } 11387 11388 // [ToType] [Return] 11389 11390 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11391 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11392 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11393 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11394 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11395 } 11396 11397 // return true if any matching specializations were found 11398 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11399 const DeclAccessPair& CurAccessFunPair) { 11400 if (CXXMethodDecl *Method 11401 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11402 // Skip non-static function templates when converting to pointer, and 11403 // static when converting to member pointer. 11404 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11405 return false; 11406 } 11407 else if (TargetTypeIsNonStaticMemberFunction) 11408 return false; 11409 11410 // C++ [over.over]p2: 11411 // If the name is a function template, template argument deduction is 11412 // done (14.8.2.2), and if the argument deduction succeeds, the 11413 // resulting template argument list is used to generate a single 11414 // function template specialization, which is added to the set of 11415 // overloaded functions considered. 11416 FunctionDecl *Specialization = nullptr; 11417 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11418 if (Sema::TemplateDeductionResult Result 11419 = S.DeduceTemplateArguments(FunctionTemplate, 11420 &OvlExplicitTemplateArgs, 11421 TargetFunctionType, Specialization, 11422 Info, /*IsAddressOfFunction*/true)) { 11423 // Make a note of the failed deduction for diagnostics. 11424 FailedCandidates.addCandidate() 11425 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11426 MakeDeductionFailureInfo(Context, Result, Info)); 11427 return false; 11428 } 11429 11430 // Template argument deduction ensures that we have an exact match or 11431 // compatible pointer-to-function arguments that would be adjusted by ICS. 11432 // This function template specicalization works. 11433 assert(S.isSameOrCompatibleFunctionType( 11434 Context.getCanonicalType(Specialization->getType()), 11435 Context.getCanonicalType(TargetFunctionType))); 11436 11437 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11438 return false; 11439 11440 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11441 return true; 11442 } 11443 11444 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11445 const DeclAccessPair& CurAccessFunPair) { 11446 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11447 // Skip non-static functions when converting to pointer, and static 11448 // when converting to member pointer. 11449 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11450 return false; 11451 } 11452 else if (TargetTypeIsNonStaticMemberFunction) 11453 return false; 11454 11455 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11456 if (S.getLangOpts().CUDA) 11457 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11458 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11459 return false; 11460 if (FunDecl->isMultiVersion()) { 11461 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11462 if (TA && !TA->isDefaultVersion()) 11463 return false; 11464 } 11465 11466 // If any candidate has a placeholder return type, trigger its deduction 11467 // now. 11468 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11469 Complain)) { 11470 HasComplained |= Complain; 11471 return false; 11472 } 11473 11474 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11475 return false; 11476 11477 // If we're in C, we need to support types that aren't exactly identical. 11478 if (!S.getLangOpts().CPlusPlus || 11479 candidateHasExactlyCorrectType(FunDecl)) { 11480 Matches.push_back(std::make_pair( 11481 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11482 FoundNonTemplateFunction = true; 11483 return true; 11484 } 11485 } 11486 11487 return false; 11488 } 11489 11490 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11491 bool Ret = false; 11492 11493 // If the overload expression doesn't have the form of a pointer to 11494 // member, don't try to convert it to a pointer-to-member type. 11495 if (IsInvalidFormOfPointerToMemberFunction()) 11496 return false; 11497 11498 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11499 E = OvlExpr->decls_end(); 11500 I != E; ++I) { 11501 // Look through any using declarations to find the underlying function. 11502 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11503 11504 // C++ [over.over]p3: 11505 // Non-member functions and static member functions match 11506 // targets of type "pointer-to-function" or "reference-to-function." 11507 // Nonstatic member functions match targets of 11508 // type "pointer-to-member-function." 11509 // Note that according to DR 247, the containing class does not matter. 11510 if (FunctionTemplateDecl *FunctionTemplate 11511 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11512 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11513 Ret = true; 11514 } 11515 // If we have explicit template arguments supplied, skip non-templates. 11516 else if (!OvlExpr->hasExplicitTemplateArgs() && 11517 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11518 Ret = true; 11519 } 11520 assert(Ret || Matches.empty()); 11521 return Ret; 11522 } 11523 11524 void EliminateAllExceptMostSpecializedTemplate() { 11525 // [...] and any given function template specialization F1 is 11526 // eliminated if the set contains a second function template 11527 // specialization whose function template is more specialized 11528 // than the function template of F1 according to the partial 11529 // ordering rules of 14.5.5.2. 11530 11531 // The algorithm specified above is quadratic. We instead use a 11532 // two-pass algorithm (similar to the one used to identify the 11533 // best viable function in an overload set) that identifies the 11534 // best function template (if it exists). 11535 11536 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11537 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11538 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11539 11540 // TODO: It looks like FailedCandidates does not serve much purpose 11541 // here, since the no_viable diagnostic has index 0. 11542 UnresolvedSetIterator Result = S.getMostSpecialized( 11543 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11544 SourceExpr->getBeginLoc(), S.PDiag(), 11545 S.PDiag(diag::err_addr_ovl_ambiguous) 11546 << Matches[0].second->getDeclName(), 11547 S.PDiag(diag::note_ovl_candidate) 11548 << (unsigned)oc_function << (unsigned)ocs_described_template, 11549 Complain, TargetFunctionType); 11550 11551 if (Result != MatchesCopy.end()) { 11552 // Make it the first and only element 11553 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11554 Matches[0].second = cast<FunctionDecl>(*Result); 11555 Matches.resize(1); 11556 } else 11557 HasComplained |= Complain; 11558 } 11559 11560 void EliminateAllTemplateMatches() { 11561 // [...] any function template specializations in the set are 11562 // eliminated if the set also contains a non-template function, [...] 11563 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11564 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11565 ++I; 11566 else { 11567 Matches[I] = Matches[--N]; 11568 Matches.resize(N); 11569 } 11570 } 11571 } 11572 11573 void EliminateSuboptimalCudaMatches() { 11574 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11575 } 11576 11577 public: 11578 void ComplainNoMatchesFound() const { 11579 assert(Matches.empty()); 11580 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11581 << OvlExpr->getName() << TargetFunctionType 11582 << OvlExpr->getSourceRange(); 11583 if (FailedCandidates.empty()) 11584 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11585 /*TakingAddress=*/true); 11586 else { 11587 // We have some deduction failure messages. Use them to diagnose 11588 // the function templates, and diagnose the non-template candidates 11589 // normally. 11590 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11591 IEnd = OvlExpr->decls_end(); 11592 I != IEnd; ++I) 11593 if (FunctionDecl *Fun = 11594 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11595 if (!functionHasPassObjectSizeParams(Fun)) 11596 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 11597 /*TakingAddress=*/true); 11598 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11599 } 11600 } 11601 11602 bool IsInvalidFormOfPointerToMemberFunction() const { 11603 return TargetTypeIsNonStaticMemberFunction && 11604 !OvlExprInfo.HasFormOfMemberPointer; 11605 } 11606 11607 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11608 // TODO: Should we condition this on whether any functions might 11609 // have matched, or is it more appropriate to do that in callers? 11610 // TODO: a fixit wouldn't hurt. 11611 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11612 << TargetType << OvlExpr->getSourceRange(); 11613 } 11614 11615 bool IsStaticMemberFunctionFromBoundPointer() const { 11616 return StaticMemberFunctionFromBoundPointer; 11617 } 11618 11619 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11620 S.Diag(OvlExpr->getBeginLoc(), 11621 diag::err_invalid_form_pointer_member_function) 11622 << OvlExpr->getSourceRange(); 11623 } 11624 11625 void ComplainOfInvalidConversion() const { 11626 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11627 << OvlExpr->getName() << TargetType; 11628 } 11629 11630 void ComplainMultipleMatchesFound() const { 11631 assert(Matches.size() > 1); 11632 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11633 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11634 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11635 /*TakingAddress=*/true); 11636 } 11637 11638 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11639 11640 int getNumMatches() const { return Matches.size(); } 11641 11642 FunctionDecl* getMatchingFunctionDecl() const { 11643 if (Matches.size() != 1) return nullptr; 11644 return Matches[0].second; 11645 } 11646 11647 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11648 if (Matches.size() != 1) return nullptr; 11649 return &Matches[0].first; 11650 } 11651 }; 11652 } 11653 11654 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11655 /// an overloaded function (C++ [over.over]), where @p From is an 11656 /// expression with overloaded function type and @p ToType is the type 11657 /// we're trying to resolve to. For example: 11658 /// 11659 /// @code 11660 /// int f(double); 11661 /// int f(int); 11662 /// 11663 /// int (*pfd)(double) = f; // selects f(double) 11664 /// @endcode 11665 /// 11666 /// This routine returns the resulting FunctionDecl if it could be 11667 /// resolved, and NULL otherwise. When @p Complain is true, this 11668 /// routine will emit diagnostics if there is an error. 11669 FunctionDecl * 11670 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11671 QualType TargetType, 11672 bool Complain, 11673 DeclAccessPair &FoundResult, 11674 bool *pHadMultipleCandidates) { 11675 assert(AddressOfExpr->getType() == Context.OverloadTy); 11676 11677 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11678 Complain); 11679 int NumMatches = Resolver.getNumMatches(); 11680 FunctionDecl *Fn = nullptr; 11681 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11682 if (NumMatches == 0 && ShouldComplain) { 11683 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11684 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11685 else 11686 Resolver.ComplainNoMatchesFound(); 11687 } 11688 else if (NumMatches > 1 && ShouldComplain) 11689 Resolver.ComplainMultipleMatchesFound(); 11690 else if (NumMatches == 1) { 11691 Fn = Resolver.getMatchingFunctionDecl(); 11692 assert(Fn); 11693 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11694 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11695 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11696 if (Complain) { 11697 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11698 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11699 else 11700 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11701 } 11702 } 11703 11704 if (pHadMultipleCandidates) 11705 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11706 return Fn; 11707 } 11708 11709 /// Given an expression that refers to an overloaded function, try to 11710 /// resolve that function to a single function that can have its address taken. 11711 /// This will modify `Pair` iff it returns non-null. 11712 /// 11713 /// This routine can only realistically succeed if all but one candidates in the 11714 /// overload set for SrcExpr cannot have their addresses taken. 11715 FunctionDecl * 11716 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11717 DeclAccessPair &Pair) { 11718 OverloadExpr::FindResult R = OverloadExpr::find(E); 11719 OverloadExpr *Ovl = R.Expression; 11720 FunctionDecl *Result = nullptr; 11721 DeclAccessPair DAP; 11722 // Don't use the AddressOfResolver because we're specifically looking for 11723 // cases where we have one overload candidate that lacks 11724 // enable_if/pass_object_size/... 11725 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11726 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11727 if (!FD) 11728 return nullptr; 11729 11730 if (!checkAddressOfFunctionIsAvailable(FD)) 11731 continue; 11732 11733 // We have more than one result; quit. 11734 if (Result) 11735 return nullptr; 11736 DAP = I.getPair(); 11737 Result = FD; 11738 } 11739 11740 if (Result) 11741 Pair = DAP; 11742 return Result; 11743 } 11744 11745 /// Given an overloaded function, tries to turn it into a non-overloaded 11746 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11747 /// will perform access checks, diagnose the use of the resultant decl, and, if 11748 /// requested, potentially perform a function-to-pointer decay. 11749 /// 11750 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11751 /// Otherwise, returns true. This may emit diagnostics and return true. 11752 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11753 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11754 Expr *E = SrcExpr.get(); 11755 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11756 11757 DeclAccessPair DAP; 11758 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11759 if (!Found || Found->isCPUDispatchMultiVersion() || 11760 Found->isCPUSpecificMultiVersion()) 11761 return false; 11762 11763 // Emitting multiple diagnostics for a function that is both inaccessible and 11764 // unavailable is consistent with our behavior elsewhere. So, always check 11765 // for both. 11766 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11767 CheckAddressOfMemberAccess(E, DAP); 11768 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11769 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11770 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11771 else 11772 SrcExpr = Fixed; 11773 return true; 11774 } 11775 11776 /// Given an expression that refers to an overloaded function, try to 11777 /// resolve that overloaded function expression down to a single function. 11778 /// 11779 /// This routine can only resolve template-ids that refer to a single function 11780 /// template, where that template-id refers to a single template whose template 11781 /// arguments are either provided by the template-id or have defaults, 11782 /// as described in C++0x [temp.arg.explicit]p3. 11783 /// 11784 /// If no template-ids are found, no diagnostics are emitted and NULL is 11785 /// returned. 11786 FunctionDecl * 11787 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11788 bool Complain, 11789 DeclAccessPair *FoundResult) { 11790 // C++ [over.over]p1: 11791 // [...] [Note: any redundant set of parentheses surrounding the 11792 // overloaded function name is ignored (5.1). ] 11793 // C++ [over.over]p1: 11794 // [...] The overloaded function name can be preceded by the & 11795 // operator. 11796 11797 // If we didn't actually find any template-ids, we're done. 11798 if (!ovl->hasExplicitTemplateArgs()) 11799 return nullptr; 11800 11801 TemplateArgumentListInfo ExplicitTemplateArgs; 11802 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11803 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11804 11805 // Look through all of the overloaded functions, searching for one 11806 // whose type matches exactly. 11807 FunctionDecl *Matched = nullptr; 11808 for (UnresolvedSetIterator I = ovl->decls_begin(), 11809 E = ovl->decls_end(); I != E; ++I) { 11810 // C++0x [temp.arg.explicit]p3: 11811 // [...] In contexts where deduction is done and fails, or in contexts 11812 // where deduction is not done, if a template argument list is 11813 // specified and it, along with any default template arguments, 11814 // identifies a single function template specialization, then the 11815 // template-id is an lvalue for the function template specialization. 11816 FunctionTemplateDecl *FunctionTemplate 11817 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11818 11819 // C++ [over.over]p2: 11820 // If the name is a function template, template argument deduction is 11821 // done (14.8.2.2), and if the argument deduction succeeds, the 11822 // resulting template argument list is used to generate a single 11823 // function template specialization, which is added to the set of 11824 // overloaded functions considered. 11825 FunctionDecl *Specialization = nullptr; 11826 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11827 if (TemplateDeductionResult Result 11828 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11829 Specialization, Info, 11830 /*IsAddressOfFunction*/true)) { 11831 // Make a note of the failed deduction for diagnostics. 11832 // TODO: Actually use the failed-deduction info? 11833 FailedCandidates.addCandidate() 11834 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11835 MakeDeductionFailureInfo(Context, Result, Info)); 11836 continue; 11837 } 11838 11839 assert(Specialization && "no specialization and no error?"); 11840 11841 // Multiple matches; we can't resolve to a single declaration. 11842 if (Matched) { 11843 if (Complain) { 11844 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11845 << ovl->getName(); 11846 NoteAllOverloadCandidates(ovl); 11847 } 11848 return nullptr; 11849 } 11850 11851 Matched = Specialization; 11852 if (FoundResult) *FoundResult = I.getPair(); 11853 } 11854 11855 if (Matched && 11856 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11857 return nullptr; 11858 11859 return Matched; 11860 } 11861 11862 // Resolve and fix an overloaded expression that can be resolved 11863 // because it identifies a single function template specialization. 11864 // 11865 // Last three arguments should only be supplied if Complain = true 11866 // 11867 // Return true if it was logically possible to so resolve the 11868 // expression, regardless of whether or not it succeeded. Always 11869 // returns true if 'complain' is set. 11870 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11871 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11872 bool complain, SourceRange OpRangeForComplaining, 11873 QualType DestTypeForComplaining, 11874 unsigned DiagIDForComplaining) { 11875 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11876 11877 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11878 11879 DeclAccessPair found; 11880 ExprResult SingleFunctionExpression; 11881 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11882 ovl.Expression, /*complain*/ false, &found)) { 11883 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11884 SrcExpr = ExprError(); 11885 return true; 11886 } 11887 11888 // It is only correct to resolve to an instance method if we're 11889 // resolving a form that's permitted to be a pointer to member. 11890 // Otherwise we'll end up making a bound member expression, which 11891 // is illegal in all the contexts we resolve like this. 11892 if (!ovl.HasFormOfMemberPointer && 11893 isa<CXXMethodDecl>(fn) && 11894 cast<CXXMethodDecl>(fn)->isInstance()) { 11895 if (!complain) return false; 11896 11897 Diag(ovl.Expression->getExprLoc(), 11898 diag::err_bound_member_function) 11899 << 0 << ovl.Expression->getSourceRange(); 11900 11901 // TODO: I believe we only end up here if there's a mix of 11902 // static and non-static candidates (otherwise the expression 11903 // would have 'bound member' type, not 'overload' type). 11904 // Ideally we would note which candidate was chosen and why 11905 // the static candidates were rejected. 11906 SrcExpr = ExprError(); 11907 return true; 11908 } 11909 11910 // Fix the expression to refer to 'fn'. 11911 SingleFunctionExpression = 11912 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11913 11914 // If desired, do function-to-pointer decay. 11915 if (doFunctionPointerConverion) { 11916 SingleFunctionExpression = 11917 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11918 if (SingleFunctionExpression.isInvalid()) { 11919 SrcExpr = ExprError(); 11920 return true; 11921 } 11922 } 11923 } 11924 11925 if (!SingleFunctionExpression.isUsable()) { 11926 if (complain) { 11927 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11928 << ovl.Expression->getName() 11929 << DestTypeForComplaining 11930 << OpRangeForComplaining 11931 << ovl.Expression->getQualifierLoc().getSourceRange(); 11932 NoteAllOverloadCandidates(SrcExpr.get()); 11933 11934 SrcExpr = ExprError(); 11935 return true; 11936 } 11937 11938 return false; 11939 } 11940 11941 SrcExpr = SingleFunctionExpression; 11942 return true; 11943 } 11944 11945 /// Add a single candidate to the overload set. 11946 static void AddOverloadedCallCandidate(Sema &S, 11947 DeclAccessPair FoundDecl, 11948 TemplateArgumentListInfo *ExplicitTemplateArgs, 11949 ArrayRef<Expr *> Args, 11950 OverloadCandidateSet &CandidateSet, 11951 bool PartialOverloading, 11952 bool KnownValid) { 11953 NamedDecl *Callee = FoundDecl.getDecl(); 11954 if (isa<UsingShadowDecl>(Callee)) 11955 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11956 11957 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11958 if (ExplicitTemplateArgs) { 11959 assert(!KnownValid && "Explicit template arguments?"); 11960 return; 11961 } 11962 // Prevent ill-formed function decls to be added as overload candidates. 11963 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11964 return; 11965 11966 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11967 /*SuppressUserConversions=*/false, 11968 PartialOverloading); 11969 return; 11970 } 11971 11972 if (FunctionTemplateDecl *FuncTemplate 11973 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11974 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11975 ExplicitTemplateArgs, Args, CandidateSet, 11976 /*SuppressUserConversions=*/false, 11977 PartialOverloading); 11978 return; 11979 } 11980 11981 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11982 } 11983 11984 /// Add the overload candidates named by callee and/or found by argument 11985 /// dependent lookup to the given overload set. 11986 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11987 ArrayRef<Expr *> Args, 11988 OverloadCandidateSet &CandidateSet, 11989 bool PartialOverloading) { 11990 11991 #ifndef NDEBUG 11992 // Verify that ArgumentDependentLookup is consistent with the rules 11993 // in C++0x [basic.lookup.argdep]p3: 11994 // 11995 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11996 // and let Y be the lookup set produced by argument dependent 11997 // lookup (defined as follows). If X contains 11998 // 11999 // -- a declaration of a class member, or 12000 // 12001 // -- a block-scope function declaration that is not a 12002 // using-declaration, or 12003 // 12004 // -- a declaration that is neither a function or a function 12005 // template 12006 // 12007 // then Y is empty. 12008 12009 if (ULE->requiresADL()) { 12010 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12011 E = ULE->decls_end(); I != E; ++I) { 12012 assert(!(*I)->getDeclContext()->isRecord()); 12013 assert(isa<UsingShadowDecl>(*I) || 12014 !(*I)->getDeclContext()->isFunctionOrMethod()); 12015 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12016 } 12017 } 12018 #endif 12019 12020 // It would be nice to avoid this copy. 12021 TemplateArgumentListInfo TABuffer; 12022 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12023 if (ULE->hasExplicitTemplateArgs()) { 12024 ULE->copyTemplateArgumentsInto(TABuffer); 12025 ExplicitTemplateArgs = &TABuffer; 12026 } 12027 12028 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12029 E = ULE->decls_end(); I != E; ++I) 12030 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12031 CandidateSet, PartialOverloading, 12032 /*KnownValid*/ true); 12033 12034 if (ULE->requiresADL()) 12035 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12036 Args, ExplicitTemplateArgs, 12037 CandidateSet, PartialOverloading); 12038 } 12039 12040 /// Determine whether a declaration with the specified name could be moved into 12041 /// a different namespace. 12042 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12043 switch (Name.getCXXOverloadedOperator()) { 12044 case OO_New: case OO_Array_New: 12045 case OO_Delete: case OO_Array_Delete: 12046 return false; 12047 12048 default: 12049 return true; 12050 } 12051 } 12052 12053 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12054 /// template, where the non-dependent name was declared after the template 12055 /// was defined. This is common in code written for a compilers which do not 12056 /// correctly implement two-stage name lookup. 12057 /// 12058 /// Returns true if a viable candidate was found and a diagnostic was issued. 12059 static bool 12060 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12061 const CXXScopeSpec &SS, LookupResult &R, 12062 OverloadCandidateSet::CandidateSetKind CSK, 12063 TemplateArgumentListInfo *ExplicitTemplateArgs, 12064 ArrayRef<Expr *> Args, 12065 bool *DoDiagnoseEmptyLookup = nullptr) { 12066 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12067 return false; 12068 12069 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12070 if (DC->isTransparentContext()) 12071 continue; 12072 12073 SemaRef.LookupQualifiedName(R, DC); 12074 12075 if (!R.empty()) { 12076 R.suppressDiagnostics(); 12077 12078 if (isa<CXXRecordDecl>(DC)) { 12079 // Don't diagnose names we find in classes; we get much better 12080 // diagnostics for these from DiagnoseEmptyLookup. 12081 R.clear(); 12082 if (DoDiagnoseEmptyLookup) 12083 *DoDiagnoseEmptyLookup = true; 12084 return false; 12085 } 12086 12087 OverloadCandidateSet Candidates(FnLoc, CSK); 12088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12089 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12090 ExplicitTemplateArgs, Args, 12091 Candidates, false, /*KnownValid*/ false); 12092 12093 OverloadCandidateSet::iterator Best; 12094 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12095 // No viable functions. Don't bother the user with notes for functions 12096 // which don't work and shouldn't be found anyway. 12097 R.clear(); 12098 return false; 12099 } 12100 12101 // Find the namespaces where ADL would have looked, and suggest 12102 // declaring the function there instead. 12103 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12104 Sema::AssociatedClassSet AssociatedClasses; 12105 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12106 AssociatedNamespaces, 12107 AssociatedClasses); 12108 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12109 if (canBeDeclaredInNamespace(R.getLookupName())) { 12110 DeclContext *Std = SemaRef.getStdNamespace(); 12111 for (Sema::AssociatedNamespaceSet::iterator 12112 it = AssociatedNamespaces.begin(), 12113 end = AssociatedNamespaces.end(); it != end; ++it) { 12114 // Never suggest declaring a function within namespace 'std'. 12115 if (Std && Std->Encloses(*it)) 12116 continue; 12117 12118 // Never suggest declaring a function within a namespace with a 12119 // reserved name, like __gnu_cxx. 12120 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12121 if (NS && 12122 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12123 continue; 12124 12125 SuggestedNamespaces.insert(*it); 12126 } 12127 } 12128 12129 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12130 << R.getLookupName(); 12131 if (SuggestedNamespaces.empty()) { 12132 SemaRef.Diag(Best->Function->getLocation(), 12133 diag::note_not_found_by_two_phase_lookup) 12134 << R.getLookupName() << 0; 12135 } else if (SuggestedNamespaces.size() == 1) { 12136 SemaRef.Diag(Best->Function->getLocation(), 12137 diag::note_not_found_by_two_phase_lookup) 12138 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12139 } else { 12140 // FIXME: It would be useful to list the associated namespaces here, 12141 // but the diagnostics infrastructure doesn't provide a way to produce 12142 // a localized representation of a list of items. 12143 SemaRef.Diag(Best->Function->getLocation(), 12144 diag::note_not_found_by_two_phase_lookup) 12145 << R.getLookupName() << 2; 12146 } 12147 12148 // Try to recover by calling this function. 12149 return true; 12150 } 12151 12152 R.clear(); 12153 } 12154 12155 return false; 12156 } 12157 12158 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12159 /// template, where the non-dependent operator was declared after the template 12160 /// was defined. 12161 /// 12162 /// Returns true if a viable candidate was found and a diagnostic was issued. 12163 static bool 12164 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12165 SourceLocation OpLoc, 12166 ArrayRef<Expr *> Args) { 12167 DeclarationName OpName = 12168 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12169 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12170 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12171 OverloadCandidateSet::CSK_Operator, 12172 /*ExplicitTemplateArgs=*/nullptr, Args); 12173 } 12174 12175 namespace { 12176 class BuildRecoveryCallExprRAII { 12177 Sema &SemaRef; 12178 public: 12179 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12180 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12181 SemaRef.IsBuildingRecoveryCallExpr = true; 12182 } 12183 12184 ~BuildRecoveryCallExprRAII() { 12185 SemaRef.IsBuildingRecoveryCallExpr = false; 12186 } 12187 }; 12188 12189 } 12190 12191 /// Attempts to recover from a call where no functions were found. 12192 /// 12193 /// Returns true if new candidates were found. 12194 static ExprResult 12195 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12196 UnresolvedLookupExpr *ULE, 12197 SourceLocation LParenLoc, 12198 MutableArrayRef<Expr *> Args, 12199 SourceLocation RParenLoc, 12200 bool EmptyLookup, bool AllowTypoCorrection) { 12201 // Do not try to recover if it is already building a recovery call. 12202 // This stops infinite loops for template instantiations like 12203 // 12204 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12205 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12206 // 12207 if (SemaRef.IsBuildingRecoveryCallExpr) 12208 return ExprError(); 12209 BuildRecoveryCallExprRAII RCE(SemaRef); 12210 12211 CXXScopeSpec SS; 12212 SS.Adopt(ULE->getQualifierLoc()); 12213 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12214 12215 TemplateArgumentListInfo TABuffer; 12216 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12217 if (ULE->hasExplicitTemplateArgs()) { 12218 ULE->copyTemplateArgumentsInto(TABuffer); 12219 ExplicitTemplateArgs = &TABuffer; 12220 } 12221 12222 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12223 Sema::LookupOrdinaryName); 12224 bool DoDiagnoseEmptyLookup = EmptyLookup; 12225 if (!DiagnoseTwoPhaseLookup( 12226 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12227 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12228 NoTypoCorrectionCCC NoTypoValidator{}; 12229 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12230 ExplicitTemplateArgs != nullptr, 12231 dyn_cast<MemberExpr>(Fn)); 12232 CorrectionCandidateCallback &Validator = 12233 AllowTypoCorrection 12234 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12235 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12236 if (!DoDiagnoseEmptyLookup || 12237 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12238 Args)) 12239 return ExprError(); 12240 } 12241 12242 assert(!R.empty() && "lookup results empty despite recovery"); 12243 12244 // If recovery created an ambiguity, just bail out. 12245 if (R.isAmbiguous()) { 12246 R.suppressDiagnostics(); 12247 return ExprError(); 12248 } 12249 12250 // Build an implicit member call if appropriate. Just drop the 12251 // casts and such from the call, we don't really care. 12252 ExprResult NewFn = ExprError(); 12253 if ((*R.begin())->isCXXClassMember()) 12254 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12255 ExplicitTemplateArgs, S); 12256 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12257 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12258 ExplicitTemplateArgs); 12259 else 12260 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12261 12262 if (NewFn.isInvalid()) 12263 return ExprError(); 12264 12265 // This shouldn't cause an infinite loop because we're giving it 12266 // an expression with viable lookup results, which should never 12267 // end up here. 12268 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12269 MultiExprArg(Args.data(), Args.size()), 12270 RParenLoc); 12271 } 12272 12273 /// Constructs and populates an OverloadedCandidateSet from 12274 /// the given function. 12275 /// \returns true when an the ExprResult output parameter has been set. 12276 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12277 UnresolvedLookupExpr *ULE, 12278 MultiExprArg Args, 12279 SourceLocation RParenLoc, 12280 OverloadCandidateSet *CandidateSet, 12281 ExprResult *Result) { 12282 #ifndef NDEBUG 12283 if (ULE->requiresADL()) { 12284 // To do ADL, we must have found an unqualified name. 12285 assert(!ULE->getQualifier() && "qualified name with ADL"); 12286 12287 // We don't perform ADL for implicit declarations of builtins. 12288 // Verify that this was correctly set up. 12289 FunctionDecl *F; 12290 if (ULE->decls_begin() != ULE->decls_end() && 12291 ULE->decls_begin() + 1 == ULE->decls_end() && 12292 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12293 F->getBuiltinID() && F->isImplicit()) 12294 llvm_unreachable("performing ADL for builtin"); 12295 12296 // We don't perform ADL in C. 12297 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12298 } 12299 #endif 12300 12301 UnbridgedCastsSet UnbridgedCasts; 12302 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12303 *Result = ExprError(); 12304 return true; 12305 } 12306 12307 // Add the functions denoted by the callee to the set of candidate 12308 // functions, including those from argument-dependent lookup. 12309 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12310 12311 if (getLangOpts().MSVCCompat && 12312 CurContext->isDependentContext() && !isSFINAEContext() && 12313 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12314 12315 OverloadCandidateSet::iterator Best; 12316 if (CandidateSet->empty() || 12317 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12318 OR_No_Viable_Function) { 12319 // In Microsoft mode, if we are inside a template class member function 12320 // then create a type dependent CallExpr. The goal is to postpone name 12321 // lookup to instantiation time to be able to search into type dependent 12322 // base classes. 12323 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12324 VK_RValue, RParenLoc); 12325 CE->setTypeDependent(true); 12326 CE->setValueDependent(true); 12327 CE->setInstantiationDependent(true); 12328 *Result = CE; 12329 return true; 12330 } 12331 } 12332 12333 if (CandidateSet->empty()) 12334 return false; 12335 12336 UnbridgedCasts.restore(); 12337 return false; 12338 } 12339 12340 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12341 /// the completed call expression. If overload resolution fails, emits 12342 /// diagnostics and returns ExprError() 12343 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12344 UnresolvedLookupExpr *ULE, 12345 SourceLocation LParenLoc, 12346 MultiExprArg Args, 12347 SourceLocation RParenLoc, 12348 Expr *ExecConfig, 12349 OverloadCandidateSet *CandidateSet, 12350 OverloadCandidateSet::iterator *Best, 12351 OverloadingResult OverloadResult, 12352 bool AllowTypoCorrection) { 12353 if (CandidateSet->empty()) 12354 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12355 RParenLoc, /*EmptyLookup=*/true, 12356 AllowTypoCorrection); 12357 12358 switch (OverloadResult) { 12359 case OR_Success: { 12360 FunctionDecl *FDecl = (*Best)->Function; 12361 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12362 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12363 return ExprError(); 12364 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12365 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12366 ExecConfig, /*IsExecConfig=*/false, 12367 (*Best)->IsADLCandidate); 12368 } 12369 12370 case OR_No_Viable_Function: { 12371 // Try to recover by looking for viable functions which the user might 12372 // have meant to call. 12373 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12374 Args, RParenLoc, 12375 /*EmptyLookup=*/false, 12376 AllowTypoCorrection); 12377 if (!Recovery.isInvalid()) 12378 return Recovery; 12379 12380 // If the user passes in a function that we can't take the address of, we 12381 // generally end up emitting really bad error messages. Here, we attempt to 12382 // emit better ones. 12383 for (const Expr *Arg : Args) { 12384 if (!Arg->getType()->isFunctionType()) 12385 continue; 12386 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12387 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12388 if (FD && 12389 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12390 Arg->getExprLoc())) 12391 return ExprError(); 12392 } 12393 } 12394 12395 CandidateSet->NoteCandidates( 12396 PartialDiagnosticAt( 12397 Fn->getBeginLoc(), 12398 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12399 << ULE->getName() << Fn->getSourceRange()), 12400 SemaRef, OCD_AllCandidates, Args); 12401 break; 12402 } 12403 12404 case OR_Ambiguous: 12405 CandidateSet->NoteCandidates( 12406 PartialDiagnosticAt(Fn->getBeginLoc(), 12407 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12408 << ULE->getName() << Fn->getSourceRange()), 12409 SemaRef, OCD_ViableCandidates, Args); 12410 break; 12411 12412 case OR_Deleted: { 12413 CandidateSet->NoteCandidates( 12414 PartialDiagnosticAt(Fn->getBeginLoc(), 12415 SemaRef.PDiag(diag::err_ovl_deleted_call) 12416 << ULE->getName() << Fn->getSourceRange()), 12417 SemaRef, OCD_AllCandidates, Args); 12418 12419 // We emitted an error for the unavailable/deleted function call but keep 12420 // the call in the AST. 12421 FunctionDecl *FDecl = (*Best)->Function; 12422 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12423 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12424 ExecConfig, /*IsExecConfig=*/false, 12425 (*Best)->IsADLCandidate); 12426 } 12427 } 12428 12429 // Overload resolution failed. 12430 return ExprError(); 12431 } 12432 12433 static void markUnaddressableCandidatesUnviable(Sema &S, 12434 OverloadCandidateSet &CS) { 12435 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12436 if (I->Viable && 12437 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12438 I->Viable = false; 12439 I->FailureKind = ovl_fail_addr_not_available; 12440 } 12441 } 12442 } 12443 12444 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12445 /// (which eventually refers to the declaration Func) and the call 12446 /// arguments Args/NumArgs, attempt to resolve the function call down 12447 /// to a specific function. If overload resolution succeeds, returns 12448 /// the call expression produced by overload resolution. 12449 /// Otherwise, emits diagnostics and returns ExprError. 12450 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12451 UnresolvedLookupExpr *ULE, 12452 SourceLocation LParenLoc, 12453 MultiExprArg Args, 12454 SourceLocation RParenLoc, 12455 Expr *ExecConfig, 12456 bool AllowTypoCorrection, 12457 bool CalleesAddressIsTaken) { 12458 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12459 OverloadCandidateSet::CSK_Normal); 12460 ExprResult result; 12461 12462 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12463 &result)) 12464 return result; 12465 12466 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12467 // functions that aren't addressible are considered unviable. 12468 if (CalleesAddressIsTaken) 12469 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12470 12471 OverloadCandidateSet::iterator Best; 12472 OverloadingResult OverloadResult = 12473 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12474 12475 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12476 ExecConfig, &CandidateSet, &Best, 12477 OverloadResult, AllowTypoCorrection); 12478 } 12479 12480 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12481 return Functions.size() > 1 || 12482 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12483 } 12484 12485 /// Create a unary operation that may resolve to an overloaded 12486 /// operator. 12487 /// 12488 /// \param OpLoc The location of the operator itself (e.g., '*'). 12489 /// 12490 /// \param Opc The UnaryOperatorKind that describes this operator. 12491 /// 12492 /// \param Fns The set of non-member functions that will be 12493 /// considered by overload resolution. The caller needs to build this 12494 /// set based on the context using, e.g., 12495 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12496 /// set should not contain any member functions; those will be added 12497 /// by CreateOverloadedUnaryOp(). 12498 /// 12499 /// \param Input The input argument. 12500 ExprResult 12501 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12502 const UnresolvedSetImpl &Fns, 12503 Expr *Input, bool PerformADL) { 12504 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12505 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12506 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12507 // TODO: provide better source location info. 12508 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12509 12510 if (checkPlaceholderForOverload(*this, Input)) 12511 return ExprError(); 12512 12513 Expr *Args[2] = { Input, nullptr }; 12514 unsigned NumArgs = 1; 12515 12516 // For post-increment and post-decrement, add the implicit '0' as 12517 // the second argument, so that we know this is a post-increment or 12518 // post-decrement. 12519 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12520 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12521 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12522 SourceLocation()); 12523 NumArgs = 2; 12524 } 12525 12526 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12527 12528 if (Input->isTypeDependent()) { 12529 if (Fns.empty()) 12530 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12531 VK_RValue, OK_Ordinary, OpLoc, false); 12532 12533 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12534 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12535 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12536 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12537 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12538 Context.DependentTy, VK_RValue, OpLoc, 12539 FPOptions()); 12540 } 12541 12542 // Build an empty overload set. 12543 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12544 12545 // Add the candidates from the given function set. 12546 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 12547 12548 // Add operator candidates that are member functions. 12549 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12550 12551 // Add candidates from ADL. 12552 if (PerformADL) { 12553 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12554 /*ExplicitTemplateArgs*/nullptr, 12555 CandidateSet); 12556 } 12557 12558 // Add builtin operator candidates. 12559 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12560 12561 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12562 12563 // Perform overload resolution. 12564 OverloadCandidateSet::iterator Best; 12565 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12566 case OR_Success: { 12567 // We found a built-in operator or an overloaded operator. 12568 FunctionDecl *FnDecl = Best->Function; 12569 12570 if (FnDecl) { 12571 Expr *Base = nullptr; 12572 // We matched an overloaded operator. Build a call to that 12573 // operator. 12574 12575 // Convert the arguments. 12576 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12577 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12578 12579 ExprResult InputRes = 12580 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12581 Best->FoundDecl, Method); 12582 if (InputRes.isInvalid()) 12583 return ExprError(); 12584 Base = Input = InputRes.get(); 12585 } else { 12586 // Convert the arguments. 12587 ExprResult InputInit 12588 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12589 Context, 12590 FnDecl->getParamDecl(0)), 12591 SourceLocation(), 12592 Input); 12593 if (InputInit.isInvalid()) 12594 return ExprError(); 12595 Input = InputInit.get(); 12596 } 12597 12598 // Build the actual expression node. 12599 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12600 Base, HadMultipleCandidates, 12601 OpLoc); 12602 if (FnExpr.isInvalid()) 12603 return ExprError(); 12604 12605 // Determine the result type. 12606 QualType ResultTy = FnDecl->getReturnType(); 12607 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12608 ResultTy = ResultTy.getNonLValueExprType(Context); 12609 12610 Args[0] = Input; 12611 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12612 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12613 FPOptions(), Best->IsADLCandidate); 12614 12615 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12616 return ExprError(); 12617 12618 if (CheckFunctionCall(FnDecl, TheCall, 12619 FnDecl->getType()->castAs<FunctionProtoType>())) 12620 return ExprError(); 12621 12622 return MaybeBindToTemporary(TheCall); 12623 } else { 12624 // We matched a built-in operator. Convert the arguments, then 12625 // break out so that we will build the appropriate built-in 12626 // operator node. 12627 ExprResult InputRes = PerformImplicitConversion( 12628 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12629 CCK_ForBuiltinOverloadedOp); 12630 if (InputRes.isInvalid()) 12631 return ExprError(); 12632 Input = InputRes.get(); 12633 break; 12634 } 12635 } 12636 12637 case OR_No_Viable_Function: 12638 // This is an erroneous use of an operator which can be overloaded by 12639 // a non-member function. Check for non-member operators which were 12640 // defined too late to be candidates. 12641 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12642 // FIXME: Recover by calling the found function. 12643 return ExprError(); 12644 12645 // No viable function; fall through to handling this as a 12646 // built-in operator, which will produce an error message for us. 12647 break; 12648 12649 case OR_Ambiguous: 12650 CandidateSet.NoteCandidates( 12651 PartialDiagnosticAt(OpLoc, 12652 PDiag(diag::err_ovl_ambiguous_oper_unary) 12653 << UnaryOperator::getOpcodeStr(Opc) 12654 << Input->getType() << Input->getSourceRange()), 12655 *this, OCD_ViableCandidates, ArgsArray, 12656 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12657 return ExprError(); 12658 12659 case OR_Deleted: 12660 CandidateSet.NoteCandidates( 12661 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12662 << UnaryOperator::getOpcodeStr(Opc) 12663 << Input->getSourceRange()), 12664 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 12665 OpLoc); 12666 return ExprError(); 12667 } 12668 12669 // Either we found no viable overloaded operator or we matched a 12670 // built-in operator. In either case, fall through to trying to 12671 // build a built-in operation. 12672 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12673 } 12674 12675 /// Create a binary operation that may resolve to an overloaded 12676 /// operator. 12677 /// 12678 /// \param OpLoc The location of the operator itself (e.g., '+'). 12679 /// 12680 /// \param Opc The BinaryOperatorKind that describes this operator. 12681 /// 12682 /// \param Fns The set of non-member functions that will be 12683 /// considered by overload resolution. The caller needs to build this 12684 /// set based on the context using, e.g., 12685 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12686 /// set should not contain any member functions; those will be added 12687 /// by CreateOverloadedBinOp(). 12688 /// 12689 /// \param LHS Left-hand argument. 12690 /// \param RHS Right-hand argument. 12691 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12692 BinaryOperatorKind Opc, 12693 const UnresolvedSetImpl &Fns, Expr *LHS, 12694 Expr *RHS, bool PerformADL, 12695 bool AllowRewrittenCandidates) { 12696 Expr *Args[2] = { LHS, RHS }; 12697 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12698 12699 if (!getLangOpts().CPlusPlus2a) 12700 AllowRewrittenCandidates = false; 12701 12702 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12703 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12704 12705 // If either side is type-dependent, create an appropriate dependent 12706 // expression. 12707 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12708 if (Fns.empty()) { 12709 // If there are no functions to store, just build a dependent 12710 // BinaryOperator or CompoundAssignment. 12711 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12712 return new (Context) BinaryOperator( 12713 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12714 OpLoc, FPFeatures); 12715 12716 return new (Context) CompoundAssignOperator( 12717 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12718 Context.DependentTy, Context.DependentTy, OpLoc, 12719 FPFeatures); 12720 } 12721 12722 // FIXME: save results of ADL from here? 12723 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12724 // TODO: provide better source location info in DNLoc component. 12725 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12726 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12727 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12728 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12729 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12730 Context.DependentTy, VK_RValue, OpLoc, 12731 FPFeatures); 12732 } 12733 12734 // Always do placeholder-like conversions on the RHS. 12735 if (checkPlaceholderForOverload(*this, Args[1])) 12736 return ExprError(); 12737 12738 // Do placeholder-like conversion on the LHS; note that we should 12739 // not get here with a PseudoObject LHS. 12740 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12741 if (checkPlaceholderForOverload(*this, Args[0])) 12742 return ExprError(); 12743 12744 // If this is the assignment operator, we only perform overload resolution 12745 // if the left-hand side is a class or enumeration type. This is actually 12746 // a hack. The standard requires that we do overload resolution between the 12747 // various built-in candidates, but as DR507 points out, this can lead to 12748 // problems. So we do it this way, which pretty much follows what GCC does. 12749 // Note that we go the traditional code path for compound assignment forms. 12750 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12751 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12752 12753 // If this is the .* operator, which is not overloadable, just 12754 // create a built-in binary operator. 12755 if (Opc == BO_PtrMemD) 12756 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12757 12758 // Build an empty overload set. 12759 OverloadCandidateSet CandidateSet( 12760 OpLoc, OverloadCandidateSet::CSK_Operator, 12761 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 12762 12763 OverloadedOperatorKind ExtraOp = 12764 AllowRewrittenCandidates ? getRewrittenOverloadedOperator(Op) : OO_None; 12765 12766 // Add the candidates from the given function set. This also adds the 12767 // rewritten candidates using these functions if necessary. 12768 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 12769 12770 // Add operator candidates that are member functions. 12771 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12772 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 12773 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 12774 OverloadCandidateParamOrder::Reversed); 12775 12776 // In C++20, also add any rewritten member candidates. 12777 if (ExtraOp) { 12778 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 12779 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 12780 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 12781 CandidateSet, 12782 OverloadCandidateParamOrder::Reversed); 12783 } 12784 12785 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12786 // performed for an assignment operator (nor for operator[] nor operator->, 12787 // which don't get here). 12788 if (Opc != BO_Assign && PerformADL) { 12789 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12790 /*ExplicitTemplateArgs*/ nullptr, 12791 CandidateSet); 12792 if (ExtraOp) { 12793 DeclarationName ExtraOpName = 12794 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 12795 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 12796 /*ExplicitTemplateArgs*/ nullptr, 12797 CandidateSet); 12798 } 12799 } 12800 12801 // Add builtin operator candidates. 12802 // 12803 // FIXME: We don't add any rewritten candidates here. This is strictly 12804 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 12805 // resulting in our selecting a rewritten builtin candidate. For example: 12806 // 12807 // enum class E { e }; 12808 // bool operator!=(E, E) requires false; 12809 // bool k = E::e != E::e; 12810 // 12811 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 12812 // it seems unreasonable to consider rewritten builtin candidates. A core 12813 // issue has been filed proposing to removed this requirement. 12814 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12815 12816 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12817 12818 // Perform overload resolution. 12819 OverloadCandidateSet::iterator Best; 12820 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12821 case OR_Success: { 12822 // We found a built-in operator or an overloaded operator. 12823 FunctionDecl *FnDecl = Best->Function; 12824 12825 bool IsReversed = (Best->RewriteKind & CRK_Reversed); 12826 if (IsReversed) 12827 std::swap(Args[0], Args[1]); 12828 12829 if (FnDecl) { 12830 Expr *Base = nullptr; 12831 // We matched an overloaded operator. Build a call to that 12832 // operator. 12833 12834 OverloadedOperatorKind ChosenOp = 12835 FnDecl->getDeclName().getCXXOverloadedOperator(); 12836 12837 // C++2a [over.match.oper]p9: 12838 // If a rewritten operator== candidate is selected by overload 12839 // resolution for an operator@, its return type shall be cv bool 12840 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 12841 !FnDecl->getReturnType()->isBooleanType()) { 12842 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) 12843 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 12844 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12845 Diag(FnDecl->getLocation(), diag::note_declared_at); 12846 return ExprError(); 12847 } 12848 12849 if (AllowRewrittenCandidates && !IsReversed && 12850 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { 12851 // We could have reversed this operator, but didn't. Check if the 12852 // reversed form was a viable candidate, and if so, if it had a 12853 // better conversion for either parameter. If so, this call is 12854 // formally ambiguous, and allowing it is an extension. 12855 for (OverloadCandidate &Cand : CandidateSet) { 12856 if (Cand.Viable && Cand.Function == FnDecl && 12857 Cand.RewriteKind & CRK_Reversed) { 12858 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 12859 if (CompareImplicitConversionSequences( 12860 *this, OpLoc, Cand.Conversions[ArgIdx], 12861 Best->Conversions[ArgIdx]) == 12862 ImplicitConversionSequence::Better) { 12863 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 12864 << BinaryOperator::getOpcodeStr(Opc) 12865 << Args[0]->getType() << Args[1]->getType() 12866 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12867 Diag(FnDecl->getLocation(), 12868 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 12869 } 12870 } 12871 break; 12872 } 12873 } 12874 } 12875 12876 // Convert the arguments. 12877 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12878 // Best->Access is only meaningful for class members. 12879 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12880 12881 ExprResult Arg1 = 12882 PerformCopyInitialization( 12883 InitializedEntity::InitializeParameter(Context, 12884 FnDecl->getParamDecl(0)), 12885 SourceLocation(), Args[1]); 12886 if (Arg1.isInvalid()) 12887 return ExprError(); 12888 12889 ExprResult Arg0 = 12890 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12891 Best->FoundDecl, Method); 12892 if (Arg0.isInvalid()) 12893 return ExprError(); 12894 Base = Args[0] = Arg0.getAs<Expr>(); 12895 Args[1] = RHS = Arg1.getAs<Expr>(); 12896 } else { 12897 // Convert the arguments. 12898 ExprResult Arg0 = PerformCopyInitialization( 12899 InitializedEntity::InitializeParameter(Context, 12900 FnDecl->getParamDecl(0)), 12901 SourceLocation(), Args[0]); 12902 if (Arg0.isInvalid()) 12903 return ExprError(); 12904 12905 ExprResult Arg1 = 12906 PerformCopyInitialization( 12907 InitializedEntity::InitializeParameter(Context, 12908 FnDecl->getParamDecl(1)), 12909 SourceLocation(), Args[1]); 12910 if (Arg1.isInvalid()) 12911 return ExprError(); 12912 Args[0] = LHS = Arg0.getAs<Expr>(); 12913 Args[1] = RHS = Arg1.getAs<Expr>(); 12914 } 12915 12916 // Build the actual expression node. 12917 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12918 Best->FoundDecl, Base, 12919 HadMultipleCandidates, OpLoc); 12920 if (FnExpr.isInvalid()) 12921 return ExprError(); 12922 12923 // Determine the result type. 12924 QualType ResultTy = FnDecl->getReturnType(); 12925 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12926 ResultTy = ResultTy.getNonLValueExprType(Context); 12927 12928 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12929 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 12930 FPFeatures, Best->IsADLCandidate); 12931 12932 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12933 FnDecl)) 12934 return ExprError(); 12935 12936 ArrayRef<const Expr *> ArgsArray(Args, 2); 12937 const Expr *ImplicitThis = nullptr; 12938 // Cut off the implicit 'this'. 12939 if (isa<CXXMethodDecl>(FnDecl)) { 12940 ImplicitThis = ArgsArray[0]; 12941 ArgsArray = ArgsArray.slice(1); 12942 } 12943 12944 // Check for a self move. 12945 if (Op == OO_Equal) 12946 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12947 12948 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12949 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12950 VariadicDoesNotApply); 12951 12952 ExprResult R = MaybeBindToTemporary(TheCall); 12953 if (R.isInvalid()) 12954 return ExprError(); 12955 12956 // For a rewritten candidate, we've already reversed the arguments 12957 // if needed. Perform the rest of the rewrite now. 12958 if ((Best->RewriteKind & CRK_DifferentOperator) || 12959 (Op == OO_Spaceship && IsReversed)) { 12960 if (Op == OO_ExclaimEqual) { 12961 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 12962 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 12963 } else { 12964 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 12965 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12966 Expr *ZeroLiteral = 12967 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 12968 12969 Sema::CodeSynthesisContext Ctx; 12970 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 12971 Ctx.Entity = FnDecl; 12972 pushCodeSynthesisContext(Ctx); 12973 12974 R = CreateOverloadedBinOp( 12975 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 12976 IsReversed ? R.get() : ZeroLiteral, PerformADL, 12977 /*AllowRewrittenCandidates=*/false); 12978 12979 popCodeSynthesisContext(); 12980 } 12981 if (R.isInvalid()) 12982 return ExprError(); 12983 } else { 12984 assert(ChosenOp == Op && "unexpected operator name"); 12985 } 12986 12987 // Make a note in the AST if we did any rewriting. 12988 if (Best->RewriteKind != CRK_None) 12989 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 12990 12991 return R; 12992 } else { 12993 // We matched a built-in operator. Convert the arguments, then 12994 // break out so that we will build the appropriate built-in 12995 // operator node. 12996 ExprResult ArgsRes0 = PerformImplicitConversion( 12997 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12998 AA_Passing, CCK_ForBuiltinOverloadedOp); 12999 if (ArgsRes0.isInvalid()) 13000 return ExprError(); 13001 Args[0] = ArgsRes0.get(); 13002 13003 ExprResult ArgsRes1 = PerformImplicitConversion( 13004 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13005 AA_Passing, CCK_ForBuiltinOverloadedOp); 13006 if (ArgsRes1.isInvalid()) 13007 return ExprError(); 13008 Args[1] = ArgsRes1.get(); 13009 break; 13010 } 13011 } 13012 13013 case OR_No_Viable_Function: { 13014 // C++ [over.match.oper]p9: 13015 // If the operator is the operator , [...] and there are no 13016 // viable functions, then the operator is assumed to be the 13017 // built-in operator and interpreted according to clause 5. 13018 if (Opc == BO_Comma) 13019 break; 13020 13021 // For class as left operand for assignment or compound assignment 13022 // operator do not fall through to handling in built-in, but report that 13023 // no overloaded assignment operator found 13024 ExprResult Result = ExprError(); 13025 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13026 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13027 Args, OpLoc); 13028 if (Args[0]->getType()->isRecordType() && 13029 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13030 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13031 << BinaryOperator::getOpcodeStr(Opc) 13032 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13033 if (Args[0]->getType()->isIncompleteType()) { 13034 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13035 << Args[0]->getType() 13036 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13037 } 13038 } else { 13039 // This is an erroneous use of an operator which can be overloaded by 13040 // a non-member function. Check for non-member operators which were 13041 // defined too late to be candidates. 13042 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13043 // FIXME: Recover by calling the found function. 13044 return ExprError(); 13045 13046 // No viable function; try to create a built-in operation, which will 13047 // produce an error. Then, show the non-viable candidates. 13048 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13049 } 13050 assert(Result.isInvalid() && 13051 "C++ binary operator overloading is missing candidates!"); 13052 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13053 return Result; 13054 } 13055 13056 case OR_Ambiguous: 13057 CandidateSet.NoteCandidates( 13058 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13059 << BinaryOperator::getOpcodeStr(Opc) 13060 << Args[0]->getType() 13061 << Args[1]->getType() 13062 << Args[0]->getSourceRange() 13063 << Args[1]->getSourceRange()), 13064 *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13065 OpLoc); 13066 return ExprError(); 13067 13068 case OR_Deleted: 13069 if (isImplicitlyDeleted(Best->Function)) { 13070 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13071 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13072 << Context.getRecordType(Method->getParent()) 13073 << getSpecialMember(Method); 13074 13075 // The user probably meant to call this special member. Just 13076 // explain why it's deleted. 13077 NoteDeletedFunction(Method); 13078 return ExprError(); 13079 } 13080 CandidateSet.NoteCandidates( 13081 PartialDiagnosticAt( 13082 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13083 << getOperatorSpelling(Best->Function->getDeclName() 13084 .getCXXOverloadedOperator()) 13085 << Args[0]->getSourceRange() 13086 << Args[1]->getSourceRange()), 13087 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13088 OpLoc); 13089 return ExprError(); 13090 } 13091 13092 // We matched a built-in operator; build it. 13093 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13094 } 13095 13096 ExprResult 13097 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13098 SourceLocation RLoc, 13099 Expr *Base, Expr *Idx) { 13100 Expr *Args[2] = { Base, Idx }; 13101 DeclarationName OpName = 13102 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13103 13104 // If either side is type-dependent, create an appropriate dependent 13105 // expression. 13106 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13107 13108 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13109 // CHECKME: no 'operator' keyword? 13110 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13111 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13112 UnresolvedLookupExpr *Fn 13113 = UnresolvedLookupExpr::Create(Context, NamingClass, 13114 NestedNameSpecifierLoc(), OpNameInfo, 13115 /*ADL*/ true, /*Overloaded*/ false, 13116 UnresolvedSetIterator(), 13117 UnresolvedSetIterator()); 13118 // Can't add any actual overloads yet 13119 13120 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13121 Context.DependentTy, VK_RValue, RLoc, 13122 FPOptions()); 13123 } 13124 13125 // Handle placeholders on both operands. 13126 if (checkPlaceholderForOverload(*this, Args[0])) 13127 return ExprError(); 13128 if (checkPlaceholderForOverload(*this, Args[1])) 13129 return ExprError(); 13130 13131 // Build an empty overload set. 13132 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13133 13134 // Subscript can only be overloaded as a member function. 13135 13136 // Add operator candidates that are member functions. 13137 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13138 13139 // Add builtin operator candidates. 13140 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13141 13142 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13143 13144 // Perform overload resolution. 13145 OverloadCandidateSet::iterator Best; 13146 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13147 case OR_Success: { 13148 // We found a built-in operator or an overloaded operator. 13149 FunctionDecl *FnDecl = Best->Function; 13150 13151 if (FnDecl) { 13152 // We matched an overloaded operator. Build a call to that 13153 // operator. 13154 13155 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13156 13157 // Convert the arguments. 13158 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13159 ExprResult Arg0 = 13160 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13161 Best->FoundDecl, Method); 13162 if (Arg0.isInvalid()) 13163 return ExprError(); 13164 Args[0] = Arg0.get(); 13165 13166 // Convert the arguments. 13167 ExprResult InputInit 13168 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13169 Context, 13170 FnDecl->getParamDecl(0)), 13171 SourceLocation(), 13172 Args[1]); 13173 if (InputInit.isInvalid()) 13174 return ExprError(); 13175 13176 Args[1] = InputInit.getAs<Expr>(); 13177 13178 // Build the actual expression node. 13179 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13180 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13181 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13182 Best->FoundDecl, 13183 Base, 13184 HadMultipleCandidates, 13185 OpLocInfo.getLoc(), 13186 OpLocInfo.getInfo()); 13187 if (FnExpr.isInvalid()) 13188 return ExprError(); 13189 13190 // Determine the result type 13191 QualType ResultTy = FnDecl->getReturnType(); 13192 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13193 ResultTy = ResultTy.getNonLValueExprType(Context); 13194 13195 CXXOperatorCallExpr *TheCall = 13196 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13197 Args, ResultTy, VK, RLoc, FPOptions()); 13198 13199 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13200 return ExprError(); 13201 13202 if (CheckFunctionCall(Method, TheCall, 13203 Method->getType()->castAs<FunctionProtoType>())) 13204 return ExprError(); 13205 13206 return MaybeBindToTemporary(TheCall); 13207 } else { 13208 // We matched a built-in operator. Convert the arguments, then 13209 // break out so that we will build the appropriate built-in 13210 // operator node. 13211 ExprResult ArgsRes0 = PerformImplicitConversion( 13212 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13213 AA_Passing, CCK_ForBuiltinOverloadedOp); 13214 if (ArgsRes0.isInvalid()) 13215 return ExprError(); 13216 Args[0] = ArgsRes0.get(); 13217 13218 ExprResult ArgsRes1 = PerformImplicitConversion( 13219 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13220 AA_Passing, CCK_ForBuiltinOverloadedOp); 13221 if (ArgsRes1.isInvalid()) 13222 return ExprError(); 13223 Args[1] = ArgsRes1.get(); 13224 13225 break; 13226 } 13227 } 13228 13229 case OR_No_Viable_Function: { 13230 PartialDiagnostic PD = CandidateSet.empty() 13231 ? (PDiag(diag::err_ovl_no_oper) 13232 << Args[0]->getType() << /*subscript*/ 0 13233 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13234 : (PDiag(diag::err_ovl_no_viable_subscript) 13235 << Args[0]->getType() << Args[0]->getSourceRange() 13236 << Args[1]->getSourceRange()); 13237 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13238 OCD_AllCandidates, Args, "[]", LLoc); 13239 return ExprError(); 13240 } 13241 13242 case OR_Ambiguous: 13243 CandidateSet.NoteCandidates( 13244 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13245 << "[]" << Args[0]->getType() 13246 << Args[1]->getType() 13247 << Args[0]->getSourceRange() 13248 << Args[1]->getSourceRange()), 13249 *this, OCD_ViableCandidates, Args, "[]", LLoc); 13250 return ExprError(); 13251 13252 case OR_Deleted: 13253 CandidateSet.NoteCandidates( 13254 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13255 << "[]" << Args[0]->getSourceRange() 13256 << Args[1]->getSourceRange()), 13257 *this, OCD_AllCandidates, Args, "[]", LLoc); 13258 return ExprError(); 13259 } 13260 13261 // We matched a built-in operator; build it. 13262 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13263 } 13264 13265 /// BuildCallToMemberFunction - Build a call to a member 13266 /// function. MemExpr is the expression that refers to the member 13267 /// function (and includes the object parameter), Args/NumArgs are the 13268 /// arguments to the function call (not including the object 13269 /// parameter). The caller needs to validate that the member 13270 /// expression refers to a non-static member function or an overloaded 13271 /// member function. 13272 ExprResult 13273 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13274 SourceLocation LParenLoc, 13275 MultiExprArg Args, 13276 SourceLocation RParenLoc) { 13277 assert(MemExprE->getType() == Context.BoundMemberTy || 13278 MemExprE->getType() == Context.OverloadTy); 13279 13280 // Dig out the member expression. This holds both the object 13281 // argument and the member function we're referring to. 13282 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13283 13284 // Determine whether this is a call to a pointer-to-member function. 13285 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13286 assert(op->getType() == Context.BoundMemberTy); 13287 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13288 13289 QualType fnType = 13290 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13291 13292 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13293 QualType resultType = proto->getCallResultType(Context); 13294 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13295 13296 // Check that the object type isn't more qualified than the 13297 // member function we're calling. 13298 Qualifiers funcQuals = proto->getMethodQuals(); 13299 13300 QualType objectType = op->getLHS()->getType(); 13301 if (op->getOpcode() == BO_PtrMemI) 13302 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13303 Qualifiers objectQuals = objectType.getQualifiers(); 13304 13305 Qualifiers difference = objectQuals - funcQuals; 13306 difference.removeObjCGCAttr(); 13307 difference.removeAddressSpace(); 13308 if (difference) { 13309 std::string qualsString = difference.getAsString(); 13310 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13311 << fnType.getUnqualifiedType() 13312 << qualsString 13313 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13314 } 13315 13316 CXXMemberCallExpr *call = 13317 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13318 valueKind, RParenLoc, proto->getNumParams()); 13319 13320 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13321 call, nullptr)) 13322 return ExprError(); 13323 13324 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13325 return ExprError(); 13326 13327 if (CheckOtherCall(call, proto)) 13328 return ExprError(); 13329 13330 return MaybeBindToTemporary(call); 13331 } 13332 13333 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13334 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13335 RParenLoc); 13336 13337 UnbridgedCastsSet UnbridgedCasts; 13338 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13339 return ExprError(); 13340 13341 MemberExpr *MemExpr; 13342 CXXMethodDecl *Method = nullptr; 13343 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13344 NestedNameSpecifier *Qualifier = nullptr; 13345 if (isa<MemberExpr>(NakedMemExpr)) { 13346 MemExpr = cast<MemberExpr>(NakedMemExpr); 13347 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13348 FoundDecl = MemExpr->getFoundDecl(); 13349 Qualifier = MemExpr->getQualifier(); 13350 UnbridgedCasts.restore(); 13351 } else { 13352 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13353 Qualifier = UnresExpr->getQualifier(); 13354 13355 QualType ObjectType = UnresExpr->getBaseType(); 13356 Expr::Classification ObjectClassification 13357 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13358 : UnresExpr->getBase()->Classify(Context); 13359 13360 // Add overload candidates 13361 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13362 OverloadCandidateSet::CSK_Normal); 13363 13364 // FIXME: avoid copy. 13365 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13366 if (UnresExpr->hasExplicitTemplateArgs()) { 13367 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13368 TemplateArgs = &TemplateArgsBuffer; 13369 } 13370 13371 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13372 E = UnresExpr->decls_end(); I != E; ++I) { 13373 13374 NamedDecl *Func = *I; 13375 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13376 if (isa<UsingShadowDecl>(Func)) 13377 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13378 13379 13380 // Microsoft supports direct constructor calls. 13381 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13382 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13383 CandidateSet, 13384 /*SuppressUserConversions*/ false); 13385 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13386 // If explicit template arguments were provided, we can't call a 13387 // non-template member function. 13388 if (TemplateArgs) 13389 continue; 13390 13391 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13392 ObjectClassification, Args, CandidateSet, 13393 /*SuppressUserConversions=*/false); 13394 } else { 13395 AddMethodTemplateCandidate( 13396 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13397 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13398 /*SuppressUserConversions=*/false); 13399 } 13400 } 13401 13402 DeclarationName DeclName = UnresExpr->getMemberName(); 13403 13404 UnbridgedCasts.restore(); 13405 13406 OverloadCandidateSet::iterator Best; 13407 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13408 Best)) { 13409 case OR_Success: 13410 Method = cast<CXXMethodDecl>(Best->Function); 13411 FoundDecl = Best->FoundDecl; 13412 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13413 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13414 return ExprError(); 13415 // If FoundDecl is different from Method (such as if one is a template 13416 // and the other a specialization), make sure DiagnoseUseOfDecl is 13417 // called on both. 13418 // FIXME: This would be more comprehensively addressed by modifying 13419 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13420 // being used. 13421 if (Method != FoundDecl.getDecl() && 13422 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13423 return ExprError(); 13424 break; 13425 13426 case OR_No_Viable_Function: 13427 CandidateSet.NoteCandidates( 13428 PartialDiagnosticAt( 13429 UnresExpr->getMemberLoc(), 13430 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13431 << DeclName << MemExprE->getSourceRange()), 13432 *this, OCD_AllCandidates, Args); 13433 // FIXME: Leaking incoming expressions! 13434 return ExprError(); 13435 13436 case OR_Ambiguous: 13437 CandidateSet.NoteCandidates( 13438 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13439 PDiag(diag::err_ovl_ambiguous_member_call) 13440 << DeclName << MemExprE->getSourceRange()), 13441 *this, OCD_AllCandidates, Args); 13442 // FIXME: Leaking incoming expressions! 13443 return ExprError(); 13444 13445 case OR_Deleted: 13446 CandidateSet.NoteCandidates( 13447 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13448 PDiag(diag::err_ovl_deleted_member_call) 13449 << DeclName << MemExprE->getSourceRange()), 13450 *this, OCD_AllCandidates, Args); 13451 // FIXME: Leaking incoming expressions! 13452 return ExprError(); 13453 } 13454 13455 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13456 13457 // If overload resolution picked a static member, build a 13458 // non-member call based on that function. 13459 if (Method->isStatic()) { 13460 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13461 RParenLoc); 13462 } 13463 13464 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13465 } 13466 13467 QualType ResultType = Method->getReturnType(); 13468 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13469 ResultType = ResultType.getNonLValueExprType(Context); 13470 13471 assert(Method && "Member call to something that isn't a method?"); 13472 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13473 CXXMemberCallExpr *TheCall = 13474 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13475 RParenLoc, Proto->getNumParams()); 13476 13477 // Check for a valid return type. 13478 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13479 TheCall, Method)) 13480 return ExprError(); 13481 13482 // Convert the object argument (for a non-static member function call). 13483 // We only need to do this if there was actually an overload; otherwise 13484 // it was done at lookup. 13485 if (!Method->isStatic()) { 13486 ExprResult ObjectArg = 13487 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13488 FoundDecl, Method); 13489 if (ObjectArg.isInvalid()) 13490 return ExprError(); 13491 MemExpr->setBase(ObjectArg.get()); 13492 } 13493 13494 // Convert the rest of the arguments 13495 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13496 RParenLoc)) 13497 return ExprError(); 13498 13499 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13500 13501 if (CheckFunctionCall(Method, TheCall, Proto)) 13502 return ExprError(); 13503 13504 // In the case the method to call was not selected by the overloading 13505 // resolution process, we still need to handle the enable_if attribute. Do 13506 // that here, so it will not hide previous -- and more relevant -- errors. 13507 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13508 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13509 Diag(MemE->getMemberLoc(), 13510 diag::err_ovl_no_viable_member_function_in_call) 13511 << Method << Method->getSourceRange(); 13512 Diag(Method->getLocation(), 13513 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13514 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13515 return ExprError(); 13516 } 13517 } 13518 13519 if ((isa<CXXConstructorDecl>(CurContext) || 13520 isa<CXXDestructorDecl>(CurContext)) && 13521 TheCall->getMethodDecl()->isPure()) { 13522 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13523 13524 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13525 MemExpr->performsVirtualDispatch(getLangOpts())) { 13526 Diag(MemExpr->getBeginLoc(), 13527 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13528 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13529 << MD->getParent()->getDeclName(); 13530 13531 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13532 if (getLangOpts().AppleKext) 13533 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13534 << MD->getParent()->getDeclName() << MD->getDeclName(); 13535 } 13536 } 13537 13538 if (CXXDestructorDecl *DD = 13539 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13540 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13541 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13542 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13543 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13544 MemExpr->getMemberLoc()); 13545 } 13546 13547 return MaybeBindToTemporary(TheCall); 13548 } 13549 13550 /// BuildCallToObjectOfClassType - Build a call to an object of class 13551 /// type (C++ [over.call.object]), which can end up invoking an 13552 /// overloaded function call operator (@c operator()) or performing a 13553 /// user-defined conversion on the object argument. 13554 ExprResult 13555 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13556 SourceLocation LParenLoc, 13557 MultiExprArg Args, 13558 SourceLocation RParenLoc) { 13559 if (checkPlaceholderForOverload(*this, Obj)) 13560 return ExprError(); 13561 ExprResult Object = Obj; 13562 13563 UnbridgedCastsSet UnbridgedCasts; 13564 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13565 return ExprError(); 13566 13567 assert(Object.get()->getType()->isRecordType() && 13568 "Requires object type argument"); 13569 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13570 13571 // C++ [over.call.object]p1: 13572 // If the primary-expression E in the function call syntax 13573 // evaluates to a class object of type "cv T", then the set of 13574 // candidate functions includes at least the function call 13575 // operators of T. The function call operators of T are obtained by 13576 // ordinary lookup of the name operator() in the context of 13577 // (E).operator(). 13578 OverloadCandidateSet CandidateSet(LParenLoc, 13579 OverloadCandidateSet::CSK_Operator); 13580 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13581 13582 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13583 diag::err_incomplete_object_call, Object.get())) 13584 return true; 13585 13586 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13587 LookupQualifiedName(R, Record->getDecl()); 13588 R.suppressDiagnostics(); 13589 13590 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13591 Oper != OperEnd; ++Oper) { 13592 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13593 Object.get()->Classify(Context), Args, CandidateSet, 13594 /*SuppressUserConversion=*/false); 13595 } 13596 13597 // C++ [over.call.object]p2: 13598 // In addition, for each (non-explicit in C++0x) conversion function 13599 // declared in T of the form 13600 // 13601 // operator conversion-type-id () cv-qualifier; 13602 // 13603 // where cv-qualifier is the same cv-qualification as, or a 13604 // greater cv-qualification than, cv, and where conversion-type-id 13605 // denotes the type "pointer to function of (P1,...,Pn) returning 13606 // R", or the type "reference to pointer to function of 13607 // (P1,...,Pn) returning R", or the type "reference to function 13608 // of (P1,...,Pn) returning R", a surrogate call function [...] 13609 // is also considered as a candidate function. Similarly, 13610 // surrogate call functions are added to the set of candidate 13611 // functions for each conversion function declared in an 13612 // accessible base class provided the function is not hidden 13613 // within T by another intervening declaration. 13614 const auto &Conversions = 13615 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13616 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13617 NamedDecl *D = *I; 13618 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13619 if (isa<UsingShadowDecl>(D)) 13620 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13621 13622 // Skip over templated conversion functions; they aren't 13623 // surrogates. 13624 if (isa<FunctionTemplateDecl>(D)) 13625 continue; 13626 13627 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13628 if (!Conv->isExplicit()) { 13629 // Strip the reference type (if any) and then the pointer type (if 13630 // any) to get down to what might be a function type. 13631 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13632 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13633 ConvType = ConvPtrType->getPointeeType(); 13634 13635 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13636 { 13637 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13638 Object.get(), Args, CandidateSet); 13639 } 13640 } 13641 } 13642 13643 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13644 13645 // Perform overload resolution. 13646 OverloadCandidateSet::iterator Best; 13647 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13648 Best)) { 13649 case OR_Success: 13650 // Overload resolution succeeded; we'll build the appropriate call 13651 // below. 13652 break; 13653 13654 case OR_No_Viable_Function: { 13655 PartialDiagnostic PD = 13656 CandidateSet.empty() 13657 ? (PDiag(diag::err_ovl_no_oper) 13658 << Object.get()->getType() << /*call*/ 1 13659 << Object.get()->getSourceRange()) 13660 : (PDiag(diag::err_ovl_no_viable_object_call) 13661 << Object.get()->getType() << Object.get()->getSourceRange()); 13662 CandidateSet.NoteCandidates( 13663 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 13664 OCD_AllCandidates, Args); 13665 break; 13666 } 13667 case OR_Ambiguous: 13668 CandidateSet.NoteCandidates( 13669 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13670 PDiag(diag::err_ovl_ambiguous_object_call) 13671 << Object.get()->getType() 13672 << Object.get()->getSourceRange()), 13673 *this, OCD_ViableCandidates, Args); 13674 break; 13675 13676 case OR_Deleted: 13677 CandidateSet.NoteCandidates( 13678 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13679 PDiag(diag::err_ovl_deleted_object_call) 13680 << Object.get()->getType() 13681 << Object.get()->getSourceRange()), 13682 *this, OCD_AllCandidates, Args); 13683 break; 13684 } 13685 13686 if (Best == CandidateSet.end()) 13687 return true; 13688 13689 UnbridgedCasts.restore(); 13690 13691 if (Best->Function == nullptr) { 13692 // Since there is no function declaration, this is one of the 13693 // surrogate candidates. Dig out the conversion function. 13694 CXXConversionDecl *Conv 13695 = cast<CXXConversionDecl>( 13696 Best->Conversions[0].UserDefined.ConversionFunction); 13697 13698 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13699 Best->FoundDecl); 13700 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13701 return ExprError(); 13702 assert(Conv == Best->FoundDecl.getDecl() && 13703 "Found Decl & conversion-to-functionptr should be same, right?!"); 13704 // We selected one of the surrogate functions that converts the 13705 // object parameter to a function pointer. Perform the conversion 13706 // on the object argument, then let BuildCallExpr finish the job. 13707 13708 // Create an implicit member expr to refer to the conversion operator. 13709 // and then call it. 13710 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13711 Conv, HadMultipleCandidates); 13712 if (Call.isInvalid()) 13713 return ExprError(); 13714 // Record usage of conversion in an implicit cast. 13715 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13716 CK_UserDefinedConversion, Call.get(), 13717 nullptr, VK_RValue); 13718 13719 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13720 } 13721 13722 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13723 13724 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13725 // that calls this method, using Object for the implicit object 13726 // parameter and passing along the remaining arguments. 13727 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13728 13729 // An error diagnostic has already been printed when parsing the declaration. 13730 if (Method->isInvalidDecl()) 13731 return ExprError(); 13732 13733 const FunctionProtoType *Proto = 13734 Method->getType()->getAs<FunctionProtoType>(); 13735 13736 unsigned NumParams = Proto->getNumParams(); 13737 13738 DeclarationNameInfo OpLocInfo( 13739 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13740 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13741 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13742 Obj, HadMultipleCandidates, 13743 OpLocInfo.getLoc(), 13744 OpLocInfo.getInfo()); 13745 if (NewFn.isInvalid()) 13746 return true; 13747 13748 // The number of argument slots to allocate in the call. If we have default 13749 // arguments we need to allocate space for them as well. We additionally 13750 // need one more slot for the object parameter. 13751 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13752 13753 // Build the full argument list for the method call (the implicit object 13754 // parameter is placed at the beginning of the list). 13755 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13756 13757 bool IsError = false; 13758 13759 // Initialize the implicit object parameter. 13760 ExprResult ObjRes = 13761 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13762 Best->FoundDecl, Method); 13763 if (ObjRes.isInvalid()) 13764 IsError = true; 13765 else 13766 Object = ObjRes; 13767 MethodArgs[0] = Object.get(); 13768 13769 // Check the argument types. 13770 for (unsigned i = 0; i != NumParams; i++) { 13771 Expr *Arg; 13772 if (i < Args.size()) { 13773 Arg = Args[i]; 13774 13775 // Pass the argument. 13776 13777 ExprResult InputInit 13778 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13779 Context, 13780 Method->getParamDecl(i)), 13781 SourceLocation(), Arg); 13782 13783 IsError |= InputInit.isInvalid(); 13784 Arg = InputInit.getAs<Expr>(); 13785 } else { 13786 ExprResult DefArg 13787 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13788 if (DefArg.isInvalid()) { 13789 IsError = true; 13790 break; 13791 } 13792 13793 Arg = DefArg.getAs<Expr>(); 13794 } 13795 13796 MethodArgs[i + 1] = Arg; 13797 } 13798 13799 // If this is a variadic call, handle args passed through "...". 13800 if (Proto->isVariadic()) { 13801 // Promote the arguments (C99 6.5.2.2p7). 13802 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13803 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13804 nullptr); 13805 IsError |= Arg.isInvalid(); 13806 MethodArgs[i + 1] = Arg.get(); 13807 } 13808 } 13809 13810 if (IsError) 13811 return true; 13812 13813 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13814 13815 // Once we've built TheCall, all of the expressions are properly owned. 13816 QualType ResultTy = Method->getReturnType(); 13817 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13818 ResultTy = ResultTy.getNonLValueExprType(Context); 13819 13820 CXXOperatorCallExpr *TheCall = 13821 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13822 ResultTy, VK, RParenLoc, FPOptions()); 13823 13824 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13825 return true; 13826 13827 if (CheckFunctionCall(Method, TheCall, Proto)) 13828 return true; 13829 13830 return MaybeBindToTemporary(TheCall); 13831 } 13832 13833 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13834 /// (if one exists), where @c Base is an expression of class type and 13835 /// @c Member is the name of the member we're trying to find. 13836 ExprResult 13837 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13838 bool *NoArrowOperatorFound) { 13839 assert(Base->getType()->isRecordType() && 13840 "left-hand side must have class type"); 13841 13842 if (checkPlaceholderForOverload(*this, Base)) 13843 return ExprError(); 13844 13845 SourceLocation Loc = Base->getExprLoc(); 13846 13847 // C++ [over.ref]p1: 13848 // 13849 // [...] An expression x->m is interpreted as (x.operator->())->m 13850 // for a class object x of type T if T::operator->() exists and if 13851 // the operator is selected as the best match function by the 13852 // overload resolution mechanism (13.3). 13853 DeclarationName OpName = 13854 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13855 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13856 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13857 13858 if (RequireCompleteType(Loc, Base->getType(), 13859 diag::err_typecheck_incomplete_tag, Base)) 13860 return ExprError(); 13861 13862 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13863 LookupQualifiedName(R, BaseRecord->getDecl()); 13864 R.suppressDiagnostics(); 13865 13866 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13867 Oper != OperEnd; ++Oper) { 13868 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13869 None, CandidateSet, /*SuppressUserConversion=*/false); 13870 } 13871 13872 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13873 13874 // Perform overload resolution. 13875 OverloadCandidateSet::iterator Best; 13876 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13877 case OR_Success: 13878 // Overload resolution succeeded; we'll build the call below. 13879 break; 13880 13881 case OR_No_Viable_Function: { 13882 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 13883 if (CandidateSet.empty()) { 13884 QualType BaseType = Base->getType(); 13885 if (NoArrowOperatorFound) { 13886 // Report this specific error to the caller instead of emitting a 13887 // diagnostic, as requested. 13888 *NoArrowOperatorFound = true; 13889 return ExprError(); 13890 } 13891 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13892 << BaseType << Base->getSourceRange(); 13893 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13894 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13895 << FixItHint::CreateReplacement(OpLoc, "."); 13896 } 13897 } else 13898 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13899 << "operator->" << Base->getSourceRange(); 13900 CandidateSet.NoteCandidates(*this, Base, Cands); 13901 return ExprError(); 13902 } 13903 case OR_Ambiguous: 13904 CandidateSet.NoteCandidates( 13905 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 13906 << "->" << Base->getType() 13907 << Base->getSourceRange()), 13908 *this, OCD_ViableCandidates, Base); 13909 return ExprError(); 13910 13911 case OR_Deleted: 13912 CandidateSet.NoteCandidates( 13913 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13914 << "->" << Base->getSourceRange()), 13915 *this, OCD_AllCandidates, Base); 13916 return ExprError(); 13917 } 13918 13919 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13920 13921 // Convert the object parameter. 13922 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13923 ExprResult BaseResult = 13924 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13925 Best->FoundDecl, Method); 13926 if (BaseResult.isInvalid()) 13927 return ExprError(); 13928 Base = BaseResult.get(); 13929 13930 // Build the operator call. 13931 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13932 Base, HadMultipleCandidates, OpLoc); 13933 if (FnExpr.isInvalid()) 13934 return ExprError(); 13935 13936 QualType ResultTy = Method->getReturnType(); 13937 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13938 ResultTy = ResultTy.getNonLValueExprType(Context); 13939 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13940 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13941 13942 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13943 return ExprError(); 13944 13945 if (CheckFunctionCall(Method, TheCall, 13946 Method->getType()->castAs<FunctionProtoType>())) 13947 return ExprError(); 13948 13949 return MaybeBindToTemporary(TheCall); 13950 } 13951 13952 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13953 /// a literal operator described by the provided lookup results. 13954 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13955 DeclarationNameInfo &SuffixInfo, 13956 ArrayRef<Expr*> Args, 13957 SourceLocation LitEndLoc, 13958 TemplateArgumentListInfo *TemplateArgs) { 13959 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13960 13961 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13962 OverloadCandidateSet::CSK_Normal); 13963 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 13964 TemplateArgs); 13965 13966 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13967 13968 // Perform overload resolution. This will usually be trivial, but might need 13969 // to perform substitutions for a literal operator template. 13970 OverloadCandidateSet::iterator Best; 13971 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13972 case OR_Success: 13973 case OR_Deleted: 13974 break; 13975 13976 case OR_No_Viable_Function: 13977 CandidateSet.NoteCandidates( 13978 PartialDiagnosticAt(UDSuffixLoc, 13979 PDiag(diag::err_ovl_no_viable_function_in_call) 13980 << R.getLookupName()), 13981 *this, OCD_AllCandidates, Args); 13982 return ExprError(); 13983 13984 case OR_Ambiguous: 13985 CandidateSet.NoteCandidates( 13986 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 13987 << R.getLookupName()), 13988 *this, OCD_ViableCandidates, Args); 13989 return ExprError(); 13990 } 13991 13992 FunctionDecl *FD = Best->Function; 13993 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13994 nullptr, HadMultipleCandidates, 13995 SuffixInfo.getLoc(), 13996 SuffixInfo.getInfo()); 13997 if (Fn.isInvalid()) 13998 return true; 13999 14000 // Check the argument types. This should almost always be a no-op, except 14001 // that array-to-pointer decay is applied to string literals. 14002 Expr *ConvArgs[2]; 14003 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14004 ExprResult InputInit = PerformCopyInitialization( 14005 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14006 SourceLocation(), Args[ArgIdx]); 14007 if (InputInit.isInvalid()) 14008 return true; 14009 ConvArgs[ArgIdx] = InputInit.get(); 14010 } 14011 14012 QualType ResultTy = FD->getReturnType(); 14013 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14014 ResultTy = ResultTy.getNonLValueExprType(Context); 14015 14016 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14017 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14018 VK, LitEndLoc, UDSuffixLoc); 14019 14020 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14021 return ExprError(); 14022 14023 if (CheckFunctionCall(FD, UDL, nullptr)) 14024 return ExprError(); 14025 14026 return MaybeBindToTemporary(UDL); 14027 } 14028 14029 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14030 /// given LookupResult is non-empty, it is assumed to describe a member which 14031 /// will be invoked. Otherwise, the function will be found via argument 14032 /// dependent lookup. 14033 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14034 /// otherwise CallExpr is set to ExprError() and some non-success value 14035 /// is returned. 14036 Sema::ForRangeStatus 14037 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14038 SourceLocation RangeLoc, 14039 const DeclarationNameInfo &NameInfo, 14040 LookupResult &MemberLookup, 14041 OverloadCandidateSet *CandidateSet, 14042 Expr *Range, ExprResult *CallExpr) { 14043 Scope *S = nullptr; 14044 14045 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14046 if (!MemberLookup.empty()) { 14047 ExprResult MemberRef = 14048 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14049 /*IsPtr=*/false, CXXScopeSpec(), 14050 /*TemplateKWLoc=*/SourceLocation(), 14051 /*FirstQualifierInScope=*/nullptr, 14052 MemberLookup, 14053 /*TemplateArgs=*/nullptr, S); 14054 if (MemberRef.isInvalid()) { 14055 *CallExpr = ExprError(); 14056 return FRS_DiagnosticIssued; 14057 } 14058 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14059 if (CallExpr->isInvalid()) { 14060 *CallExpr = ExprError(); 14061 return FRS_DiagnosticIssued; 14062 } 14063 } else { 14064 UnresolvedSet<0> FoundNames; 14065 UnresolvedLookupExpr *Fn = 14066 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14067 NestedNameSpecifierLoc(), NameInfo, 14068 /*NeedsADL=*/true, /*Overloaded=*/false, 14069 FoundNames.begin(), FoundNames.end()); 14070 14071 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14072 CandidateSet, CallExpr); 14073 if (CandidateSet->empty() || CandidateSetError) { 14074 *CallExpr = ExprError(); 14075 return FRS_NoViableFunction; 14076 } 14077 OverloadCandidateSet::iterator Best; 14078 OverloadingResult OverloadResult = 14079 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14080 14081 if (OverloadResult == OR_No_Viable_Function) { 14082 *CallExpr = ExprError(); 14083 return FRS_NoViableFunction; 14084 } 14085 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14086 Loc, nullptr, CandidateSet, &Best, 14087 OverloadResult, 14088 /*AllowTypoCorrection=*/false); 14089 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14090 *CallExpr = ExprError(); 14091 return FRS_DiagnosticIssued; 14092 } 14093 } 14094 return FRS_Success; 14095 } 14096 14097 14098 /// FixOverloadedFunctionReference - E is an expression that refers to 14099 /// a C++ overloaded function (possibly with some parentheses and 14100 /// perhaps a '&' around it). We have resolved the overloaded function 14101 /// to the function declaration Fn, so patch up the expression E to 14102 /// refer (possibly indirectly) to Fn. Returns the new expr. 14103 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14104 FunctionDecl *Fn) { 14105 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14106 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14107 Found, Fn); 14108 if (SubExpr == PE->getSubExpr()) 14109 return PE; 14110 14111 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14112 } 14113 14114 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14115 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14116 Found, Fn); 14117 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14118 SubExpr->getType()) && 14119 "Implicit cast type cannot be determined from overload"); 14120 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14121 if (SubExpr == ICE->getSubExpr()) 14122 return ICE; 14123 14124 return ImplicitCastExpr::Create(Context, ICE->getType(), 14125 ICE->getCastKind(), 14126 SubExpr, nullptr, 14127 ICE->getValueKind()); 14128 } 14129 14130 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14131 if (!GSE->isResultDependent()) { 14132 Expr *SubExpr = 14133 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14134 if (SubExpr == GSE->getResultExpr()) 14135 return GSE; 14136 14137 // Replace the resulting type information before rebuilding the generic 14138 // selection expression. 14139 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14140 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14141 unsigned ResultIdx = GSE->getResultIndex(); 14142 AssocExprs[ResultIdx] = SubExpr; 14143 14144 return GenericSelectionExpr::Create( 14145 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14146 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14147 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14148 ResultIdx); 14149 } 14150 // Rather than fall through to the unreachable, return the original generic 14151 // selection expression. 14152 return GSE; 14153 } 14154 14155 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14156 assert(UnOp->getOpcode() == UO_AddrOf && 14157 "Can only take the address of an overloaded function"); 14158 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14159 if (Method->isStatic()) { 14160 // Do nothing: static member functions aren't any different 14161 // from non-member functions. 14162 } else { 14163 // Fix the subexpression, which really has to be an 14164 // UnresolvedLookupExpr holding an overloaded member function 14165 // or template. 14166 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14167 Found, Fn); 14168 if (SubExpr == UnOp->getSubExpr()) 14169 return UnOp; 14170 14171 assert(isa<DeclRefExpr>(SubExpr) 14172 && "fixed to something other than a decl ref"); 14173 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14174 && "fixed to a member ref with no nested name qualifier"); 14175 14176 // We have taken the address of a pointer to member 14177 // function. Perform the computation here so that we get the 14178 // appropriate pointer to member type. 14179 QualType ClassType 14180 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14181 QualType MemPtrType 14182 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14183 // Under the MS ABI, lock down the inheritance model now. 14184 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14185 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14186 14187 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 14188 VK_RValue, OK_Ordinary, 14189 UnOp->getOperatorLoc(), false); 14190 } 14191 } 14192 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14193 Found, Fn); 14194 if (SubExpr == UnOp->getSubExpr()) 14195 return UnOp; 14196 14197 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 14198 Context.getPointerType(SubExpr->getType()), 14199 VK_RValue, OK_Ordinary, 14200 UnOp->getOperatorLoc(), false); 14201 } 14202 14203 // C++ [except.spec]p17: 14204 // An exception-specification is considered to be needed when: 14205 // - in an expression the function is the unique lookup result or the 14206 // selected member of a set of overloaded functions 14207 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 14208 ResolveExceptionSpec(E->getExprLoc(), FPT); 14209 14210 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14211 // FIXME: avoid copy. 14212 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14213 if (ULE->hasExplicitTemplateArgs()) { 14214 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14215 TemplateArgs = &TemplateArgsBuffer; 14216 } 14217 14218 DeclRefExpr *DRE = 14219 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14220 ULE->getQualifierLoc(), Found.getDecl(), 14221 ULE->getTemplateKeywordLoc(), TemplateArgs); 14222 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14223 return DRE; 14224 } 14225 14226 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14227 // FIXME: avoid copy. 14228 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14229 if (MemExpr->hasExplicitTemplateArgs()) { 14230 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14231 TemplateArgs = &TemplateArgsBuffer; 14232 } 14233 14234 Expr *Base; 14235 14236 // If we're filling in a static method where we used to have an 14237 // implicit member access, rewrite to a simple decl ref. 14238 if (MemExpr->isImplicitAccess()) { 14239 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14240 DeclRefExpr *DRE = BuildDeclRefExpr( 14241 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14242 MemExpr->getQualifierLoc(), Found.getDecl(), 14243 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14244 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14245 return DRE; 14246 } else { 14247 SourceLocation Loc = MemExpr->getMemberLoc(); 14248 if (MemExpr->getQualifier()) 14249 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14250 Base = 14251 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14252 } 14253 } else 14254 Base = MemExpr->getBase(); 14255 14256 ExprValueKind valueKind; 14257 QualType type; 14258 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14259 valueKind = VK_LValue; 14260 type = Fn->getType(); 14261 } else { 14262 valueKind = VK_RValue; 14263 type = Context.BoundMemberTy; 14264 } 14265 14266 return BuildMemberExpr( 14267 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14268 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14269 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14270 type, valueKind, OK_Ordinary, TemplateArgs); 14271 } 14272 14273 llvm_unreachable("Invalid reference to overloaded function"); 14274 } 14275 14276 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14277 DeclAccessPair Found, 14278 FunctionDecl *Fn) { 14279 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14280 } 14281