1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.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 bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 64 VK_LValue, Loc, LocInfo); 65 if (HadMultipleCandidates) 66 DRE->setHadMultipleCandidates(true); 67 68 S.MarkDeclRefReferenced(DRE); 69 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 70 CK_FunctionToPointerDecay); 71 } 72 73 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 74 bool InOverloadResolution, 75 StandardConversionSequence &SCS, 76 bool CStyle, 77 bool AllowObjCWritebackConversion); 78 79 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 80 QualType &ToType, 81 bool InOverloadResolution, 82 StandardConversionSequence &SCS, 83 bool CStyle); 84 static OverloadingResult 85 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 86 UserDefinedConversionSequence& User, 87 OverloadCandidateSet& Conversions, 88 bool AllowExplicit, 89 bool AllowObjCConversionOnExplicit); 90 91 92 static ImplicitConversionSequence::CompareKind 93 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 94 const StandardConversionSequence& SCS1, 95 const StandardConversionSequence& SCS2); 96 97 static ImplicitConversionSequence::CompareKind 98 CompareQualificationConversions(Sema &S, 99 const StandardConversionSequence& SCS1, 100 const StandardConversionSequence& SCS2); 101 102 static ImplicitConversionSequence::CompareKind 103 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 104 const StandardConversionSequence& SCS1, 105 const StandardConversionSequence& SCS2); 106 107 /// GetConversionRank - Retrieve the implicit conversion rank 108 /// corresponding to the given implicit conversion kind. 109 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 110 static const ImplicitConversionRank 111 Rank[(int)ICK_Num_Conversion_Kinds] = { 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Promotion, 119 ICR_Promotion, 120 ICR_Promotion, 121 ICR_Conversion, 122 ICR_Conversion, 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_Complex_Real_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Writeback_Conversion, 136 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 137 // it was omitted by the patch that added 138 // ICK_Zero_Event_Conversion 139 ICR_C_Conversion 140 }; 141 return Rank[(int)Kind]; 142 } 143 144 /// GetImplicitConversionName - Return the name of this kind of 145 /// implicit conversion. 146 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 147 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 148 "No conversion", 149 "Lvalue-to-rvalue", 150 "Array-to-pointer", 151 "Function-to-pointer", 152 "Noreturn adjustment", 153 "Qualification", 154 "Integral promotion", 155 "Floating point promotion", 156 "Complex promotion", 157 "Integral conversion", 158 "Floating conversion", 159 "Complex conversion", 160 "Floating-integral conversion", 161 "Pointer conversion", 162 "Pointer-to-member conversion", 163 "Boolean conversion", 164 "Compatible-types conversion", 165 "Derived-to-base conversion", 166 "Vector conversion", 167 "Vector splat", 168 "Complex-real conversion", 169 "Block Pointer conversion", 170 "Transparent Union Conversion", 171 "Writeback conversion", 172 "OpenCL Zero Event Conversion", 173 "C specific type conversion" 174 }; 175 return Name[Kind]; 176 } 177 178 /// StandardConversionSequence - Set the standard conversion 179 /// sequence to the identity conversion. 180 void StandardConversionSequence::setAsIdentityConversion() { 181 First = ICK_Identity; 182 Second = ICK_Identity; 183 Third = ICK_Identity; 184 DeprecatedStringLiteralToCharPtr = false; 185 QualificationIncludesObjCLifetime = false; 186 ReferenceBinding = false; 187 DirectBinding = false; 188 IsLvalueReference = true; 189 BindsToFunctionLvalue = false; 190 BindsToRvalue = false; 191 BindsImplicitObjectArgumentWithoutRefQualifier = false; 192 ObjCLifetimeConversionBinding = false; 193 CopyConstructor = nullptr; 194 } 195 196 /// getRank - Retrieve the rank of this standard conversion sequence 197 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 198 /// implicit conversions. 199 ImplicitConversionRank StandardConversionSequence::getRank() const { 200 ImplicitConversionRank Rank = ICR_Exact_Match; 201 if (GetConversionRank(First) > Rank) 202 Rank = GetConversionRank(First); 203 if (GetConversionRank(Second) > Rank) 204 Rank = GetConversionRank(Second); 205 if (GetConversionRank(Third) > Rank) 206 Rank = GetConversionRank(Third); 207 return Rank; 208 } 209 210 /// isPointerConversionToBool - Determines whether this conversion is 211 /// a conversion of a pointer or pointer-to-member to bool. This is 212 /// used as part of the ranking of standard conversion sequences 213 /// (C++ 13.3.3.2p4). 214 bool StandardConversionSequence::isPointerConversionToBool() const { 215 // Note that FromType has not necessarily been transformed by the 216 // array-to-pointer or function-to-pointer implicit conversions, so 217 // check for their presence as well as checking whether FromType is 218 // a pointer. 219 if (getToType(1)->isBooleanType() && 220 (getFromType()->isPointerType() || 221 getFromType()->isObjCObjectPointerType() || 222 getFromType()->isBlockPointerType() || 223 getFromType()->isNullPtrType() || 224 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 225 return true; 226 227 return false; 228 } 229 230 /// isPointerConversionToVoidPointer - Determines whether this 231 /// conversion is a conversion of a pointer to a void pointer. This is 232 /// used as part of the ranking of standard conversion sequences (C++ 233 /// 13.3.3.2p4). 234 bool 235 StandardConversionSequence:: 236 isPointerConversionToVoidPointer(ASTContext& Context) const { 237 QualType FromType = getFromType(); 238 QualType ToType = getToType(1); 239 240 // Note that FromType has not necessarily been transformed by the 241 // array-to-pointer implicit conversion, so check for its presence 242 // and redo the conversion to get a pointer. 243 if (First == ICK_Array_To_Pointer) 244 FromType = Context.getArrayDecayedType(FromType); 245 246 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 247 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 248 return ToPtrType->getPointeeType()->isVoidType(); 249 250 return false; 251 } 252 253 /// Skip any implicit casts which could be either part of a narrowing conversion 254 /// or after one in an implicit conversion. 255 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 256 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 257 switch (ICE->getCastKind()) { 258 case CK_NoOp: 259 case CK_IntegralCast: 260 case CK_IntegralToBoolean: 261 case CK_IntegralToFloating: 262 case CK_BooleanToSignedIntegral: 263 case CK_FloatingToIntegral: 264 case CK_FloatingToBoolean: 265 case CK_FloatingCast: 266 Converted = ICE->getSubExpr(); 267 continue; 268 269 default: 270 return Converted; 271 } 272 } 273 274 return Converted; 275 } 276 277 /// Check if this standard conversion sequence represents a narrowing 278 /// conversion, according to C++11 [dcl.init.list]p7. 279 /// 280 /// \param Ctx The AST context. 281 /// \param Converted The result of applying this standard conversion sequence. 282 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 283 /// value of the expression prior to the narrowing conversion. 284 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 285 /// type of the expression prior to the narrowing conversion. 286 NarrowingKind 287 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 288 const Expr *Converted, 289 APValue &ConstantValue, 290 QualType &ConstantType) const { 291 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 292 293 // C++11 [dcl.init.list]p7: 294 // A narrowing conversion is an implicit conversion ... 295 QualType FromType = getToType(0); 296 QualType ToType = getToType(1); 297 298 // A conversion to an enumeration type is narrowing if the conversion to 299 // the underlying type is narrowing. This only arises for expressions of 300 // the form 'Enum{init}'. 301 if (auto *ET = ToType->getAs<EnumType>()) 302 ToType = ET->getDecl()->getIntegerType(); 303 304 switch (Second) { 305 // 'bool' is an integral type; dispatch to the right place to handle it. 306 case ICK_Boolean_Conversion: 307 if (FromType->isRealFloatingType()) 308 goto FloatingIntegralConversion; 309 if (FromType->isIntegralOrUnscopedEnumerationType()) 310 goto IntegralConversion; 311 // Boolean conversions can be from pointers and pointers to members 312 // [conv.bool], and those aren't considered narrowing conversions. 313 return NK_Not_Narrowing; 314 315 // -- from a floating-point type to an integer type, or 316 // 317 // -- from an integer type or unscoped enumeration type to a floating-point 318 // type, except where the source is a constant expression and the actual 319 // value after conversion will fit into the target type and will produce 320 // the original value when converted back to the original type, or 321 case ICK_Floating_Integral: 322 FloatingIntegralConversion: 323 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 324 return NK_Type_Narrowing; 325 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 326 llvm::APSInt IntConstantValue; 327 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 328 if (Initializer && 329 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 330 // Convert the integer to the floating type. 331 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 332 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 333 llvm::APFloat::rmNearestTiesToEven); 334 // And back. 335 llvm::APSInt ConvertedValue = IntConstantValue; 336 bool ignored; 337 Result.convertToInteger(ConvertedValue, 338 llvm::APFloat::rmTowardZero, &ignored); 339 // If the resulting value is different, this was a narrowing conversion. 340 if (IntConstantValue != ConvertedValue) { 341 ConstantValue = APValue(IntConstantValue); 342 ConstantType = Initializer->getType(); 343 return NK_Constant_Narrowing; 344 } 345 } else { 346 // Variables are always narrowings. 347 return NK_Variable_Narrowing; 348 } 349 } 350 return NK_Not_Narrowing; 351 352 // -- from long double to double or float, or from double to float, except 353 // where the source is a constant expression and the actual value after 354 // conversion is within the range of values that can be represented (even 355 // if it cannot be represented exactly), or 356 case ICK_Floating_Conversion: 357 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 358 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 359 // FromType is larger than ToType. 360 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 361 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 362 // Constant! 363 assert(ConstantValue.isFloat()); 364 llvm::APFloat FloatVal = ConstantValue.getFloat(); 365 // Convert the source value into the target type. 366 bool ignored; 367 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 368 Ctx.getFloatTypeSemantics(ToType), 369 llvm::APFloat::rmNearestTiesToEven, &ignored); 370 // If there was no overflow, the source value is within the range of 371 // values that can be represented. 372 if (ConvertStatus & llvm::APFloat::opOverflow) { 373 ConstantType = Initializer->getType(); 374 return NK_Constant_Narrowing; 375 } 376 } else { 377 return NK_Variable_Narrowing; 378 } 379 } 380 return NK_Not_Narrowing; 381 382 // -- from an integer type or unscoped enumeration type to an integer type 383 // that cannot represent all the values of the original type, except where 384 // the source is a constant expression and the actual value after 385 // conversion will fit into the target type and will produce the original 386 // value when converted back to the original type. 387 case ICK_Integral_Conversion: 388 IntegralConversion: { 389 assert(FromType->isIntegralOrUnscopedEnumerationType()); 390 assert(ToType->isIntegralOrUnscopedEnumerationType()); 391 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 392 const unsigned FromWidth = Ctx.getIntWidth(FromType); 393 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 394 const unsigned ToWidth = Ctx.getIntWidth(ToType); 395 396 if (FromWidth > ToWidth || 397 (FromWidth == ToWidth && FromSigned != ToSigned) || 398 (FromSigned && !ToSigned)) { 399 // Not all values of FromType can be represented in ToType. 400 llvm::APSInt InitializerValue; 401 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 402 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 403 // Such conversions on variables are always narrowing. 404 return NK_Variable_Narrowing; 405 } 406 bool Narrowing = false; 407 if (FromWidth < ToWidth) { 408 // Negative -> unsigned is narrowing. Otherwise, more bits is never 409 // narrowing. 410 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 411 Narrowing = true; 412 } else { 413 // Add a bit to the InitializerValue so we don't have to worry about 414 // signed vs. unsigned comparisons. 415 InitializerValue = InitializerValue.extend( 416 InitializerValue.getBitWidth() + 1); 417 // Convert the initializer to and from the target width and signed-ness. 418 llvm::APSInt ConvertedValue = InitializerValue; 419 ConvertedValue = ConvertedValue.trunc(ToWidth); 420 ConvertedValue.setIsSigned(ToSigned); 421 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 422 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 423 // If the result is different, this was a narrowing conversion. 424 if (ConvertedValue != InitializerValue) 425 Narrowing = true; 426 } 427 if (Narrowing) { 428 ConstantType = Initializer->getType(); 429 ConstantValue = APValue(InitializerValue); 430 return NK_Constant_Narrowing; 431 } 432 } 433 return NK_Not_Narrowing; 434 } 435 436 default: 437 // Other kinds of conversions are not narrowings. 438 return NK_Not_Narrowing; 439 } 440 } 441 442 /// dump - Print this standard conversion sequence to standard 443 /// error. Useful for debugging overloading issues. 444 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 445 raw_ostream &OS = llvm::errs(); 446 bool PrintedSomething = false; 447 if (First != ICK_Identity) { 448 OS << GetImplicitConversionName(First); 449 PrintedSomething = true; 450 } 451 452 if (Second != ICK_Identity) { 453 if (PrintedSomething) { 454 OS << " -> "; 455 } 456 OS << GetImplicitConversionName(Second); 457 458 if (CopyConstructor) { 459 OS << " (by copy constructor)"; 460 } else if (DirectBinding) { 461 OS << " (direct reference binding)"; 462 } else if (ReferenceBinding) { 463 OS << " (reference binding)"; 464 } 465 PrintedSomething = true; 466 } 467 468 if (Third != ICK_Identity) { 469 if (PrintedSomething) { 470 OS << " -> "; 471 } 472 OS << GetImplicitConversionName(Third); 473 PrintedSomething = true; 474 } 475 476 if (!PrintedSomething) { 477 OS << "No conversions required"; 478 } 479 } 480 481 /// dump - Print this user-defined conversion sequence to standard 482 /// error. Useful for debugging overloading issues. 483 void UserDefinedConversionSequence::dump() const { 484 raw_ostream &OS = llvm::errs(); 485 if (Before.First || Before.Second || Before.Third) { 486 Before.dump(); 487 OS << " -> "; 488 } 489 if (ConversionFunction) 490 OS << '\'' << *ConversionFunction << '\''; 491 else 492 OS << "aggregate initialization"; 493 if (After.First || After.Second || After.Third) { 494 OS << " -> "; 495 After.dump(); 496 } 497 } 498 499 /// dump - Print this implicit conversion sequence to standard 500 /// error. Useful for debugging overloading issues. 501 void ImplicitConversionSequence::dump() const { 502 raw_ostream &OS = llvm::errs(); 503 if (isStdInitializerListElement()) 504 OS << "Worst std::initializer_list element conversion: "; 505 switch (ConversionKind) { 506 case StandardConversion: 507 OS << "Standard conversion: "; 508 Standard.dump(); 509 break; 510 case UserDefinedConversion: 511 OS << "User-defined conversion: "; 512 UserDefined.dump(); 513 break; 514 case EllipsisConversion: 515 OS << "Ellipsis conversion"; 516 break; 517 case AmbiguousConversion: 518 OS << "Ambiguous conversion"; 519 break; 520 case BadConversion: 521 OS << "Bad conversion"; 522 break; 523 } 524 525 OS << "\n"; 526 } 527 528 void AmbiguousConversionSequence::construct() { 529 new (&conversions()) ConversionSet(); 530 } 531 532 void AmbiguousConversionSequence::destruct() { 533 conversions().~ConversionSet(); 534 } 535 536 void 537 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 538 FromTypePtr = O.FromTypePtr; 539 ToTypePtr = O.ToTypePtr; 540 new (&conversions()) ConversionSet(O.conversions()); 541 } 542 543 namespace { 544 // Structure used by DeductionFailureInfo to store 545 // template argument information. 546 struct DFIArguments { 547 TemplateArgument FirstArg; 548 TemplateArgument SecondArg; 549 }; 550 // Structure used by DeductionFailureInfo to store 551 // template parameter and template argument information. 552 struct DFIParamWithArguments : DFIArguments { 553 TemplateParameter Param; 554 }; 555 // Structure used by DeductionFailureInfo to store template argument 556 // information and the index of the problematic call argument. 557 struct DFIDeducedMismatchArgs : DFIArguments { 558 TemplateArgumentList *TemplateArgs; 559 unsigned CallArgIndex; 560 }; 561 } 562 563 /// \brief Convert from Sema's representation of template deduction information 564 /// to the form used in overload-candidate information. 565 DeductionFailureInfo 566 clang::MakeDeductionFailureInfo(ASTContext &Context, 567 Sema::TemplateDeductionResult TDK, 568 TemplateDeductionInfo &Info) { 569 DeductionFailureInfo Result; 570 Result.Result = static_cast<unsigned>(TDK); 571 Result.HasDiagnostic = false; 572 switch (TDK) { 573 case Sema::TDK_Success: 574 case Sema::TDK_Invalid: 575 case Sema::TDK_InstantiationDepth: 576 case Sema::TDK_TooManyArguments: 577 case Sema::TDK_TooFewArguments: 578 case Sema::TDK_MiscellaneousDeductionFailure: 579 Result.Data = nullptr; 580 break; 581 582 case Sema::TDK_Incomplete: 583 case Sema::TDK_InvalidExplicitArguments: 584 Result.Data = Info.Param.getOpaqueValue(); 585 break; 586 587 case Sema::TDK_DeducedMismatch: { 588 // FIXME: Should allocate from normal heap so that we can free this later. 589 auto *Saved = new (Context) DFIDeducedMismatchArgs; 590 Saved->FirstArg = Info.FirstArg; 591 Saved->SecondArg = Info.SecondArg; 592 Saved->TemplateArgs = Info.take(); 593 Saved->CallArgIndex = Info.CallArgIndex; 594 Result.Data = Saved; 595 break; 596 } 597 598 case Sema::TDK_NonDeducedMismatch: { 599 // FIXME: Should allocate from normal heap so that we can free this later. 600 DFIArguments *Saved = new (Context) DFIArguments; 601 Saved->FirstArg = Info.FirstArg; 602 Saved->SecondArg = Info.SecondArg; 603 Result.Data = Saved; 604 break; 605 } 606 607 case Sema::TDK_Inconsistent: 608 case Sema::TDK_Underqualified: { 609 // FIXME: Should allocate from normal heap so that we can free this later. 610 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 611 Saved->Param = Info.Param; 612 Saved->FirstArg = Info.FirstArg; 613 Saved->SecondArg = Info.SecondArg; 614 Result.Data = Saved; 615 break; 616 } 617 618 case Sema::TDK_SubstitutionFailure: 619 Result.Data = Info.take(); 620 if (Info.hasSFINAEDiagnostic()) { 621 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 622 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 623 Info.takeSFINAEDiagnostic(*Diag); 624 Result.HasDiagnostic = true; 625 } 626 break; 627 628 case Sema::TDK_FailedOverloadResolution: 629 Result.Data = Info.Expression; 630 break; 631 } 632 633 return Result; 634 } 635 636 void DeductionFailureInfo::Destroy() { 637 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 638 case Sema::TDK_Success: 639 case Sema::TDK_Invalid: 640 case Sema::TDK_InstantiationDepth: 641 case Sema::TDK_Incomplete: 642 case Sema::TDK_TooManyArguments: 643 case Sema::TDK_TooFewArguments: 644 case Sema::TDK_InvalidExplicitArguments: 645 case Sema::TDK_FailedOverloadResolution: 646 break; 647 648 case Sema::TDK_Inconsistent: 649 case Sema::TDK_Underqualified: 650 case Sema::TDK_DeducedMismatch: 651 case Sema::TDK_NonDeducedMismatch: 652 // FIXME: Destroy the data? 653 Data = nullptr; 654 break; 655 656 case Sema::TDK_SubstitutionFailure: 657 // FIXME: Destroy the template argument list? 658 Data = nullptr; 659 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 660 Diag->~PartialDiagnosticAt(); 661 HasDiagnostic = false; 662 } 663 break; 664 665 // Unhandled 666 case Sema::TDK_MiscellaneousDeductionFailure: 667 break; 668 } 669 } 670 671 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 672 if (HasDiagnostic) 673 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 674 return nullptr; 675 } 676 677 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 678 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 679 case Sema::TDK_Success: 680 case Sema::TDK_Invalid: 681 case Sema::TDK_InstantiationDepth: 682 case Sema::TDK_TooManyArguments: 683 case Sema::TDK_TooFewArguments: 684 case Sema::TDK_SubstitutionFailure: 685 case Sema::TDK_DeducedMismatch: 686 case Sema::TDK_NonDeducedMismatch: 687 case Sema::TDK_FailedOverloadResolution: 688 return TemplateParameter(); 689 690 case Sema::TDK_Incomplete: 691 case Sema::TDK_InvalidExplicitArguments: 692 return TemplateParameter::getFromOpaqueValue(Data); 693 694 case Sema::TDK_Inconsistent: 695 case Sema::TDK_Underqualified: 696 return static_cast<DFIParamWithArguments*>(Data)->Param; 697 698 // Unhandled 699 case Sema::TDK_MiscellaneousDeductionFailure: 700 break; 701 } 702 703 return TemplateParameter(); 704 } 705 706 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 707 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 708 case Sema::TDK_Success: 709 case Sema::TDK_Invalid: 710 case Sema::TDK_InstantiationDepth: 711 case Sema::TDK_TooManyArguments: 712 case Sema::TDK_TooFewArguments: 713 case Sema::TDK_Incomplete: 714 case Sema::TDK_InvalidExplicitArguments: 715 case Sema::TDK_Inconsistent: 716 case Sema::TDK_Underqualified: 717 case Sema::TDK_NonDeducedMismatch: 718 case Sema::TDK_FailedOverloadResolution: 719 return nullptr; 720 721 case Sema::TDK_DeducedMismatch: 722 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 723 724 case Sema::TDK_SubstitutionFailure: 725 return static_cast<TemplateArgumentList*>(Data); 726 727 // Unhandled 728 case Sema::TDK_MiscellaneousDeductionFailure: 729 break; 730 } 731 732 return nullptr; 733 } 734 735 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 736 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 737 case Sema::TDK_Success: 738 case Sema::TDK_Invalid: 739 case Sema::TDK_InstantiationDepth: 740 case Sema::TDK_Incomplete: 741 case Sema::TDK_TooManyArguments: 742 case Sema::TDK_TooFewArguments: 743 case Sema::TDK_InvalidExplicitArguments: 744 case Sema::TDK_SubstitutionFailure: 745 case Sema::TDK_FailedOverloadResolution: 746 return nullptr; 747 748 case Sema::TDK_Inconsistent: 749 case Sema::TDK_Underqualified: 750 case Sema::TDK_DeducedMismatch: 751 case Sema::TDK_NonDeducedMismatch: 752 return &static_cast<DFIArguments*>(Data)->FirstArg; 753 754 // Unhandled 755 case Sema::TDK_MiscellaneousDeductionFailure: 756 break; 757 } 758 759 return nullptr; 760 } 761 762 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 764 case Sema::TDK_Success: 765 case Sema::TDK_Invalid: 766 case Sema::TDK_InstantiationDepth: 767 case Sema::TDK_Incomplete: 768 case Sema::TDK_TooManyArguments: 769 case Sema::TDK_TooFewArguments: 770 case Sema::TDK_InvalidExplicitArguments: 771 case Sema::TDK_SubstitutionFailure: 772 case Sema::TDK_FailedOverloadResolution: 773 return nullptr; 774 775 case Sema::TDK_Inconsistent: 776 case Sema::TDK_Underqualified: 777 case Sema::TDK_DeducedMismatch: 778 case Sema::TDK_NonDeducedMismatch: 779 return &static_cast<DFIArguments*>(Data)->SecondArg; 780 781 // Unhandled 782 case Sema::TDK_MiscellaneousDeductionFailure: 783 break; 784 } 785 786 return nullptr; 787 } 788 789 Expr *DeductionFailureInfo::getExpr() { 790 if (static_cast<Sema::TemplateDeductionResult>(Result) == 791 Sema::TDK_FailedOverloadResolution) 792 return static_cast<Expr*>(Data); 793 794 return nullptr; 795 } 796 797 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 798 if (static_cast<Sema::TemplateDeductionResult>(Result) == 799 Sema::TDK_DeducedMismatch) 800 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 801 802 return llvm::None; 803 } 804 805 void OverloadCandidateSet::destroyCandidates() { 806 for (iterator i = begin(), e = end(); i != e; ++i) { 807 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 808 i->Conversions[ii].~ImplicitConversionSequence(); 809 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 810 i->DeductionFailure.Destroy(); 811 } 812 } 813 814 void OverloadCandidateSet::clear() { 815 destroyCandidates(); 816 NumInlineSequences = 0; 817 Candidates.clear(); 818 Functions.clear(); 819 } 820 821 namespace { 822 class UnbridgedCastsSet { 823 struct Entry { 824 Expr **Addr; 825 Expr *Saved; 826 }; 827 SmallVector<Entry, 2> Entries; 828 829 public: 830 void save(Sema &S, Expr *&E) { 831 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 832 Entry entry = { &E, E }; 833 Entries.push_back(entry); 834 E = S.stripARCUnbridgedCast(E); 835 } 836 837 void restore() { 838 for (SmallVectorImpl<Entry>::iterator 839 i = Entries.begin(), e = Entries.end(); i != e; ++i) 840 *i->Addr = i->Saved; 841 } 842 }; 843 } 844 845 /// checkPlaceholderForOverload - Do any interesting placeholder-like 846 /// preprocessing on the given expression. 847 /// 848 /// \param unbridgedCasts a collection to which to add unbridged casts; 849 /// without this, they will be immediately diagnosed as errors 850 /// 851 /// Return true on unrecoverable error. 852 static bool 853 checkPlaceholderForOverload(Sema &S, Expr *&E, 854 UnbridgedCastsSet *unbridgedCasts = nullptr) { 855 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 856 // We can't handle overloaded expressions here because overload 857 // resolution might reasonably tweak them. 858 if (placeholder->getKind() == BuiltinType::Overload) return false; 859 860 // If the context potentially accepts unbridged ARC casts, strip 861 // the unbridged cast and add it to the collection for later restoration. 862 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 863 unbridgedCasts) { 864 unbridgedCasts->save(S, E); 865 return false; 866 } 867 868 // Go ahead and check everything else. 869 ExprResult result = S.CheckPlaceholderExpr(E); 870 if (result.isInvalid()) 871 return true; 872 873 E = result.get(); 874 return false; 875 } 876 877 // Nothing to do. 878 return false; 879 } 880 881 /// checkArgPlaceholdersForOverload - Check a set of call operands for 882 /// placeholders. 883 static bool checkArgPlaceholdersForOverload(Sema &S, 884 MultiExprArg Args, 885 UnbridgedCastsSet &unbridged) { 886 for (unsigned i = 0, e = Args.size(); i != e; ++i) 887 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 888 return true; 889 890 return false; 891 } 892 893 // IsOverload - Determine whether the given New declaration is an 894 // overload of the declarations in Old. This routine returns false if 895 // New and Old cannot be overloaded, e.g., if New has the same 896 // signature as some function in Old (C++ 1.3.10) or if the Old 897 // declarations aren't functions (or function templates) at all. When 898 // it does return false, MatchedDecl will point to the decl that New 899 // cannot be overloaded with. This decl may be a UsingShadowDecl on 900 // top of the underlying declaration. 901 // 902 // Example: Given the following input: 903 // 904 // void f(int, float); // #1 905 // void f(int, int); // #2 906 // int f(int, int); // #3 907 // 908 // When we process #1, there is no previous declaration of "f", 909 // so IsOverload will not be used. 910 // 911 // When we process #2, Old contains only the FunctionDecl for #1. By 912 // comparing the parameter types, we see that #1 and #2 are overloaded 913 // (since they have different signatures), so this routine returns 914 // false; MatchedDecl is unchanged. 915 // 916 // When we process #3, Old is an overload set containing #1 and #2. We 917 // compare the signatures of #3 to #1 (they're overloaded, so we do 918 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 919 // identical (return types of functions are not part of the 920 // signature), IsOverload returns false and MatchedDecl will be set to 921 // point to the FunctionDecl for #2. 922 // 923 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 924 // into a class by a using declaration. The rules for whether to hide 925 // shadow declarations ignore some properties which otherwise figure 926 // into a function template's signature. 927 Sema::OverloadKind 928 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 929 NamedDecl *&Match, bool NewIsUsingDecl) { 930 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 931 I != E; ++I) { 932 NamedDecl *OldD = *I; 933 934 bool OldIsUsingDecl = false; 935 if (isa<UsingShadowDecl>(OldD)) { 936 OldIsUsingDecl = true; 937 938 // We can always introduce two using declarations into the same 939 // context, even if they have identical signatures. 940 if (NewIsUsingDecl) continue; 941 942 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 943 } 944 945 // A using-declaration does not conflict with another declaration 946 // if one of them is hidden. 947 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 948 continue; 949 950 // If either declaration was introduced by a using declaration, 951 // we'll need to use slightly different rules for matching. 952 // Essentially, these rules are the normal rules, except that 953 // function templates hide function templates with different 954 // return types or template parameter lists. 955 bool UseMemberUsingDeclRules = 956 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 957 !New->getFriendObjectKind(); 958 959 if (FunctionDecl *OldF = OldD->getAsFunction()) { 960 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 961 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 962 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 963 continue; 964 } 965 966 if (!isa<FunctionTemplateDecl>(OldD) && 967 !shouldLinkPossiblyHiddenDecl(*I, New)) 968 continue; 969 970 Match = *I; 971 return Ovl_Match; 972 } 973 } else if (isa<UsingDecl>(OldD)) { 974 // We can overload with these, which can show up when doing 975 // redeclaration checks for UsingDecls. 976 assert(Old.getLookupKind() == LookupUsingDeclName); 977 } else if (isa<TagDecl>(OldD)) { 978 // We can always overload with tags by hiding them. 979 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 980 // Optimistically assume that an unresolved using decl will 981 // overload; if it doesn't, we'll have to diagnose during 982 // template instantiation. 983 } else { 984 // (C++ 13p1): 985 // Only function declarations can be overloaded; object and type 986 // declarations cannot be overloaded. 987 Match = *I; 988 return Ovl_NonFunction; 989 } 990 } 991 992 return Ovl_Overload; 993 } 994 995 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 996 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 997 // C++ [basic.start.main]p2: This function shall not be overloaded. 998 if (New->isMain()) 999 return false; 1000 1001 // MSVCRT user defined entry points cannot be overloaded. 1002 if (New->isMSVCRTEntryPoint()) 1003 return false; 1004 1005 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1006 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1007 1008 // C++ [temp.fct]p2: 1009 // A function template can be overloaded with other function templates 1010 // and with normal (non-template) functions. 1011 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1012 return true; 1013 1014 // Is the function New an overload of the function Old? 1015 QualType OldQType = Context.getCanonicalType(Old->getType()); 1016 QualType NewQType = Context.getCanonicalType(New->getType()); 1017 1018 // Compare the signatures (C++ 1.3.10) of the two functions to 1019 // determine whether they are overloads. If we find any mismatch 1020 // in the signature, they are overloads. 1021 1022 // If either of these functions is a K&R-style function (no 1023 // prototype), then we consider them to have matching signatures. 1024 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1025 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1026 return false; 1027 1028 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1029 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1030 1031 // The signature of a function includes the types of its 1032 // parameters (C++ 1.3.10), which includes the presence or absence 1033 // of the ellipsis; see C++ DR 357). 1034 if (OldQType != NewQType && 1035 (OldType->getNumParams() != NewType->getNumParams() || 1036 OldType->isVariadic() != NewType->isVariadic() || 1037 !FunctionParamTypesAreEqual(OldType, NewType))) 1038 return true; 1039 1040 // C++ [temp.over.link]p4: 1041 // The signature of a function template consists of its function 1042 // signature, its return type and its template parameter list. The names 1043 // of the template parameters are significant only for establishing the 1044 // relationship between the template parameters and the rest of the 1045 // signature. 1046 // 1047 // We check the return type and template parameter lists for function 1048 // templates first; the remaining checks follow. 1049 // 1050 // However, we don't consider either of these when deciding whether 1051 // a member introduced by a shadow declaration is hidden. 1052 if (!UseMemberUsingDeclRules && NewTemplate && 1053 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1054 OldTemplate->getTemplateParameters(), 1055 false, TPL_TemplateMatch) || 1056 OldType->getReturnType() != NewType->getReturnType())) 1057 return true; 1058 1059 // If the function is a class member, its signature includes the 1060 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1061 // 1062 // As part of this, also check whether one of the member functions 1063 // is static, in which case they are not overloads (C++ 1064 // 13.1p2). While not part of the definition of the signature, 1065 // this check is important to determine whether these functions 1066 // can be overloaded. 1067 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1068 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1069 if (OldMethod && NewMethod && 1070 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1071 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1072 if (!UseMemberUsingDeclRules && 1073 (OldMethod->getRefQualifier() == RQ_None || 1074 NewMethod->getRefQualifier() == RQ_None)) { 1075 // C++0x [over.load]p2: 1076 // - Member function declarations with the same name and the same 1077 // parameter-type-list as well as member function template 1078 // declarations with the same name, the same parameter-type-list, and 1079 // the same template parameter lists cannot be overloaded if any of 1080 // them, but not all, have a ref-qualifier (8.3.5). 1081 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1082 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1083 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1084 } 1085 return true; 1086 } 1087 1088 // We may not have applied the implicit const for a constexpr member 1089 // function yet (because we haven't yet resolved whether this is a static 1090 // or non-static member function). Add it now, on the assumption that this 1091 // is a redeclaration of OldMethod. 1092 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1093 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1094 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1095 !isa<CXXConstructorDecl>(NewMethod)) 1096 NewQuals |= Qualifiers::Const; 1097 1098 // We do not allow overloading based off of '__restrict'. 1099 OldQuals &= ~Qualifiers::Restrict; 1100 NewQuals &= ~Qualifiers::Restrict; 1101 if (OldQuals != NewQuals) 1102 return true; 1103 } 1104 1105 // Though pass_object_size is placed on parameters and takes an argument, we 1106 // consider it to be a function-level modifier for the sake of function 1107 // identity. Either the function has one or more parameters with 1108 // pass_object_size or it doesn't. 1109 if (functionHasPassObjectSizeParams(New) != 1110 functionHasPassObjectSizeParams(Old)) 1111 return true; 1112 1113 // enable_if attributes are an order-sensitive part of the signature. 1114 for (specific_attr_iterator<EnableIfAttr> 1115 NewI = New->specific_attr_begin<EnableIfAttr>(), 1116 NewE = New->specific_attr_end<EnableIfAttr>(), 1117 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1118 OldE = Old->specific_attr_end<EnableIfAttr>(); 1119 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1120 if (NewI == NewE || OldI == OldE) 1121 return true; 1122 llvm::FoldingSetNodeID NewID, OldID; 1123 NewI->getCond()->Profile(NewID, Context, true); 1124 OldI->getCond()->Profile(OldID, Context, true); 1125 if (NewID != OldID) 1126 return true; 1127 } 1128 1129 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1130 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1131 OldTarget = IdentifyCUDATarget(Old); 1132 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1133 return false; 1134 1135 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1136 1137 // Don't allow mixing of HD with other kinds. This guarantees that 1138 // we have only one viable function with this signature on any 1139 // side of CUDA compilation . 1140 // __global__ functions can't be overloaded based on attribute 1141 // difference because, like HD, they also exist on both sides. 1142 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) || 1143 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) 1144 return false; 1145 1146 // Allow overloading of functions with same signature, but 1147 // different CUDA target attributes. 1148 return NewTarget != OldTarget; 1149 } 1150 1151 // The signatures match; this is not an overload. 1152 return false; 1153 } 1154 1155 /// \brief Checks availability of the function depending on the current 1156 /// function context. Inside an unavailable function, unavailability is ignored. 1157 /// 1158 /// \returns true if \arg FD is unavailable and current context is inside 1159 /// an available function, false otherwise. 1160 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1161 if (!FD->isUnavailable()) 1162 return false; 1163 1164 // Walk up the context of the caller. 1165 Decl *C = cast<Decl>(CurContext); 1166 do { 1167 if (C->isUnavailable()) 1168 return false; 1169 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1170 return true; 1171 } 1172 1173 /// \brief Tries a user-defined conversion from From to ToType. 1174 /// 1175 /// Produces an implicit conversion sequence for when a standard conversion 1176 /// is not an option. See TryImplicitConversion for more information. 1177 static ImplicitConversionSequence 1178 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1179 bool SuppressUserConversions, 1180 bool AllowExplicit, 1181 bool InOverloadResolution, 1182 bool CStyle, 1183 bool AllowObjCWritebackConversion, 1184 bool AllowObjCConversionOnExplicit) { 1185 ImplicitConversionSequence ICS; 1186 1187 if (SuppressUserConversions) { 1188 // We're not in the case above, so there is no conversion that 1189 // we can perform. 1190 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1191 return ICS; 1192 } 1193 1194 // Attempt user-defined conversion. 1195 OverloadCandidateSet Conversions(From->getExprLoc(), 1196 OverloadCandidateSet::CSK_Normal); 1197 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1198 Conversions, AllowExplicit, 1199 AllowObjCConversionOnExplicit)) { 1200 case OR_Success: 1201 case OR_Deleted: 1202 ICS.setUserDefined(); 1203 // C++ [over.ics.user]p4: 1204 // A conversion of an expression of class type to the same class 1205 // type is given Exact Match rank, and a conversion of an 1206 // expression of class type to a base class of that type is 1207 // given Conversion rank, in spite of the fact that a copy 1208 // constructor (i.e., a user-defined conversion function) is 1209 // called for those cases. 1210 if (CXXConstructorDecl *Constructor 1211 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1212 QualType FromCanon 1213 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1214 QualType ToCanon 1215 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1216 if (Constructor->isCopyConstructor() && 1217 (FromCanon == ToCanon || 1218 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1219 // Turn this into a "standard" conversion sequence, so that it 1220 // gets ranked with standard conversion sequences. 1221 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1222 ICS.setStandard(); 1223 ICS.Standard.setAsIdentityConversion(); 1224 ICS.Standard.setFromType(From->getType()); 1225 ICS.Standard.setAllToTypes(ToType); 1226 ICS.Standard.CopyConstructor = Constructor; 1227 ICS.Standard.FoundCopyConstructor = Found; 1228 if (ToCanon != FromCanon) 1229 ICS.Standard.Second = ICK_Derived_To_Base; 1230 } 1231 } 1232 break; 1233 1234 case OR_Ambiguous: 1235 ICS.setAmbiguous(); 1236 ICS.Ambiguous.setFromType(From->getType()); 1237 ICS.Ambiguous.setToType(ToType); 1238 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1239 Cand != Conversions.end(); ++Cand) 1240 if (Cand->Viable) 1241 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1242 break; 1243 1244 // Fall through. 1245 case OR_No_Viable_Function: 1246 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1247 break; 1248 } 1249 1250 return ICS; 1251 } 1252 1253 /// TryImplicitConversion - Attempt to perform an implicit conversion 1254 /// from the given expression (Expr) to the given type (ToType). This 1255 /// function returns an implicit conversion sequence that can be used 1256 /// to perform the initialization. Given 1257 /// 1258 /// void f(float f); 1259 /// void g(int i) { f(i); } 1260 /// 1261 /// this routine would produce an implicit conversion sequence to 1262 /// describe the initialization of f from i, which will be a standard 1263 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1264 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1265 // 1266 /// Note that this routine only determines how the conversion can be 1267 /// performed; it does not actually perform the conversion. As such, 1268 /// it will not produce any diagnostics if no conversion is available, 1269 /// but will instead return an implicit conversion sequence of kind 1270 /// "BadConversion". 1271 /// 1272 /// If @p SuppressUserConversions, then user-defined conversions are 1273 /// not permitted. 1274 /// If @p AllowExplicit, then explicit user-defined conversions are 1275 /// permitted. 1276 /// 1277 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1278 /// writeback conversion, which allows __autoreleasing id* parameters to 1279 /// be initialized with __strong id* or __weak id* arguments. 1280 static ImplicitConversionSequence 1281 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1282 bool SuppressUserConversions, 1283 bool AllowExplicit, 1284 bool InOverloadResolution, 1285 bool CStyle, 1286 bool AllowObjCWritebackConversion, 1287 bool AllowObjCConversionOnExplicit) { 1288 ImplicitConversionSequence ICS; 1289 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1290 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1291 ICS.setStandard(); 1292 return ICS; 1293 } 1294 1295 if (!S.getLangOpts().CPlusPlus) { 1296 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1297 return ICS; 1298 } 1299 1300 // C++ [over.ics.user]p4: 1301 // A conversion of an expression of class type to the same class 1302 // type is given Exact Match rank, and a conversion of an 1303 // expression of class type to a base class of that type is 1304 // given Conversion rank, in spite of the fact that a copy/move 1305 // constructor (i.e., a user-defined conversion function) is 1306 // called for those cases. 1307 QualType FromType = From->getType(); 1308 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1309 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1310 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1311 ICS.setStandard(); 1312 ICS.Standard.setAsIdentityConversion(); 1313 ICS.Standard.setFromType(FromType); 1314 ICS.Standard.setAllToTypes(ToType); 1315 1316 // We don't actually check at this point whether there is a valid 1317 // copy/move constructor, since overloading just assumes that it 1318 // exists. When we actually perform initialization, we'll find the 1319 // appropriate constructor to copy the returned object, if needed. 1320 ICS.Standard.CopyConstructor = nullptr; 1321 1322 // Determine whether this is considered a derived-to-base conversion. 1323 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1324 ICS.Standard.Second = ICK_Derived_To_Base; 1325 1326 return ICS; 1327 } 1328 1329 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1330 AllowExplicit, InOverloadResolution, CStyle, 1331 AllowObjCWritebackConversion, 1332 AllowObjCConversionOnExplicit); 1333 } 1334 1335 ImplicitConversionSequence 1336 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1337 bool SuppressUserConversions, 1338 bool AllowExplicit, 1339 bool InOverloadResolution, 1340 bool CStyle, 1341 bool AllowObjCWritebackConversion) { 1342 return ::TryImplicitConversion(*this, From, ToType, 1343 SuppressUserConversions, AllowExplicit, 1344 InOverloadResolution, CStyle, 1345 AllowObjCWritebackConversion, 1346 /*AllowObjCConversionOnExplicit=*/false); 1347 } 1348 1349 /// PerformImplicitConversion - Perform an implicit conversion of the 1350 /// expression From to the type ToType. Returns the 1351 /// converted expression. Flavor is the kind of conversion we're 1352 /// performing, used in the error message. If @p AllowExplicit, 1353 /// explicit user-defined conversions are permitted. 1354 ExprResult 1355 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1356 AssignmentAction Action, bool AllowExplicit) { 1357 ImplicitConversionSequence ICS; 1358 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1359 } 1360 1361 ExprResult 1362 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1363 AssignmentAction Action, bool AllowExplicit, 1364 ImplicitConversionSequence& ICS) { 1365 if (checkPlaceholderForOverload(*this, From)) 1366 return ExprError(); 1367 1368 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1369 bool AllowObjCWritebackConversion 1370 = getLangOpts().ObjCAutoRefCount && 1371 (Action == AA_Passing || Action == AA_Sending); 1372 if (getLangOpts().ObjC1) 1373 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1374 ToType, From->getType(), From); 1375 ICS = ::TryImplicitConversion(*this, From, ToType, 1376 /*SuppressUserConversions=*/false, 1377 AllowExplicit, 1378 /*InOverloadResolution=*/false, 1379 /*CStyle=*/false, 1380 AllowObjCWritebackConversion, 1381 /*AllowObjCConversionOnExplicit=*/false); 1382 return PerformImplicitConversion(From, ToType, ICS, Action); 1383 } 1384 1385 /// \brief Determine whether the conversion from FromType to ToType is a valid 1386 /// conversion that strips "noreturn" off the nested function type. 1387 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1388 QualType &ResultTy) { 1389 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1390 return false; 1391 1392 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1393 // where F adds one of the following at most once: 1394 // - a pointer 1395 // - a member pointer 1396 // - a block pointer 1397 CanQualType CanTo = Context.getCanonicalType(ToType); 1398 CanQualType CanFrom = Context.getCanonicalType(FromType); 1399 Type::TypeClass TyClass = CanTo->getTypeClass(); 1400 if (TyClass != CanFrom->getTypeClass()) return false; 1401 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1402 if (TyClass == Type::Pointer) { 1403 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1404 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1405 } else if (TyClass == Type::BlockPointer) { 1406 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1407 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1408 } else if (TyClass == Type::MemberPointer) { 1409 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1410 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1411 } else { 1412 return false; 1413 } 1414 1415 TyClass = CanTo->getTypeClass(); 1416 if (TyClass != CanFrom->getTypeClass()) return false; 1417 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1418 return false; 1419 } 1420 1421 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1422 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1423 if (!EInfo.getNoReturn()) return false; 1424 1425 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1426 assert(QualType(FromFn, 0).isCanonical()); 1427 if (QualType(FromFn, 0) != CanTo) return false; 1428 1429 ResultTy = ToType; 1430 return true; 1431 } 1432 1433 /// \brief Determine whether the conversion from FromType to ToType is a valid 1434 /// vector conversion. 1435 /// 1436 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1437 /// conversion. 1438 static bool IsVectorConversion(Sema &S, QualType FromType, 1439 QualType ToType, ImplicitConversionKind &ICK) { 1440 // We need at least one of these types to be a vector type to have a vector 1441 // conversion. 1442 if (!ToType->isVectorType() && !FromType->isVectorType()) 1443 return false; 1444 1445 // Identical types require no conversions. 1446 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1447 return false; 1448 1449 // There are no conversions between extended vector types, only identity. 1450 if (ToType->isExtVectorType()) { 1451 // There are no conversions between extended vector types other than the 1452 // identity conversion. 1453 if (FromType->isExtVectorType()) 1454 return false; 1455 1456 // Vector splat from any arithmetic type to a vector. 1457 if (FromType->isArithmeticType()) { 1458 ICK = ICK_Vector_Splat; 1459 return true; 1460 } 1461 } 1462 1463 // We can perform the conversion between vector types in the following cases: 1464 // 1)vector types are equivalent AltiVec and GCC vector types 1465 // 2)lax vector conversions are permitted and the vector types are of the 1466 // same size 1467 if (ToType->isVectorType() && FromType->isVectorType()) { 1468 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1469 S.isLaxVectorConversion(FromType, ToType)) { 1470 ICK = ICK_Vector_Conversion; 1471 return true; 1472 } 1473 } 1474 1475 return false; 1476 } 1477 1478 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1479 bool InOverloadResolution, 1480 StandardConversionSequence &SCS, 1481 bool CStyle); 1482 1483 /// IsStandardConversion - Determines whether there is a standard 1484 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1485 /// expression From to the type ToType. Standard conversion sequences 1486 /// only consider non-class types; for conversions that involve class 1487 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1488 /// contain the standard conversion sequence required to perform this 1489 /// conversion and this routine will return true. Otherwise, this 1490 /// routine will return false and the value of SCS is unspecified. 1491 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1492 bool InOverloadResolution, 1493 StandardConversionSequence &SCS, 1494 bool CStyle, 1495 bool AllowObjCWritebackConversion) { 1496 QualType FromType = From->getType(); 1497 1498 // Standard conversions (C++ [conv]) 1499 SCS.setAsIdentityConversion(); 1500 SCS.IncompatibleObjC = false; 1501 SCS.setFromType(FromType); 1502 SCS.CopyConstructor = nullptr; 1503 1504 // There are no standard conversions for class types in C++, so 1505 // abort early. When overloading in C, however, we do permit them. 1506 if (S.getLangOpts().CPlusPlus && 1507 (FromType->isRecordType() || ToType->isRecordType())) 1508 return false; 1509 1510 // The first conversion can be an lvalue-to-rvalue conversion, 1511 // array-to-pointer conversion, or function-to-pointer conversion 1512 // (C++ 4p1). 1513 1514 if (FromType == S.Context.OverloadTy) { 1515 DeclAccessPair AccessPair; 1516 if (FunctionDecl *Fn 1517 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1518 AccessPair)) { 1519 // We were able to resolve the address of the overloaded function, 1520 // so we can convert to the type of that function. 1521 FromType = Fn->getType(); 1522 SCS.setFromType(FromType); 1523 1524 // we can sometimes resolve &foo<int> regardless of ToType, so check 1525 // if the type matches (identity) or we are converting to bool 1526 if (!S.Context.hasSameUnqualifiedType( 1527 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1528 QualType resultTy; 1529 // if the function type matches except for [[noreturn]], it's ok 1530 if (!S.IsNoReturnConversion(FromType, 1531 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1532 // otherwise, only a boolean conversion is standard 1533 if (!ToType->isBooleanType()) 1534 return false; 1535 } 1536 1537 // Check if the "from" expression is taking the address of an overloaded 1538 // function and recompute the FromType accordingly. Take advantage of the 1539 // fact that non-static member functions *must* have such an address-of 1540 // expression. 1541 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1542 if (Method && !Method->isStatic()) { 1543 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1544 "Non-unary operator on non-static member address"); 1545 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1546 == UO_AddrOf && 1547 "Non-address-of operator on non-static member address"); 1548 const Type *ClassType 1549 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1550 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1551 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1552 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1553 UO_AddrOf && 1554 "Non-address-of operator for overloaded function expression"); 1555 FromType = S.Context.getPointerType(FromType); 1556 } 1557 1558 // Check that we've computed the proper type after overload resolution. 1559 assert(S.Context.hasSameType( 1560 FromType, 1561 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1562 } else { 1563 return false; 1564 } 1565 } 1566 // Lvalue-to-rvalue conversion (C++11 4.1): 1567 // A glvalue (3.10) of a non-function, non-array type T can 1568 // be converted to a prvalue. 1569 bool argIsLValue = From->isGLValue(); 1570 if (argIsLValue && 1571 !FromType->isFunctionType() && !FromType->isArrayType() && 1572 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1573 SCS.First = ICK_Lvalue_To_Rvalue; 1574 1575 // C11 6.3.2.1p2: 1576 // ... if the lvalue has atomic type, the value has the non-atomic version 1577 // of the type of the lvalue ... 1578 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1579 FromType = Atomic->getValueType(); 1580 1581 // If T is a non-class type, the type of the rvalue is the 1582 // cv-unqualified version of T. Otherwise, the type of the rvalue 1583 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1584 // just strip the qualifiers because they don't matter. 1585 FromType = FromType.getUnqualifiedType(); 1586 } else if (FromType->isArrayType()) { 1587 // Array-to-pointer conversion (C++ 4.2) 1588 SCS.First = ICK_Array_To_Pointer; 1589 1590 // An lvalue or rvalue of type "array of N T" or "array of unknown 1591 // bound of T" can be converted to an rvalue of type "pointer to 1592 // T" (C++ 4.2p1). 1593 FromType = S.Context.getArrayDecayedType(FromType); 1594 1595 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1596 // This conversion is deprecated in C++03 (D.4) 1597 SCS.DeprecatedStringLiteralToCharPtr = true; 1598 1599 // For the purpose of ranking in overload resolution 1600 // (13.3.3.1.1), this conversion is considered an 1601 // array-to-pointer conversion followed by a qualification 1602 // conversion (4.4). (C++ 4.2p2) 1603 SCS.Second = ICK_Identity; 1604 SCS.Third = ICK_Qualification; 1605 SCS.QualificationIncludesObjCLifetime = false; 1606 SCS.setAllToTypes(FromType); 1607 return true; 1608 } 1609 } else if (FromType->isFunctionType() && argIsLValue) { 1610 // Function-to-pointer conversion (C++ 4.3). 1611 SCS.First = ICK_Function_To_Pointer; 1612 1613 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1614 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1615 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1616 return false; 1617 1618 // An lvalue of function type T can be converted to an rvalue of 1619 // type "pointer to T." The result is a pointer to the 1620 // function. (C++ 4.3p1). 1621 FromType = S.Context.getPointerType(FromType); 1622 } else { 1623 // We don't require any conversions for the first step. 1624 SCS.First = ICK_Identity; 1625 } 1626 SCS.setToType(0, FromType); 1627 1628 // The second conversion can be an integral promotion, floating 1629 // point promotion, integral conversion, floating point conversion, 1630 // floating-integral conversion, pointer conversion, 1631 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1632 // For overloading in C, this can also be a "compatible-type" 1633 // conversion. 1634 bool IncompatibleObjC = false; 1635 ImplicitConversionKind SecondICK = ICK_Identity; 1636 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1637 // The unqualified versions of the types are the same: there's no 1638 // conversion to do. 1639 SCS.Second = ICK_Identity; 1640 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1641 // Integral promotion (C++ 4.5). 1642 SCS.Second = ICK_Integral_Promotion; 1643 FromType = ToType.getUnqualifiedType(); 1644 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1645 // Floating point promotion (C++ 4.6). 1646 SCS.Second = ICK_Floating_Promotion; 1647 FromType = ToType.getUnqualifiedType(); 1648 } else if (S.IsComplexPromotion(FromType, ToType)) { 1649 // Complex promotion (Clang extension) 1650 SCS.Second = ICK_Complex_Promotion; 1651 FromType = ToType.getUnqualifiedType(); 1652 } else if (ToType->isBooleanType() && 1653 (FromType->isArithmeticType() || 1654 FromType->isAnyPointerType() || 1655 FromType->isBlockPointerType() || 1656 FromType->isMemberPointerType() || 1657 FromType->isNullPtrType())) { 1658 // Boolean conversions (C++ 4.12). 1659 SCS.Second = ICK_Boolean_Conversion; 1660 FromType = S.Context.BoolTy; 1661 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1662 ToType->isIntegralType(S.Context)) { 1663 // Integral conversions (C++ 4.7). 1664 SCS.Second = ICK_Integral_Conversion; 1665 FromType = ToType.getUnqualifiedType(); 1666 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1667 // Complex conversions (C99 6.3.1.6) 1668 SCS.Second = ICK_Complex_Conversion; 1669 FromType = ToType.getUnqualifiedType(); 1670 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1671 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1672 // Complex-real conversions (C99 6.3.1.7) 1673 SCS.Second = ICK_Complex_Real; 1674 FromType = ToType.getUnqualifiedType(); 1675 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1676 // FIXME: disable conversions between long double and __float128 if 1677 // their representation is different until there is back end support 1678 // We of course allow this conversion if long double is really double. 1679 if (&S.Context.getFloatTypeSemantics(FromType) != 1680 &S.Context.getFloatTypeSemantics(ToType)) { 1681 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1682 ToType == S.Context.LongDoubleTy) || 1683 (FromType == S.Context.LongDoubleTy && 1684 ToType == S.Context.Float128Ty)); 1685 if (Float128AndLongDouble && 1686 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1687 &llvm::APFloat::IEEEdouble)) 1688 return false; 1689 } 1690 // Floating point conversions (C++ 4.8). 1691 SCS.Second = ICK_Floating_Conversion; 1692 FromType = ToType.getUnqualifiedType(); 1693 } else if ((FromType->isRealFloatingType() && 1694 ToType->isIntegralType(S.Context)) || 1695 (FromType->isIntegralOrUnscopedEnumerationType() && 1696 ToType->isRealFloatingType())) { 1697 // Floating-integral conversions (C++ 4.9). 1698 SCS.Second = ICK_Floating_Integral; 1699 FromType = ToType.getUnqualifiedType(); 1700 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1701 SCS.Second = ICK_Block_Pointer_Conversion; 1702 } else if (AllowObjCWritebackConversion && 1703 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1704 SCS.Second = ICK_Writeback_Conversion; 1705 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1706 FromType, IncompatibleObjC)) { 1707 // Pointer conversions (C++ 4.10). 1708 SCS.Second = ICK_Pointer_Conversion; 1709 SCS.IncompatibleObjC = IncompatibleObjC; 1710 FromType = FromType.getUnqualifiedType(); 1711 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1712 InOverloadResolution, FromType)) { 1713 // Pointer to member conversions (4.11). 1714 SCS.Second = ICK_Pointer_Member; 1715 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1716 SCS.Second = SecondICK; 1717 FromType = ToType.getUnqualifiedType(); 1718 } else if (!S.getLangOpts().CPlusPlus && 1719 S.Context.typesAreCompatible(ToType, FromType)) { 1720 // Compatible conversions (Clang extension for C function overloading) 1721 SCS.Second = ICK_Compatible_Conversion; 1722 FromType = ToType.getUnqualifiedType(); 1723 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1724 // Treat a conversion that strips "noreturn" as an identity conversion. 1725 SCS.Second = ICK_NoReturn_Adjustment; 1726 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1727 InOverloadResolution, 1728 SCS, CStyle)) { 1729 SCS.Second = ICK_TransparentUnionConversion; 1730 FromType = ToType; 1731 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1732 CStyle)) { 1733 // tryAtomicConversion has updated the standard conversion sequence 1734 // appropriately. 1735 return true; 1736 } else if (ToType->isEventT() && 1737 From->isIntegerConstantExpr(S.getASTContext()) && 1738 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1739 SCS.Second = ICK_Zero_Event_Conversion; 1740 FromType = ToType; 1741 } else { 1742 // No second conversion required. 1743 SCS.Second = ICK_Identity; 1744 } 1745 SCS.setToType(1, FromType); 1746 1747 QualType CanonFrom; 1748 QualType CanonTo; 1749 // The third conversion can be a qualification conversion (C++ 4p1). 1750 bool ObjCLifetimeConversion; 1751 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1752 ObjCLifetimeConversion)) { 1753 SCS.Third = ICK_Qualification; 1754 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1755 FromType = ToType; 1756 CanonFrom = S.Context.getCanonicalType(FromType); 1757 CanonTo = S.Context.getCanonicalType(ToType); 1758 } else { 1759 // No conversion required 1760 SCS.Third = ICK_Identity; 1761 1762 // C++ [over.best.ics]p6: 1763 // [...] Any difference in top-level cv-qualification is 1764 // subsumed by the initialization itself and does not constitute 1765 // a conversion. [...] 1766 CanonFrom = S.Context.getCanonicalType(FromType); 1767 CanonTo = S.Context.getCanonicalType(ToType); 1768 if (CanonFrom.getLocalUnqualifiedType() 1769 == CanonTo.getLocalUnqualifiedType() && 1770 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1771 FromType = ToType; 1772 CanonFrom = CanonTo; 1773 } 1774 } 1775 SCS.setToType(2, FromType); 1776 1777 if (CanonFrom == CanonTo) 1778 return true; 1779 1780 // If we have not converted the argument type to the parameter type, 1781 // this is a bad conversion sequence, unless we're resolving an overload in C. 1782 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1783 return false; 1784 1785 ExprResult ER = ExprResult{From}; 1786 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1787 /*Diagnose=*/false, 1788 /*DiagnoseCFAudited=*/false, 1789 /*ConvertRHS=*/false); 1790 if (Conv != Sema::Compatible) 1791 return false; 1792 1793 SCS.setAllToTypes(ToType); 1794 // We need to set all three because we want this conversion to rank terribly, 1795 // and we don't know what conversions it may overlap with. 1796 SCS.First = ICK_C_Only_Conversion; 1797 SCS.Second = ICK_C_Only_Conversion; 1798 SCS.Third = ICK_C_Only_Conversion; 1799 return true; 1800 } 1801 1802 static bool 1803 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1804 QualType &ToType, 1805 bool InOverloadResolution, 1806 StandardConversionSequence &SCS, 1807 bool CStyle) { 1808 1809 const RecordType *UT = ToType->getAsUnionType(); 1810 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1811 return false; 1812 // The field to initialize within the transparent union. 1813 RecordDecl *UD = UT->getDecl(); 1814 // It's compatible if the expression matches any of the fields. 1815 for (const auto *it : UD->fields()) { 1816 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1817 CStyle, /*ObjCWritebackConversion=*/false)) { 1818 ToType = it->getType(); 1819 return true; 1820 } 1821 } 1822 return false; 1823 } 1824 1825 /// IsIntegralPromotion - Determines whether the conversion from the 1826 /// expression From (whose potentially-adjusted type is FromType) to 1827 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1828 /// sets PromotedType to the promoted type. 1829 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1830 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1831 // All integers are built-in. 1832 if (!To) { 1833 return false; 1834 } 1835 1836 // An rvalue of type char, signed char, unsigned char, short int, or 1837 // unsigned short int can be converted to an rvalue of type int if 1838 // int can represent all the values of the source type; otherwise, 1839 // the source rvalue can be converted to an rvalue of type unsigned 1840 // int (C++ 4.5p1). 1841 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1842 !FromType->isEnumeralType()) { 1843 if (// We can promote any signed, promotable integer type to an int 1844 (FromType->isSignedIntegerType() || 1845 // We can promote any unsigned integer type whose size is 1846 // less than int to an int. 1847 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1848 return To->getKind() == BuiltinType::Int; 1849 } 1850 1851 return To->getKind() == BuiltinType::UInt; 1852 } 1853 1854 // C++11 [conv.prom]p3: 1855 // A prvalue of an unscoped enumeration type whose underlying type is not 1856 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1857 // following types that can represent all the values of the enumeration 1858 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1859 // unsigned int, long int, unsigned long int, long long int, or unsigned 1860 // long long int. If none of the types in that list can represent all the 1861 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1862 // type can be converted to an rvalue a prvalue of the extended integer type 1863 // with lowest integer conversion rank (4.13) greater than the rank of long 1864 // long in which all the values of the enumeration can be represented. If 1865 // there are two such extended types, the signed one is chosen. 1866 // C++11 [conv.prom]p4: 1867 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1868 // can be converted to a prvalue of its underlying type. Moreover, if 1869 // integral promotion can be applied to its underlying type, a prvalue of an 1870 // unscoped enumeration type whose underlying type is fixed can also be 1871 // converted to a prvalue of the promoted underlying type. 1872 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1873 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1874 // provided for a scoped enumeration. 1875 if (FromEnumType->getDecl()->isScoped()) 1876 return false; 1877 1878 // We can perform an integral promotion to the underlying type of the enum, 1879 // even if that's not the promoted type. Note that the check for promoting 1880 // the underlying type is based on the type alone, and does not consider 1881 // the bitfield-ness of the actual source expression. 1882 if (FromEnumType->getDecl()->isFixed()) { 1883 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1884 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1885 IsIntegralPromotion(nullptr, Underlying, ToType); 1886 } 1887 1888 // We have already pre-calculated the promotion type, so this is trivial. 1889 if (ToType->isIntegerType() && 1890 isCompleteType(From->getLocStart(), FromType)) 1891 return Context.hasSameUnqualifiedType( 1892 ToType, FromEnumType->getDecl()->getPromotionType()); 1893 } 1894 1895 // C++0x [conv.prom]p2: 1896 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1897 // to an rvalue a prvalue of the first of the following types that can 1898 // represent all the values of its underlying type: int, unsigned int, 1899 // long int, unsigned long int, long long int, or unsigned long long int. 1900 // If none of the types in that list can represent all the values of its 1901 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1902 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1903 // type. 1904 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1905 ToType->isIntegerType()) { 1906 // Determine whether the type we're converting from is signed or 1907 // unsigned. 1908 bool FromIsSigned = FromType->isSignedIntegerType(); 1909 uint64_t FromSize = Context.getTypeSize(FromType); 1910 1911 // The types we'll try to promote to, in the appropriate 1912 // order. Try each of these types. 1913 QualType PromoteTypes[6] = { 1914 Context.IntTy, Context.UnsignedIntTy, 1915 Context.LongTy, Context.UnsignedLongTy , 1916 Context.LongLongTy, Context.UnsignedLongLongTy 1917 }; 1918 for (int Idx = 0; Idx < 6; ++Idx) { 1919 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1920 if (FromSize < ToSize || 1921 (FromSize == ToSize && 1922 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1923 // We found the type that we can promote to. If this is the 1924 // type we wanted, we have a promotion. Otherwise, no 1925 // promotion. 1926 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1927 } 1928 } 1929 } 1930 1931 // An rvalue for an integral bit-field (9.6) can be converted to an 1932 // rvalue of type int if int can represent all the values of the 1933 // bit-field; otherwise, it can be converted to unsigned int if 1934 // unsigned int can represent all the values of the bit-field. If 1935 // the bit-field is larger yet, no integral promotion applies to 1936 // it. If the bit-field has an enumerated type, it is treated as any 1937 // other value of that type for promotion purposes (C++ 4.5p3). 1938 // FIXME: We should delay checking of bit-fields until we actually perform the 1939 // conversion. 1940 if (From) { 1941 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1942 llvm::APSInt BitWidth; 1943 if (FromType->isIntegralType(Context) && 1944 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1945 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1946 ToSize = Context.getTypeSize(ToType); 1947 1948 // Are we promoting to an int from a bitfield that fits in an int? 1949 if (BitWidth < ToSize || 1950 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1951 return To->getKind() == BuiltinType::Int; 1952 } 1953 1954 // Are we promoting to an unsigned int from an unsigned bitfield 1955 // that fits into an unsigned int? 1956 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1957 return To->getKind() == BuiltinType::UInt; 1958 } 1959 1960 return false; 1961 } 1962 } 1963 } 1964 1965 // An rvalue of type bool can be converted to an rvalue of type int, 1966 // with false becoming zero and true becoming one (C++ 4.5p4). 1967 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1968 return true; 1969 } 1970 1971 return false; 1972 } 1973 1974 /// IsFloatingPointPromotion - Determines whether the conversion from 1975 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1976 /// returns true and sets PromotedType to the promoted type. 1977 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1978 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1979 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1980 /// An rvalue of type float can be converted to an rvalue of type 1981 /// double. (C++ 4.6p1). 1982 if (FromBuiltin->getKind() == BuiltinType::Float && 1983 ToBuiltin->getKind() == BuiltinType::Double) 1984 return true; 1985 1986 // C99 6.3.1.5p1: 1987 // When a float is promoted to double or long double, or a 1988 // double is promoted to long double [...]. 1989 if (!getLangOpts().CPlusPlus && 1990 (FromBuiltin->getKind() == BuiltinType::Float || 1991 FromBuiltin->getKind() == BuiltinType::Double) && 1992 (ToBuiltin->getKind() == BuiltinType::LongDouble || 1993 ToBuiltin->getKind() == BuiltinType::Float128)) 1994 return true; 1995 1996 // Half can be promoted to float. 1997 if (!getLangOpts().NativeHalfType && 1998 FromBuiltin->getKind() == BuiltinType::Half && 1999 ToBuiltin->getKind() == BuiltinType::Float) 2000 return true; 2001 } 2002 2003 return false; 2004 } 2005 2006 /// \brief Determine if a conversion is a complex promotion. 2007 /// 2008 /// A complex promotion is defined as a complex -> complex conversion 2009 /// where the conversion between the underlying real types is a 2010 /// floating-point or integral promotion. 2011 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2012 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2013 if (!FromComplex) 2014 return false; 2015 2016 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2017 if (!ToComplex) 2018 return false; 2019 2020 return IsFloatingPointPromotion(FromComplex->getElementType(), 2021 ToComplex->getElementType()) || 2022 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2023 ToComplex->getElementType()); 2024 } 2025 2026 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2027 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2028 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2029 /// if non-empty, will be a pointer to ToType that may or may not have 2030 /// the right set of qualifiers on its pointee. 2031 /// 2032 static QualType 2033 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2034 QualType ToPointee, QualType ToType, 2035 ASTContext &Context, 2036 bool StripObjCLifetime = false) { 2037 assert((FromPtr->getTypeClass() == Type::Pointer || 2038 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2039 "Invalid similarly-qualified pointer type"); 2040 2041 /// Conversions to 'id' subsume cv-qualifier conversions. 2042 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2043 return ToType.getUnqualifiedType(); 2044 2045 QualType CanonFromPointee 2046 = Context.getCanonicalType(FromPtr->getPointeeType()); 2047 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2048 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2049 2050 if (StripObjCLifetime) 2051 Quals.removeObjCLifetime(); 2052 2053 // Exact qualifier match -> return the pointer type we're converting to. 2054 if (CanonToPointee.getLocalQualifiers() == Quals) { 2055 // ToType is exactly what we need. Return it. 2056 if (!ToType.isNull()) 2057 return ToType.getUnqualifiedType(); 2058 2059 // Build a pointer to ToPointee. It has the right qualifiers 2060 // already. 2061 if (isa<ObjCObjectPointerType>(ToType)) 2062 return Context.getObjCObjectPointerType(ToPointee); 2063 return Context.getPointerType(ToPointee); 2064 } 2065 2066 // Just build a canonical type that has the right qualifiers. 2067 QualType QualifiedCanonToPointee 2068 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2069 2070 if (isa<ObjCObjectPointerType>(ToType)) 2071 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2072 return Context.getPointerType(QualifiedCanonToPointee); 2073 } 2074 2075 static bool isNullPointerConstantForConversion(Expr *Expr, 2076 bool InOverloadResolution, 2077 ASTContext &Context) { 2078 // Handle value-dependent integral null pointer constants correctly. 2079 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2080 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2081 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2082 return !InOverloadResolution; 2083 2084 return Expr->isNullPointerConstant(Context, 2085 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2086 : Expr::NPC_ValueDependentIsNull); 2087 } 2088 2089 /// IsPointerConversion - Determines whether the conversion of the 2090 /// expression From, which has the (possibly adjusted) type FromType, 2091 /// can be converted to the type ToType via a pointer conversion (C++ 2092 /// 4.10). If so, returns true and places the converted type (that 2093 /// might differ from ToType in its cv-qualifiers at some level) into 2094 /// ConvertedType. 2095 /// 2096 /// This routine also supports conversions to and from block pointers 2097 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2098 /// pointers to interfaces. FIXME: Once we've determined the 2099 /// appropriate overloading rules for Objective-C, we may want to 2100 /// split the Objective-C checks into a different routine; however, 2101 /// GCC seems to consider all of these conversions to be pointer 2102 /// conversions, so for now they live here. IncompatibleObjC will be 2103 /// set if the conversion is an allowed Objective-C conversion that 2104 /// should result in a warning. 2105 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2106 bool InOverloadResolution, 2107 QualType& ConvertedType, 2108 bool &IncompatibleObjC) { 2109 IncompatibleObjC = false; 2110 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2111 IncompatibleObjC)) 2112 return true; 2113 2114 // Conversion from a null pointer constant to any Objective-C pointer type. 2115 if (ToType->isObjCObjectPointerType() && 2116 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2117 ConvertedType = ToType; 2118 return true; 2119 } 2120 2121 // Blocks: Block pointers can be converted to void*. 2122 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2123 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2124 ConvertedType = ToType; 2125 return true; 2126 } 2127 // Blocks: A null pointer constant can be converted to a block 2128 // pointer type. 2129 if (ToType->isBlockPointerType() && 2130 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2131 ConvertedType = ToType; 2132 return true; 2133 } 2134 2135 // If the left-hand-side is nullptr_t, the right side can be a null 2136 // pointer constant. 2137 if (ToType->isNullPtrType() && 2138 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2139 ConvertedType = ToType; 2140 return true; 2141 } 2142 2143 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2144 if (!ToTypePtr) 2145 return false; 2146 2147 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2148 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2149 ConvertedType = ToType; 2150 return true; 2151 } 2152 2153 // Beyond this point, both types need to be pointers 2154 // , including objective-c pointers. 2155 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2156 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2157 !getLangOpts().ObjCAutoRefCount) { 2158 ConvertedType = BuildSimilarlyQualifiedPointerType( 2159 FromType->getAs<ObjCObjectPointerType>(), 2160 ToPointeeType, 2161 ToType, Context); 2162 return true; 2163 } 2164 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2165 if (!FromTypePtr) 2166 return false; 2167 2168 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2169 2170 // If the unqualified pointee types are the same, this can't be a 2171 // pointer conversion, so don't do all of the work below. 2172 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2173 return false; 2174 2175 // An rvalue of type "pointer to cv T," where T is an object type, 2176 // can be converted to an rvalue of type "pointer to cv void" (C++ 2177 // 4.10p2). 2178 if (FromPointeeType->isIncompleteOrObjectType() && 2179 ToPointeeType->isVoidType()) { 2180 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2181 ToPointeeType, 2182 ToType, Context, 2183 /*StripObjCLifetime=*/true); 2184 return true; 2185 } 2186 2187 // MSVC allows implicit function to void* type conversion. 2188 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2189 ToPointeeType->isVoidType()) { 2190 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2191 ToPointeeType, 2192 ToType, Context); 2193 return true; 2194 } 2195 2196 // When we're overloading in C, we allow a special kind of pointer 2197 // conversion for compatible-but-not-identical pointee types. 2198 if (!getLangOpts().CPlusPlus && 2199 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2200 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2201 ToPointeeType, 2202 ToType, Context); 2203 return true; 2204 } 2205 2206 // C++ [conv.ptr]p3: 2207 // 2208 // An rvalue of type "pointer to cv D," where D is a class type, 2209 // can be converted to an rvalue of type "pointer to cv B," where 2210 // B is a base class (clause 10) of D. If B is an inaccessible 2211 // (clause 11) or ambiguous (10.2) base class of D, a program that 2212 // necessitates this conversion is ill-formed. The result of the 2213 // conversion is a pointer to the base class sub-object of the 2214 // derived class object. The null pointer value is converted to 2215 // the null pointer value of the destination type. 2216 // 2217 // Note that we do not check for ambiguity or inaccessibility 2218 // here. That is handled by CheckPointerConversion. 2219 if (getLangOpts().CPlusPlus && 2220 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2221 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2222 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2223 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2224 ToPointeeType, 2225 ToType, Context); 2226 return true; 2227 } 2228 2229 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2230 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2231 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2232 ToPointeeType, 2233 ToType, Context); 2234 return true; 2235 } 2236 2237 return false; 2238 } 2239 2240 /// \brief Adopt the given qualifiers for the given type. 2241 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2242 Qualifiers TQs = T.getQualifiers(); 2243 2244 // Check whether qualifiers already match. 2245 if (TQs == Qs) 2246 return T; 2247 2248 if (Qs.compatiblyIncludes(TQs)) 2249 return Context.getQualifiedType(T, Qs); 2250 2251 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2252 } 2253 2254 /// isObjCPointerConversion - Determines whether this is an 2255 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2256 /// with the same arguments and return values. 2257 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2258 QualType& ConvertedType, 2259 bool &IncompatibleObjC) { 2260 if (!getLangOpts().ObjC1) 2261 return false; 2262 2263 // The set of qualifiers on the type we're converting from. 2264 Qualifiers FromQualifiers = FromType.getQualifiers(); 2265 2266 // First, we handle all conversions on ObjC object pointer types. 2267 const ObjCObjectPointerType* ToObjCPtr = 2268 ToType->getAs<ObjCObjectPointerType>(); 2269 const ObjCObjectPointerType *FromObjCPtr = 2270 FromType->getAs<ObjCObjectPointerType>(); 2271 2272 if (ToObjCPtr && FromObjCPtr) { 2273 // If the pointee types are the same (ignoring qualifications), 2274 // then this is not a pointer conversion. 2275 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2276 FromObjCPtr->getPointeeType())) 2277 return false; 2278 2279 // Conversion between Objective-C pointers. 2280 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2281 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2282 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2283 if (getLangOpts().CPlusPlus && LHS && RHS && 2284 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2285 FromObjCPtr->getPointeeType())) 2286 return false; 2287 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2288 ToObjCPtr->getPointeeType(), 2289 ToType, Context); 2290 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2291 return true; 2292 } 2293 2294 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2295 // Okay: this is some kind of implicit downcast of Objective-C 2296 // interfaces, which is permitted. However, we're going to 2297 // complain about it. 2298 IncompatibleObjC = true; 2299 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2300 ToObjCPtr->getPointeeType(), 2301 ToType, Context); 2302 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2303 return true; 2304 } 2305 } 2306 // Beyond this point, both types need to be C pointers or block pointers. 2307 QualType ToPointeeType; 2308 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2309 ToPointeeType = ToCPtr->getPointeeType(); 2310 else if (const BlockPointerType *ToBlockPtr = 2311 ToType->getAs<BlockPointerType>()) { 2312 // Objective C++: We're able to convert from a pointer to any object 2313 // to a block pointer type. 2314 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2315 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2316 return true; 2317 } 2318 ToPointeeType = ToBlockPtr->getPointeeType(); 2319 } 2320 else if (FromType->getAs<BlockPointerType>() && 2321 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2322 // Objective C++: We're able to convert from a block pointer type to a 2323 // pointer to any object. 2324 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2325 return true; 2326 } 2327 else 2328 return false; 2329 2330 QualType FromPointeeType; 2331 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2332 FromPointeeType = FromCPtr->getPointeeType(); 2333 else if (const BlockPointerType *FromBlockPtr = 2334 FromType->getAs<BlockPointerType>()) 2335 FromPointeeType = FromBlockPtr->getPointeeType(); 2336 else 2337 return false; 2338 2339 // If we have pointers to pointers, recursively check whether this 2340 // is an Objective-C conversion. 2341 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2342 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2343 IncompatibleObjC)) { 2344 // We always complain about this conversion. 2345 IncompatibleObjC = true; 2346 ConvertedType = Context.getPointerType(ConvertedType); 2347 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2348 return true; 2349 } 2350 // Allow conversion of pointee being objective-c pointer to another one; 2351 // as in I* to id. 2352 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2353 ToPointeeType->getAs<ObjCObjectPointerType>() && 2354 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2355 IncompatibleObjC)) { 2356 2357 ConvertedType = Context.getPointerType(ConvertedType); 2358 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2359 return true; 2360 } 2361 2362 // If we have pointers to functions or blocks, check whether the only 2363 // differences in the argument and result types are in Objective-C 2364 // pointer conversions. If so, we permit the conversion (but 2365 // complain about it). 2366 const FunctionProtoType *FromFunctionType 2367 = FromPointeeType->getAs<FunctionProtoType>(); 2368 const FunctionProtoType *ToFunctionType 2369 = ToPointeeType->getAs<FunctionProtoType>(); 2370 if (FromFunctionType && ToFunctionType) { 2371 // If the function types are exactly the same, this isn't an 2372 // Objective-C pointer conversion. 2373 if (Context.getCanonicalType(FromPointeeType) 2374 == Context.getCanonicalType(ToPointeeType)) 2375 return false; 2376 2377 // Perform the quick checks that will tell us whether these 2378 // function types are obviously different. 2379 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2380 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2381 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2382 return false; 2383 2384 bool HasObjCConversion = false; 2385 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2386 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2387 // Okay, the types match exactly. Nothing to do. 2388 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2389 ToFunctionType->getReturnType(), 2390 ConvertedType, IncompatibleObjC)) { 2391 // Okay, we have an Objective-C pointer conversion. 2392 HasObjCConversion = true; 2393 } else { 2394 // Function types are too different. Abort. 2395 return false; 2396 } 2397 2398 // Check argument types. 2399 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2400 ArgIdx != NumArgs; ++ArgIdx) { 2401 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2402 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2403 if (Context.getCanonicalType(FromArgType) 2404 == Context.getCanonicalType(ToArgType)) { 2405 // Okay, the types match exactly. Nothing to do. 2406 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2407 ConvertedType, IncompatibleObjC)) { 2408 // Okay, we have an Objective-C pointer conversion. 2409 HasObjCConversion = true; 2410 } else { 2411 // Argument types are too different. Abort. 2412 return false; 2413 } 2414 } 2415 2416 if (HasObjCConversion) { 2417 // We had an Objective-C conversion. Allow this pointer 2418 // conversion, but complain about it. 2419 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2420 IncompatibleObjC = true; 2421 return true; 2422 } 2423 } 2424 2425 return false; 2426 } 2427 2428 /// \brief Determine whether this is an Objective-C writeback conversion, 2429 /// used for parameter passing when performing automatic reference counting. 2430 /// 2431 /// \param FromType The type we're converting form. 2432 /// 2433 /// \param ToType The type we're converting to. 2434 /// 2435 /// \param ConvertedType The type that will be produced after applying 2436 /// this conversion. 2437 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2438 QualType &ConvertedType) { 2439 if (!getLangOpts().ObjCAutoRefCount || 2440 Context.hasSameUnqualifiedType(FromType, ToType)) 2441 return false; 2442 2443 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2444 QualType ToPointee; 2445 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2446 ToPointee = ToPointer->getPointeeType(); 2447 else 2448 return false; 2449 2450 Qualifiers ToQuals = ToPointee.getQualifiers(); 2451 if (!ToPointee->isObjCLifetimeType() || 2452 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2453 !ToQuals.withoutObjCLifetime().empty()) 2454 return false; 2455 2456 // Argument must be a pointer to __strong to __weak. 2457 QualType FromPointee; 2458 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2459 FromPointee = FromPointer->getPointeeType(); 2460 else 2461 return false; 2462 2463 Qualifiers FromQuals = FromPointee.getQualifiers(); 2464 if (!FromPointee->isObjCLifetimeType() || 2465 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2466 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2467 return false; 2468 2469 // Make sure that we have compatible qualifiers. 2470 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2471 if (!ToQuals.compatiblyIncludes(FromQuals)) 2472 return false; 2473 2474 // Remove qualifiers from the pointee type we're converting from; they 2475 // aren't used in the compatibility check belong, and we'll be adding back 2476 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2477 FromPointee = FromPointee.getUnqualifiedType(); 2478 2479 // The unqualified form of the pointee types must be compatible. 2480 ToPointee = ToPointee.getUnqualifiedType(); 2481 bool IncompatibleObjC; 2482 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2483 FromPointee = ToPointee; 2484 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2485 IncompatibleObjC)) 2486 return false; 2487 2488 /// \brief Construct the type we're converting to, which is a pointer to 2489 /// __autoreleasing pointee. 2490 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2491 ConvertedType = Context.getPointerType(FromPointee); 2492 return true; 2493 } 2494 2495 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2496 QualType& ConvertedType) { 2497 QualType ToPointeeType; 2498 if (const BlockPointerType *ToBlockPtr = 2499 ToType->getAs<BlockPointerType>()) 2500 ToPointeeType = ToBlockPtr->getPointeeType(); 2501 else 2502 return false; 2503 2504 QualType FromPointeeType; 2505 if (const BlockPointerType *FromBlockPtr = 2506 FromType->getAs<BlockPointerType>()) 2507 FromPointeeType = FromBlockPtr->getPointeeType(); 2508 else 2509 return false; 2510 // We have pointer to blocks, check whether the only 2511 // differences in the argument and result types are in Objective-C 2512 // pointer conversions. If so, we permit the conversion. 2513 2514 const FunctionProtoType *FromFunctionType 2515 = FromPointeeType->getAs<FunctionProtoType>(); 2516 const FunctionProtoType *ToFunctionType 2517 = ToPointeeType->getAs<FunctionProtoType>(); 2518 2519 if (!FromFunctionType || !ToFunctionType) 2520 return false; 2521 2522 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2523 return true; 2524 2525 // Perform the quick checks that will tell us whether these 2526 // function types are obviously different. 2527 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2528 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2529 return false; 2530 2531 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2532 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2533 if (FromEInfo != ToEInfo) 2534 return false; 2535 2536 bool IncompatibleObjC = false; 2537 if (Context.hasSameType(FromFunctionType->getReturnType(), 2538 ToFunctionType->getReturnType())) { 2539 // Okay, the types match exactly. Nothing to do. 2540 } else { 2541 QualType RHS = FromFunctionType->getReturnType(); 2542 QualType LHS = ToFunctionType->getReturnType(); 2543 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2544 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2545 LHS = LHS.getUnqualifiedType(); 2546 2547 if (Context.hasSameType(RHS,LHS)) { 2548 // OK exact match. 2549 } else if (isObjCPointerConversion(RHS, LHS, 2550 ConvertedType, IncompatibleObjC)) { 2551 if (IncompatibleObjC) 2552 return false; 2553 // Okay, we have an Objective-C pointer conversion. 2554 } 2555 else 2556 return false; 2557 } 2558 2559 // Check argument types. 2560 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2561 ArgIdx != NumArgs; ++ArgIdx) { 2562 IncompatibleObjC = false; 2563 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2564 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2565 if (Context.hasSameType(FromArgType, ToArgType)) { 2566 // Okay, the types match exactly. Nothing to do. 2567 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2568 ConvertedType, IncompatibleObjC)) { 2569 if (IncompatibleObjC) 2570 return false; 2571 // Okay, we have an Objective-C pointer conversion. 2572 } else 2573 // Argument types are too different. Abort. 2574 return false; 2575 } 2576 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2577 ToFunctionType)) 2578 return false; 2579 2580 ConvertedType = ToType; 2581 return true; 2582 } 2583 2584 enum { 2585 ft_default, 2586 ft_different_class, 2587 ft_parameter_arity, 2588 ft_parameter_mismatch, 2589 ft_return_type, 2590 ft_qualifer_mismatch 2591 }; 2592 2593 /// Attempts to get the FunctionProtoType from a Type. Handles 2594 /// MemberFunctionPointers properly. 2595 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2596 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2597 return FPT; 2598 2599 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2600 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2601 2602 return nullptr; 2603 } 2604 2605 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2606 /// function types. Catches different number of parameter, mismatch in 2607 /// parameter types, and different return types. 2608 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2609 QualType FromType, QualType ToType) { 2610 // If either type is not valid, include no extra info. 2611 if (FromType.isNull() || ToType.isNull()) { 2612 PDiag << ft_default; 2613 return; 2614 } 2615 2616 // Get the function type from the pointers. 2617 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2618 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2619 *ToMember = ToType->getAs<MemberPointerType>(); 2620 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2621 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2622 << QualType(FromMember->getClass(), 0); 2623 return; 2624 } 2625 FromType = FromMember->getPointeeType(); 2626 ToType = ToMember->getPointeeType(); 2627 } 2628 2629 if (FromType->isPointerType()) 2630 FromType = FromType->getPointeeType(); 2631 if (ToType->isPointerType()) 2632 ToType = ToType->getPointeeType(); 2633 2634 // Remove references. 2635 FromType = FromType.getNonReferenceType(); 2636 ToType = ToType.getNonReferenceType(); 2637 2638 // Don't print extra info for non-specialized template functions. 2639 if (FromType->isInstantiationDependentType() && 2640 !FromType->getAs<TemplateSpecializationType>()) { 2641 PDiag << ft_default; 2642 return; 2643 } 2644 2645 // No extra info for same types. 2646 if (Context.hasSameType(FromType, ToType)) { 2647 PDiag << ft_default; 2648 return; 2649 } 2650 2651 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2652 *ToFunction = tryGetFunctionProtoType(ToType); 2653 2654 // Both types need to be function types. 2655 if (!FromFunction || !ToFunction) { 2656 PDiag << ft_default; 2657 return; 2658 } 2659 2660 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2661 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2662 << FromFunction->getNumParams(); 2663 return; 2664 } 2665 2666 // Handle different parameter types. 2667 unsigned ArgPos; 2668 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2669 PDiag << ft_parameter_mismatch << ArgPos + 1 2670 << ToFunction->getParamType(ArgPos) 2671 << FromFunction->getParamType(ArgPos); 2672 return; 2673 } 2674 2675 // Handle different return type. 2676 if (!Context.hasSameType(FromFunction->getReturnType(), 2677 ToFunction->getReturnType())) { 2678 PDiag << ft_return_type << ToFunction->getReturnType() 2679 << FromFunction->getReturnType(); 2680 return; 2681 } 2682 2683 unsigned FromQuals = FromFunction->getTypeQuals(), 2684 ToQuals = ToFunction->getTypeQuals(); 2685 if (FromQuals != ToQuals) { 2686 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2687 return; 2688 } 2689 2690 // Unable to find a difference, so add no extra info. 2691 PDiag << ft_default; 2692 } 2693 2694 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2695 /// for equality of their argument types. Caller has already checked that 2696 /// they have same number of arguments. If the parameters are different, 2697 /// ArgPos will have the parameter index of the first different parameter. 2698 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2699 const FunctionProtoType *NewType, 2700 unsigned *ArgPos) { 2701 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2702 N = NewType->param_type_begin(), 2703 E = OldType->param_type_end(); 2704 O && (O != E); ++O, ++N) { 2705 if (!Context.hasSameType(O->getUnqualifiedType(), 2706 N->getUnqualifiedType())) { 2707 if (ArgPos) 2708 *ArgPos = O - OldType->param_type_begin(); 2709 return false; 2710 } 2711 } 2712 return true; 2713 } 2714 2715 /// CheckPointerConversion - Check the pointer conversion from the 2716 /// expression From to the type ToType. This routine checks for 2717 /// ambiguous or inaccessible derived-to-base pointer 2718 /// conversions for which IsPointerConversion has already returned 2719 /// true. It returns true and produces a diagnostic if there was an 2720 /// error, or returns false otherwise. 2721 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2722 CastKind &Kind, 2723 CXXCastPath& BasePath, 2724 bool IgnoreBaseAccess, 2725 bool Diagnose) { 2726 QualType FromType = From->getType(); 2727 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2728 2729 Kind = CK_BitCast; 2730 2731 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2732 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2733 Expr::NPCK_ZeroExpression) { 2734 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2735 DiagRuntimeBehavior(From->getExprLoc(), From, 2736 PDiag(diag::warn_impcast_bool_to_null_pointer) 2737 << ToType << From->getSourceRange()); 2738 else if (!isUnevaluatedContext()) 2739 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2740 << ToType << From->getSourceRange(); 2741 } 2742 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2743 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2744 QualType FromPointeeType = FromPtrType->getPointeeType(), 2745 ToPointeeType = ToPtrType->getPointeeType(); 2746 2747 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2748 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2749 // We must have a derived-to-base conversion. Check an 2750 // ambiguous or inaccessible conversion. 2751 unsigned InaccessibleID = 0; 2752 unsigned AmbigiousID = 0; 2753 if (Diagnose) { 2754 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2755 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2756 } 2757 if (CheckDerivedToBaseConversion( 2758 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2759 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2760 &BasePath, IgnoreBaseAccess)) 2761 return true; 2762 2763 // The conversion was successful. 2764 Kind = CK_DerivedToBase; 2765 } 2766 2767 if (Diagnose && !IsCStyleOrFunctionalCast && 2768 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2769 assert(getLangOpts().MSVCCompat && 2770 "this should only be possible with MSVCCompat!"); 2771 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2772 << From->getSourceRange(); 2773 } 2774 } 2775 } else if (const ObjCObjectPointerType *ToPtrType = 2776 ToType->getAs<ObjCObjectPointerType>()) { 2777 if (const ObjCObjectPointerType *FromPtrType = 2778 FromType->getAs<ObjCObjectPointerType>()) { 2779 // Objective-C++ conversions are always okay. 2780 // FIXME: We should have a different class of conversions for the 2781 // Objective-C++ implicit conversions. 2782 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2783 return false; 2784 } else if (FromType->isBlockPointerType()) { 2785 Kind = CK_BlockPointerToObjCPointerCast; 2786 } else { 2787 Kind = CK_CPointerToObjCPointerCast; 2788 } 2789 } else if (ToType->isBlockPointerType()) { 2790 if (!FromType->isBlockPointerType()) 2791 Kind = CK_AnyPointerToBlockPointerCast; 2792 } 2793 2794 // We shouldn't fall into this case unless it's valid for other 2795 // reasons. 2796 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2797 Kind = CK_NullToPointer; 2798 2799 return false; 2800 } 2801 2802 /// IsMemberPointerConversion - Determines whether the conversion of the 2803 /// expression From, which has the (possibly adjusted) type FromType, can be 2804 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2805 /// If so, returns true and places the converted type (that might differ from 2806 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2807 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2808 QualType ToType, 2809 bool InOverloadResolution, 2810 QualType &ConvertedType) { 2811 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2812 if (!ToTypePtr) 2813 return false; 2814 2815 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2816 if (From->isNullPointerConstant(Context, 2817 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2818 : Expr::NPC_ValueDependentIsNull)) { 2819 ConvertedType = ToType; 2820 return true; 2821 } 2822 2823 // Otherwise, both types have to be member pointers. 2824 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2825 if (!FromTypePtr) 2826 return false; 2827 2828 // A pointer to member of B can be converted to a pointer to member of D, 2829 // where D is derived from B (C++ 4.11p2). 2830 QualType FromClass(FromTypePtr->getClass(), 0); 2831 QualType ToClass(ToTypePtr->getClass(), 0); 2832 2833 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2834 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2835 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2836 ToClass.getTypePtr()); 2837 return true; 2838 } 2839 2840 return false; 2841 } 2842 2843 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2844 /// expression From to the type ToType. This routine checks for ambiguous or 2845 /// virtual or inaccessible base-to-derived member pointer conversions 2846 /// for which IsMemberPointerConversion has already returned true. It returns 2847 /// true and produces a diagnostic if there was an error, or returns false 2848 /// otherwise. 2849 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2850 CastKind &Kind, 2851 CXXCastPath &BasePath, 2852 bool IgnoreBaseAccess) { 2853 QualType FromType = From->getType(); 2854 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2855 if (!FromPtrType) { 2856 // This must be a null pointer to member pointer conversion 2857 assert(From->isNullPointerConstant(Context, 2858 Expr::NPC_ValueDependentIsNull) && 2859 "Expr must be null pointer constant!"); 2860 Kind = CK_NullToMemberPointer; 2861 return false; 2862 } 2863 2864 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2865 assert(ToPtrType && "No member pointer cast has a target type " 2866 "that is not a member pointer."); 2867 2868 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2869 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2870 2871 // FIXME: What about dependent types? 2872 assert(FromClass->isRecordType() && "Pointer into non-class."); 2873 assert(ToClass->isRecordType() && "Pointer into non-class."); 2874 2875 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2876 /*DetectVirtual=*/true); 2877 bool DerivationOkay = 2878 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2879 assert(DerivationOkay && 2880 "Should not have been called if derivation isn't OK."); 2881 (void)DerivationOkay; 2882 2883 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2884 getUnqualifiedType())) { 2885 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2886 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2887 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2888 return true; 2889 } 2890 2891 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2892 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2893 << FromClass << ToClass << QualType(VBase, 0) 2894 << From->getSourceRange(); 2895 return true; 2896 } 2897 2898 if (!IgnoreBaseAccess) 2899 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2900 Paths.front(), 2901 diag::err_downcast_from_inaccessible_base); 2902 2903 // Must be a base to derived member conversion. 2904 BuildBasePathArray(Paths, BasePath); 2905 Kind = CK_BaseToDerivedMemberPointer; 2906 return false; 2907 } 2908 2909 /// Determine whether the lifetime conversion between the two given 2910 /// qualifiers sets is nontrivial. 2911 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2912 Qualifiers ToQuals) { 2913 // Converting anything to const __unsafe_unretained is trivial. 2914 if (ToQuals.hasConst() && 2915 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2916 return false; 2917 2918 return true; 2919 } 2920 2921 /// IsQualificationConversion - Determines whether the conversion from 2922 /// an rvalue of type FromType to ToType is a qualification conversion 2923 /// (C++ 4.4). 2924 /// 2925 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2926 /// when the qualification conversion involves a change in the Objective-C 2927 /// object lifetime. 2928 bool 2929 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2930 bool CStyle, bool &ObjCLifetimeConversion) { 2931 FromType = Context.getCanonicalType(FromType); 2932 ToType = Context.getCanonicalType(ToType); 2933 ObjCLifetimeConversion = false; 2934 2935 // If FromType and ToType are the same type, this is not a 2936 // qualification conversion. 2937 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2938 return false; 2939 2940 // (C++ 4.4p4): 2941 // A conversion can add cv-qualifiers at levels other than the first 2942 // in multi-level pointers, subject to the following rules: [...] 2943 bool PreviousToQualsIncludeConst = true; 2944 bool UnwrappedAnyPointer = false; 2945 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2946 // Within each iteration of the loop, we check the qualifiers to 2947 // determine if this still looks like a qualification 2948 // conversion. Then, if all is well, we unwrap one more level of 2949 // pointers or pointers-to-members and do it all again 2950 // until there are no more pointers or pointers-to-members left to 2951 // unwrap. 2952 UnwrappedAnyPointer = true; 2953 2954 Qualifiers FromQuals = FromType.getQualifiers(); 2955 Qualifiers ToQuals = ToType.getQualifiers(); 2956 2957 // Ignore __unaligned qualifier if this type is void. 2958 if (ToType.getUnqualifiedType()->isVoidType()) 2959 FromQuals.removeUnaligned(); 2960 2961 // Objective-C ARC: 2962 // Check Objective-C lifetime conversions. 2963 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2964 UnwrappedAnyPointer) { 2965 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2966 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2967 ObjCLifetimeConversion = true; 2968 FromQuals.removeObjCLifetime(); 2969 ToQuals.removeObjCLifetime(); 2970 } else { 2971 // Qualification conversions cannot cast between different 2972 // Objective-C lifetime qualifiers. 2973 return false; 2974 } 2975 } 2976 2977 // Allow addition/removal of GC attributes but not changing GC attributes. 2978 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2979 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2980 FromQuals.removeObjCGCAttr(); 2981 ToQuals.removeObjCGCAttr(); 2982 } 2983 2984 // -- for every j > 0, if const is in cv 1,j then const is in cv 2985 // 2,j, and similarly for volatile. 2986 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2987 return false; 2988 2989 // -- if the cv 1,j and cv 2,j are different, then const is in 2990 // every cv for 0 < k < j. 2991 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2992 && !PreviousToQualsIncludeConst) 2993 return false; 2994 2995 // Keep track of whether all prior cv-qualifiers in the "to" type 2996 // include const. 2997 PreviousToQualsIncludeConst 2998 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2999 } 3000 3001 // We are left with FromType and ToType being the pointee types 3002 // after unwrapping the original FromType and ToType the same number 3003 // of types. If we unwrapped any pointers, and if FromType and 3004 // ToType have the same unqualified type (since we checked 3005 // qualifiers above), then this is a qualification conversion. 3006 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3007 } 3008 3009 /// \brief - Determine whether this is a conversion from a scalar type to an 3010 /// atomic type. 3011 /// 3012 /// If successful, updates \c SCS's second and third steps in the conversion 3013 /// sequence to finish the conversion. 3014 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3015 bool InOverloadResolution, 3016 StandardConversionSequence &SCS, 3017 bool CStyle) { 3018 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3019 if (!ToAtomic) 3020 return false; 3021 3022 StandardConversionSequence InnerSCS; 3023 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3024 InOverloadResolution, InnerSCS, 3025 CStyle, /*AllowObjCWritebackConversion=*/false)) 3026 return false; 3027 3028 SCS.Second = InnerSCS.Second; 3029 SCS.setToType(1, InnerSCS.getToType(1)); 3030 SCS.Third = InnerSCS.Third; 3031 SCS.QualificationIncludesObjCLifetime 3032 = InnerSCS.QualificationIncludesObjCLifetime; 3033 SCS.setToType(2, InnerSCS.getToType(2)); 3034 return true; 3035 } 3036 3037 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3038 CXXConstructorDecl *Constructor, 3039 QualType Type) { 3040 const FunctionProtoType *CtorType = 3041 Constructor->getType()->getAs<FunctionProtoType>(); 3042 if (CtorType->getNumParams() > 0) { 3043 QualType FirstArg = CtorType->getParamType(0); 3044 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3045 return true; 3046 } 3047 return false; 3048 } 3049 3050 static OverloadingResult 3051 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3052 CXXRecordDecl *To, 3053 UserDefinedConversionSequence &User, 3054 OverloadCandidateSet &CandidateSet, 3055 bool AllowExplicit) { 3056 for (auto *D : S.LookupConstructors(To)) { 3057 auto Info = getConstructorInfo(D); 3058 if (!Info) 3059 continue; 3060 3061 bool Usable = !Info.Constructor->isInvalidDecl() && 3062 S.isInitListConstructor(Info.Constructor) && 3063 (AllowExplicit || !Info.Constructor->isExplicit()); 3064 if (Usable) { 3065 // If the first argument is (a reference to) the target type, 3066 // suppress conversions. 3067 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3068 S.Context, Info.Constructor, ToType); 3069 if (Info.ConstructorTmpl) 3070 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3071 /*ExplicitArgs*/ nullptr, From, 3072 CandidateSet, SuppressUserConversions); 3073 else 3074 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3075 CandidateSet, SuppressUserConversions); 3076 } 3077 } 3078 3079 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3080 3081 OverloadCandidateSet::iterator Best; 3082 switch (auto Result = 3083 CandidateSet.BestViableFunction(S, From->getLocStart(), 3084 Best, true)) { 3085 case OR_Deleted: 3086 case OR_Success: { 3087 // Record the standard conversion we used and the conversion function. 3088 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3089 QualType ThisType = Constructor->getThisType(S.Context); 3090 // Initializer lists don't have conversions as such. 3091 User.Before.setAsIdentityConversion(); 3092 User.HadMultipleCandidates = HadMultipleCandidates; 3093 User.ConversionFunction = Constructor; 3094 User.FoundConversionFunction = Best->FoundDecl; 3095 User.After.setAsIdentityConversion(); 3096 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3097 User.After.setAllToTypes(ToType); 3098 return Result; 3099 } 3100 3101 case OR_No_Viable_Function: 3102 return OR_No_Viable_Function; 3103 case OR_Ambiguous: 3104 return OR_Ambiguous; 3105 } 3106 3107 llvm_unreachable("Invalid OverloadResult!"); 3108 } 3109 3110 /// Determines whether there is a user-defined conversion sequence 3111 /// (C++ [over.ics.user]) that converts expression From to the type 3112 /// ToType. If such a conversion exists, User will contain the 3113 /// user-defined conversion sequence that performs such a conversion 3114 /// and this routine will return true. Otherwise, this routine returns 3115 /// false and User is unspecified. 3116 /// 3117 /// \param AllowExplicit true if the conversion should consider C++0x 3118 /// "explicit" conversion functions as well as non-explicit conversion 3119 /// functions (C++0x [class.conv.fct]p2). 3120 /// 3121 /// \param AllowObjCConversionOnExplicit true if the conversion should 3122 /// allow an extra Objective-C pointer conversion on uses of explicit 3123 /// constructors. Requires \c AllowExplicit to also be set. 3124 static OverloadingResult 3125 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3126 UserDefinedConversionSequence &User, 3127 OverloadCandidateSet &CandidateSet, 3128 bool AllowExplicit, 3129 bool AllowObjCConversionOnExplicit) { 3130 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3131 3132 // Whether we will only visit constructors. 3133 bool ConstructorsOnly = false; 3134 3135 // If the type we are conversion to is a class type, enumerate its 3136 // constructors. 3137 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3138 // C++ [over.match.ctor]p1: 3139 // When objects of class type are direct-initialized (8.5), or 3140 // copy-initialized from an expression of the same or a 3141 // derived class type (8.5), overload resolution selects the 3142 // constructor. [...] For copy-initialization, the candidate 3143 // functions are all the converting constructors (12.3.1) of 3144 // that class. The argument list is the expression-list within 3145 // the parentheses of the initializer. 3146 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3147 (From->getType()->getAs<RecordType>() && 3148 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3149 ConstructorsOnly = true; 3150 3151 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3152 // We're not going to find any constructors. 3153 } else if (CXXRecordDecl *ToRecordDecl 3154 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3155 3156 Expr **Args = &From; 3157 unsigned NumArgs = 1; 3158 bool ListInitializing = false; 3159 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3160 // But first, see if there is an init-list-constructor that will work. 3161 OverloadingResult Result = IsInitializerListConstructorConversion( 3162 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3163 if (Result != OR_No_Viable_Function) 3164 return Result; 3165 // Never mind. 3166 CandidateSet.clear(); 3167 3168 // If we're list-initializing, we pass the individual elements as 3169 // arguments, not the entire list. 3170 Args = InitList->getInits(); 3171 NumArgs = InitList->getNumInits(); 3172 ListInitializing = true; 3173 } 3174 3175 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3176 auto Info = getConstructorInfo(D); 3177 if (!Info) 3178 continue; 3179 3180 bool Usable = !Info.Constructor->isInvalidDecl(); 3181 if (ListInitializing) 3182 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3183 else 3184 Usable = Usable && 3185 Info.Constructor->isConvertingConstructor(AllowExplicit); 3186 if (Usable) { 3187 bool SuppressUserConversions = !ConstructorsOnly; 3188 if (SuppressUserConversions && ListInitializing) { 3189 SuppressUserConversions = false; 3190 if (NumArgs == 1) { 3191 // If the first argument is (a reference to) the target type, 3192 // suppress conversions. 3193 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3194 S.Context, Info.Constructor, ToType); 3195 } 3196 } 3197 if (Info.ConstructorTmpl) 3198 S.AddTemplateOverloadCandidate( 3199 Info.ConstructorTmpl, Info.FoundDecl, 3200 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3201 CandidateSet, SuppressUserConversions); 3202 else 3203 // Allow one user-defined conversion when user specifies a 3204 // From->ToType conversion via an static cast (c-style, etc). 3205 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3206 llvm::makeArrayRef(Args, NumArgs), 3207 CandidateSet, SuppressUserConversions); 3208 } 3209 } 3210 } 3211 } 3212 3213 // Enumerate conversion functions, if we're allowed to. 3214 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3215 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3216 // No conversion functions from incomplete types. 3217 } else if (const RecordType *FromRecordType 3218 = From->getType()->getAs<RecordType>()) { 3219 if (CXXRecordDecl *FromRecordDecl 3220 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3221 // Add all of the conversion functions as candidates. 3222 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3223 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3224 DeclAccessPair FoundDecl = I.getPair(); 3225 NamedDecl *D = FoundDecl.getDecl(); 3226 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3227 if (isa<UsingShadowDecl>(D)) 3228 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3229 3230 CXXConversionDecl *Conv; 3231 FunctionTemplateDecl *ConvTemplate; 3232 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3233 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3234 else 3235 Conv = cast<CXXConversionDecl>(D); 3236 3237 if (AllowExplicit || !Conv->isExplicit()) { 3238 if (ConvTemplate) 3239 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3240 ActingContext, From, ToType, 3241 CandidateSet, 3242 AllowObjCConversionOnExplicit); 3243 else 3244 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3245 From, ToType, CandidateSet, 3246 AllowObjCConversionOnExplicit); 3247 } 3248 } 3249 } 3250 } 3251 3252 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3253 3254 OverloadCandidateSet::iterator Best; 3255 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3256 Best, true)) { 3257 case OR_Success: 3258 case OR_Deleted: 3259 // Record the standard conversion we used and the conversion function. 3260 if (CXXConstructorDecl *Constructor 3261 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3262 // C++ [over.ics.user]p1: 3263 // If the user-defined conversion is specified by a 3264 // constructor (12.3.1), the initial standard conversion 3265 // sequence converts the source type to the type required by 3266 // the argument of the constructor. 3267 // 3268 QualType ThisType = Constructor->getThisType(S.Context); 3269 if (isa<InitListExpr>(From)) { 3270 // Initializer lists don't have conversions as such. 3271 User.Before.setAsIdentityConversion(); 3272 } else { 3273 if (Best->Conversions[0].isEllipsis()) 3274 User.EllipsisConversion = true; 3275 else { 3276 User.Before = Best->Conversions[0].Standard; 3277 User.EllipsisConversion = false; 3278 } 3279 } 3280 User.HadMultipleCandidates = HadMultipleCandidates; 3281 User.ConversionFunction = Constructor; 3282 User.FoundConversionFunction = Best->FoundDecl; 3283 User.After.setAsIdentityConversion(); 3284 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3285 User.After.setAllToTypes(ToType); 3286 return Result; 3287 } 3288 if (CXXConversionDecl *Conversion 3289 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3290 // C++ [over.ics.user]p1: 3291 // 3292 // [...] If the user-defined conversion is specified by a 3293 // conversion function (12.3.2), the initial standard 3294 // conversion sequence converts the source type to the 3295 // implicit object parameter of the conversion function. 3296 User.Before = Best->Conversions[0].Standard; 3297 User.HadMultipleCandidates = HadMultipleCandidates; 3298 User.ConversionFunction = Conversion; 3299 User.FoundConversionFunction = Best->FoundDecl; 3300 User.EllipsisConversion = false; 3301 3302 // C++ [over.ics.user]p2: 3303 // The second standard conversion sequence converts the 3304 // result of the user-defined conversion to the target type 3305 // for the sequence. Since an implicit conversion sequence 3306 // is an initialization, the special rules for 3307 // initialization by user-defined conversion apply when 3308 // selecting the best user-defined conversion for a 3309 // user-defined conversion sequence (see 13.3.3 and 3310 // 13.3.3.1). 3311 User.After = Best->FinalConversion; 3312 return Result; 3313 } 3314 llvm_unreachable("Not a constructor or conversion function?"); 3315 3316 case OR_No_Viable_Function: 3317 return OR_No_Viable_Function; 3318 3319 case OR_Ambiguous: 3320 return OR_Ambiguous; 3321 } 3322 3323 llvm_unreachable("Invalid OverloadResult!"); 3324 } 3325 3326 bool 3327 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3328 ImplicitConversionSequence ICS; 3329 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3330 OverloadCandidateSet::CSK_Normal); 3331 OverloadingResult OvResult = 3332 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3333 CandidateSet, false, false); 3334 if (OvResult == OR_Ambiguous) 3335 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3336 << From->getType() << ToType << From->getSourceRange(); 3337 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3338 if (!RequireCompleteType(From->getLocStart(), ToType, 3339 diag::err_typecheck_nonviable_condition_incomplete, 3340 From->getType(), From->getSourceRange())) 3341 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3342 << false << From->getType() << From->getSourceRange() << ToType; 3343 } else 3344 return false; 3345 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3346 return true; 3347 } 3348 3349 /// \brief Compare the user-defined conversion functions or constructors 3350 /// of two user-defined conversion sequences to determine whether any ordering 3351 /// is possible. 3352 static ImplicitConversionSequence::CompareKind 3353 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3354 FunctionDecl *Function2) { 3355 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3356 return ImplicitConversionSequence::Indistinguishable; 3357 3358 // Objective-C++: 3359 // If both conversion functions are implicitly-declared conversions from 3360 // a lambda closure type to a function pointer and a block pointer, 3361 // respectively, always prefer the conversion to a function pointer, 3362 // because the function pointer is more lightweight and is more likely 3363 // to keep code working. 3364 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3365 if (!Conv1) 3366 return ImplicitConversionSequence::Indistinguishable; 3367 3368 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3369 if (!Conv2) 3370 return ImplicitConversionSequence::Indistinguishable; 3371 3372 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3373 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3374 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3375 if (Block1 != Block2) 3376 return Block1 ? ImplicitConversionSequence::Worse 3377 : ImplicitConversionSequence::Better; 3378 } 3379 3380 return ImplicitConversionSequence::Indistinguishable; 3381 } 3382 3383 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3384 const ImplicitConversionSequence &ICS) { 3385 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3386 (ICS.isUserDefined() && 3387 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3388 } 3389 3390 /// CompareImplicitConversionSequences - Compare two implicit 3391 /// conversion sequences to determine whether one is better than the 3392 /// other or if they are indistinguishable (C++ 13.3.3.2). 3393 static ImplicitConversionSequence::CompareKind 3394 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3395 const ImplicitConversionSequence& ICS1, 3396 const ImplicitConversionSequence& ICS2) 3397 { 3398 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3399 // conversion sequences (as defined in 13.3.3.1) 3400 // -- a standard conversion sequence (13.3.3.1.1) is a better 3401 // conversion sequence than a user-defined conversion sequence or 3402 // an ellipsis conversion sequence, and 3403 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3404 // conversion sequence than an ellipsis conversion sequence 3405 // (13.3.3.1.3). 3406 // 3407 // C++0x [over.best.ics]p10: 3408 // For the purpose of ranking implicit conversion sequences as 3409 // described in 13.3.3.2, the ambiguous conversion sequence is 3410 // treated as a user-defined sequence that is indistinguishable 3411 // from any other user-defined conversion sequence. 3412 3413 // String literal to 'char *' conversion has been deprecated in C++03. It has 3414 // been removed from C++11. We still accept this conversion, if it happens at 3415 // the best viable function. Otherwise, this conversion is considered worse 3416 // than ellipsis conversion. Consider this as an extension; this is not in the 3417 // standard. For example: 3418 // 3419 // int &f(...); // #1 3420 // void f(char*); // #2 3421 // void g() { int &r = f("foo"); } 3422 // 3423 // In C++03, we pick #2 as the best viable function. 3424 // In C++11, we pick #1 as the best viable function, because ellipsis 3425 // conversion is better than string-literal to char* conversion (since there 3426 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3427 // convert arguments, #2 would be the best viable function in C++11. 3428 // If the best viable function has this conversion, a warning will be issued 3429 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3430 3431 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3432 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3433 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3434 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3435 ? ImplicitConversionSequence::Worse 3436 : ImplicitConversionSequence::Better; 3437 3438 if (ICS1.getKindRank() < ICS2.getKindRank()) 3439 return ImplicitConversionSequence::Better; 3440 if (ICS2.getKindRank() < ICS1.getKindRank()) 3441 return ImplicitConversionSequence::Worse; 3442 3443 // The following checks require both conversion sequences to be of 3444 // the same kind. 3445 if (ICS1.getKind() != ICS2.getKind()) 3446 return ImplicitConversionSequence::Indistinguishable; 3447 3448 ImplicitConversionSequence::CompareKind Result = 3449 ImplicitConversionSequence::Indistinguishable; 3450 3451 // Two implicit conversion sequences of the same form are 3452 // indistinguishable conversion sequences unless one of the 3453 // following rules apply: (C++ 13.3.3.2p3): 3454 3455 // List-initialization sequence L1 is a better conversion sequence than 3456 // list-initialization sequence L2 if: 3457 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3458 // if not that, 3459 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3460 // and N1 is smaller than N2., 3461 // even if one of the other rules in this paragraph would otherwise apply. 3462 if (!ICS1.isBad()) { 3463 if (ICS1.isStdInitializerListElement() && 3464 !ICS2.isStdInitializerListElement()) 3465 return ImplicitConversionSequence::Better; 3466 if (!ICS1.isStdInitializerListElement() && 3467 ICS2.isStdInitializerListElement()) 3468 return ImplicitConversionSequence::Worse; 3469 } 3470 3471 if (ICS1.isStandard()) 3472 // Standard conversion sequence S1 is a better conversion sequence than 3473 // standard conversion sequence S2 if [...] 3474 Result = CompareStandardConversionSequences(S, Loc, 3475 ICS1.Standard, ICS2.Standard); 3476 else if (ICS1.isUserDefined()) { 3477 // User-defined conversion sequence U1 is a better conversion 3478 // sequence than another user-defined conversion sequence U2 if 3479 // they contain the same user-defined conversion function or 3480 // constructor and if the second standard conversion sequence of 3481 // U1 is better than the second standard conversion sequence of 3482 // U2 (C++ 13.3.3.2p3). 3483 if (ICS1.UserDefined.ConversionFunction == 3484 ICS2.UserDefined.ConversionFunction) 3485 Result = CompareStandardConversionSequences(S, Loc, 3486 ICS1.UserDefined.After, 3487 ICS2.UserDefined.After); 3488 else 3489 Result = compareConversionFunctions(S, 3490 ICS1.UserDefined.ConversionFunction, 3491 ICS2.UserDefined.ConversionFunction); 3492 } 3493 3494 return Result; 3495 } 3496 3497 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3498 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3499 Qualifiers Quals; 3500 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3501 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3502 } 3503 3504 return Context.hasSameUnqualifiedType(T1, T2); 3505 } 3506 3507 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3508 // determine if one is a proper subset of the other. 3509 static ImplicitConversionSequence::CompareKind 3510 compareStandardConversionSubsets(ASTContext &Context, 3511 const StandardConversionSequence& SCS1, 3512 const StandardConversionSequence& SCS2) { 3513 ImplicitConversionSequence::CompareKind Result 3514 = ImplicitConversionSequence::Indistinguishable; 3515 3516 // the identity conversion sequence is considered to be a subsequence of 3517 // any non-identity conversion sequence 3518 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3519 return ImplicitConversionSequence::Better; 3520 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3521 return ImplicitConversionSequence::Worse; 3522 3523 if (SCS1.Second != SCS2.Second) { 3524 if (SCS1.Second == ICK_Identity) 3525 Result = ImplicitConversionSequence::Better; 3526 else if (SCS2.Second == ICK_Identity) 3527 Result = ImplicitConversionSequence::Worse; 3528 else 3529 return ImplicitConversionSequence::Indistinguishable; 3530 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3531 return ImplicitConversionSequence::Indistinguishable; 3532 3533 if (SCS1.Third == SCS2.Third) { 3534 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3535 : ImplicitConversionSequence::Indistinguishable; 3536 } 3537 3538 if (SCS1.Third == ICK_Identity) 3539 return Result == ImplicitConversionSequence::Worse 3540 ? ImplicitConversionSequence::Indistinguishable 3541 : ImplicitConversionSequence::Better; 3542 3543 if (SCS2.Third == ICK_Identity) 3544 return Result == ImplicitConversionSequence::Better 3545 ? ImplicitConversionSequence::Indistinguishable 3546 : ImplicitConversionSequence::Worse; 3547 3548 return ImplicitConversionSequence::Indistinguishable; 3549 } 3550 3551 /// \brief Determine whether one of the given reference bindings is better 3552 /// than the other based on what kind of bindings they are. 3553 static bool 3554 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3555 const StandardConversionSequence &SCS2) { 3556 // C++0x [over.ics.rank]p3b4: 3557 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3558 // implicit object parameter of a non-static member function declared 3559 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3560 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3561 // lvalue reference to a function lvalue and S2 binds an rvalue 3562 // reference*. 3563 // 3564 // FIXME: Rvalue references. We're going rogue with the above edits, 3565 // because the semantics in the current C++0x working paper (N3225 at the 3566 // time of this writing) break the standard definition of std::forward 3567 // and std::reference_wrapper when dealing with references to functions. 3568 // Proposed wording changes submitted to CWG for consideration. 3569 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3570 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3571 return false; 3572 3573 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3574 SCS2.IsLvalueReference) || 3575 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3576 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3577 } 3578 3579 /// CompareStandardConversionSequences - Compare two standard 3580 /// conversion sequences to determine whether one is better than the 3581 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3582 static ImplicitConversionSequence::CompareKind 3583 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3584 const StandardConversionSequence& SCS1, 3585 const StandardConversionSequence& SCS2) 3586 { 3587 // Standard conversion sequence S1 is a better conversion sequence 3588 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3589 3590 // -- S1 is a proper subsequence of S2 (comparing the conversion 3591 // sequences in the canonical form defined by 13.3.3.1.1, 3592 // excluding any Lvalue Transformation; the identity conversion 3593 // sequence is considered to be a subsequence of any 3594 // non-identity conversion sequence) or, if not that, 3595 if (ImplicitConversionSequence::CompareKind CK 3596 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3597 return CK; 3598 3599 // -- the rank of S1 is better than the rank of S2 (by the rules 3600 // defined below), or, if not that, 3601 ImplicitConversionRank Rank1 = SCS1.getRank(); 3602 ImplicitConversionRank Rank2 = SCS2.getRank(); 3603 if (Rank1 < Rank2) 3604 return ImplicitConversionSequence::Better; 3605 else if (Rank2 < Rank1) 3606 return ImplicitConversionSequence::Worse; 3607 3608 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3609 // are indistinguishable unless one of the following rules 3610 // applies: 3611 3612 // A conversion that is not a conversion of a pointer, or 3613 // pointer to member, to bool is better than another conversion 3614 // that is such a conversion. 3615 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3616 return SCS2.isPointerConversionToBool() 3617 ? ImplicitConversionSequence::Better 3618 : ImplicitConversionSequence::Worse; 3619 3620 // C++ [over.ics.rank]p4b2: 3621 // 3622 // If class B is derived directly or indirectly from class A, 3623 // conversion of B* to A* is better than conversion of B* to 3624 // void*, and conversion of A* to void* is better than conversion 3625 // of B* to void*. 3626 bool SCS1ConvertsToVoid 3627 = SCS1.isPointerConversionToVoidPointer(S.Context); 3628 bool SCS2ConvertsToVoid 3629 = SCS2.isPointerConversionToVoidPointer(S.Context); 3630 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3631 // Exactly one of the conversion sequences is a conversion to 3632 // a void pointer; it's the worse conversion. 3633 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3634 : ImplicitConversionSequence::Worse; 3635 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3636 // Neither conversion sequence converts to a void pointer; compare 3637 // their derived-to-base conversions. 3638 if (ImplicitConversionSequence::CompareKind DerivedCK 3639 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3640 return DerivedCK; 3641 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3642 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3643 // Both conversion sequences are conversions to void 3644 // pointers. Compare the source types to determine if there's an 3645 // inheritance relationship in their sources. 3646 QualType FromType1 = SCS1.getFromType(); 3647 QualType FromType2 = SCS2.getFromType(); 3648 3649 // Adjust the types we're converting from via the array-to-pointer 3650 // conversion, if we need to. 3651 if (SCS1.First == ICK_Array_To_Pointer) 3652 FromType1 = S.Context.getArrayDecayedType(FromType1); 3653 if (SCS2.First == ICK_Array_To_Pointer) 3654 FromType2 = S.Context.getArrayDecayedType(FromType2); 3655 3656 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3657 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3658 3659 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3660 return ImplicitConversionSequence::Better; 3661 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3662 return ImplicitConversionSequence::Worse; 3663 3664 // Objective-C++: If one interface is more specific than the 3665 // other, it is the better one. 3666 const ObjCObjectPointerType* FromObjCPtr1 3667 = FromType1->getAs<ObjCObjectPointerType>(); 3668 const ObjCObjectPointerType* FromObjCPtr2 3669 = FromType2->getAs<ObjCObjectPointerType>(); 3670 if (FromObjCPtr1 && FromObjCPtr2) { 3671 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3672 FromObjCPtr2); 3673 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3674 FromObjCPtr1); 3675 if (AssignLeft != AssignRight) { 3676 return AssignLeft? ImplicitConversionSequence::Better 3677 : ImplicitConversionSequence::Worse; 3678 } 3679 } 3680 } 3681 3682 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3683 // bullet 3). 3684 if (ImplicitConversionSequence::CompareKind QualCK 3685 = CompareQualificationConversions(S, SCS1, SCS2)) 3686 return QualCK; 3687 3688 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3689 // Check for a better reference binding based on the kind of bindings. 3690 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3691 return ImplicitConversionSequence::Better; 3692 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3693 return ImplicitConversionSequence::Worse; 3694 3695 // C++ [over.ics.rank]p3b4: 3696 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3697 // which the references refer are the same type except for 3698 // top-level cv-qualifiers, and the type to which the reference 3699 // initialized by S2 refers is more cv-qualified than the type 3700 // to which the reference initialized by S1 refers. 3701 QualType T1 = SCS1.getToType(2); 3702 QualType T2 = SCS2.getToType(2); 3703 T1 = S.Context.getCanonicalType(T1); 3704 T2 = S.Context.getCanonicalType(T2); 3705 Qualifiers T1Quals, T2Quals; 3706 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3707 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3708 if (UnqualT1 == UnqualT2) { 3709 // Objective-C++ ARC: If the references refer to objects with different 3710 // lifetimes, prefer bindings that don't change lifetime. 3711 if (SCS1.ObjCLifetimeConversionBinding != 3712 SCS2.ObjCLifetimeConversionBinding) { 3713 return SCS1.ObjCLifetimeConversionBinding 3714 ? ImplicitConversionSequence::Worse 3715 : ImplicitConversionSequence::Better; 3716 } 3717 3718 // If the type is an array type, promote the element qualifiers to the 3719 // type for comparison. 3720 if (isa<ArrayType>(T1) && T1Quals) 3721 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3722 if (isa<ArrayType>(T2) && T2Quals) 3723 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3724 if (T2.isMoreQualifiedThan(T1)) 3725 return ImplicitConversionSequence::Better; 3726 else if (T1.isMoreQualifiedThan(T2)) 3727 return ImplicitConversionSequence::Worse; 3728 } 3729 } 3730 3731 // In Microsoft mode, prefer an integral conversion to a 3732 // floating-to-integral conversion if the integral conversion 3733 // is between types of the same size. 3734 // For example: 3735 // void f(float); 3736 // void f(int); 3737 // int main { 3738 // long a; 3739 // f(a); 3740 // } 3741 // Here, MSVC will call f(int) instead of generating a compile error 3742 // as clang will do in standard mode. 3743 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3744 SCS2.Second == ICK_Floating_Integral && 3745 S.Context.getTypeSize(SCS1.getFromType()) == 3746 S.Context.getTypeSize(SCS1.getToType(2))) 3747 return ImplicitConversionSequence::Better; 3748 3749 return ImplicitConversionSequence::Indistinguishable; 3750 } 3751 3752 /// CompareQualificationConversions - Compares two standard conversion 3753 /// sequences to determine whether they can be ranked based on their 3754 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3755 static ImplicitConversionSequence::CompareKind 3756 CompareQualificationConversions(Sema &S, 3757 const StandardConversionSequence& SCS1, 3758 const StandardConversionSequence& SCS2) { 3759 // C++ 13.3.3.2p3: 3760 // -- S1 and S2 differ only in their qualification conversion and 3761 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3762 // cv-qualification signature of type T1 is a proper subset of 3763 // the cv-qualification signature of type T2, and S1 is not the 3764 // deprecated string literal array-to-pointer conversion (4.2). 3765 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3766 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3767 return ImplicitConversionSequence::Indistinguishable; 3768 3769 // FIXME: the example in the standard doesn't use a qualification 3770 // conversion (!) 3771 QualType T1 = SCS1.getToType(2); 3772 QualType T2 = SCS2.getToType(2); 3773 T1 = S.Context.getCanonicalType(T1); 3774 T2 = S.Context.getCanonicalType(T2); 3775 Qualifiers T1Quals, T2Quals; 3776 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3777 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3778 3779 // If the types are the same, we won't learn anything by unwrapped 3780 // them. 3781 if (UnqualT1 == UnqualT2) 3782 return ImplicitConversionSequence::Indistinguishable; 3783 3784 // If the type is an array type, promote the element qualifiers to the type 3785 // for comparison. 3786 if (isa<ArrayType>(T1) && T1Quals) 3787 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3788 if (isa<ArrayType>(T2) && T2Quals) 3789 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3790 3791 ImplicitConversionSequence::CompareKind Result 3792 = ImplicitConversionSequence::Indistinguishable; 3793 3794 // Objective-C++ ARC: 3795 // Prefer qualification conversions not involving a change in lifetime 3796 // to qualification conversions that do not change lifetime. 3797 if (SCS1.QualificationIncludesObjCLifetime != 3798 SCS2.QualificationIncludesObjCLifetime) { 3799 Result = SCS1.QualificationIncludesObjCLifetime 3800 ? ImplicitConversionSequence::Worse 3801 : ImplicitConversionSequence::Better; 3802 } 3803 3804 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3805 // Within each iteration of the loop, we check the qualifiers to 3806 // determine if this still looks like a qualification 3807 // conversion. Then, if all is well, we unwrap one more level of 3808 // pointers or pointers-to-members and do it all again 3809 // until there are no more pointers or pointers-to-members left 3810 // to unwrap. This essentially mimics what 3811 // IsQualificationConversion does, but here we're checking for a 3812 // strict subset of qualifiers. 3813 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3814 // The qualifiers are the same, so this doesn't tell us anything 3815 // about how the sequences rank. 3816 ; 3817 else if (T2.isMoreQualifiedThan(T1)) { 3818 // T1 has fewer qualifiers, so it could be the better sequence. 3819 if (Result == ImplicitConversionSequence::Worse) 3820 // Neither has qualifiers that are a subset of the other's 3821 // qualifiers. 3822 return ImplicitConversionSequence::Indistinguishable; 3823 3824 Result = ImplicitConversionSequence::Better; 3825 } else if (T1.isMoreQualifiedThan(T2)) { 3826 // T2 has fewer qualifiers, so it could be the better sequence. 3827 if (Result == ImplicitConversionSequence::Better) 3828 // Neither has qualifiers that are a subset of the other's 3829 // qualifiers. 3830 return ImplicitConversionSequence::Indistinguishable; 3831 3832 Result = ImplicitConversionSequence::Worse; 3833 } else { 3834 // Qualifiers are disjoint. 3835 return ImplicitConversionSequence::Indistinguishable; 3836 } 3837 3838 // If the types after this point are equivalent, we're done. 3839 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3840 break; 3841 } 3842 3843 // Check that the winning standard conversion sequence isn't using 3844 // the deprecated string literal array to pointer conversion. 3845 switch (Result) { 3846 case ImplicitConversionSequence::Better: 3847 if (SCS1.DeprecatedStringLiteralToCharPtr) 3848 Result = ImplicitConversionSequence::Indistinguishable; 3849 break; 3850 3851 case ImplicitConversionSequence::Indistinguishable: 3852 break; 3853 3854 case ImplicitConversionSequence::Worse: 3855 if (SCS2.DeprecatedStringLiteralToCharPtr) 3856 Result = ImplicitConversionSequence::Indistinguishable; 3857 break; 3858 } 3859 3860 return Result; 3861 } 3862 3863 /// CompareDerivedToBaseConversions - Compares two standard conversion 3864 /// sequences to determine whether they can be ranked based on their 3865 /// various kinds of derived-to-base conversions (C++ 3866 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3867 /// conversions between Objective-C interface types. 3868 static ImplicitConversionSequence::CompareKind 3869 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3870 const StandardConversionSequence& SCS1, 3871 const StandardConversionSequence& SCS2) { 3872 QualType FromType1 = SCS1.getFromType(); 3873 QualType ToType1 = SCS1.getToType(1); 3874 QualType FromType2 = SCS2.getFromType(); 3875 QualType ToType2 = SCS2.getToType(1); 3876 3877 // Adjust the types we're converting from via the array-to-pointer 3878 // conversion, if we need to. 3879 if (SCS1.First == ICK_Array_To_Pointer) 3880 FromType1 = S.Context.getArrayDecayedType(FromType1); 3881 if (SCS2.First == ICK_Array_To_Pointer) 3882 FromType2 = S.Context.getArrayDecayedType(FromType2); 3883 3884 // Canonicalize all of the types. 3885 FromType1 = S.Context.getCanonicalType(FromType1); 3886 ToType1 = S.Context.getCanonicalType(ToType1); 3887 FromType2 = S.Context.getCanonicalType(FromType2); 3888 ToType2 = S.Context.getCanonicalType(ToType2); 3889 3890 // C++ [over.ics.rank]p4b3: 3891 // 3892 // If class B is derived directly or indirectly from class A and 3893 // class C is derived directly or indirectly from B, 3894 // 3895 // Compare based on pointer conversions. 3896 if (SCS1.Second == ICK_Pointer_Conversion && 3897 SCS2.Second == ICK_Pointer_Conversion && 3898 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3899 FromType1->isPointerType() && FromType2->isPointerType() && 3900 ToType1->isPointerType() && ToType2->isPointerType()) { 3901 QualType FromPointee1 3902 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3903 QualType ToPointee1 3904 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3905 QualType FromPointee2 3906 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3907 QualType ToPointee2 3908 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3909 3910 // -- conversion of C* to B* is better than conversion of C* to A*, 3911 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3912 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3913 return ImplicitConversionSequence::Better; 3914 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3915 return ImplicitConversionSequence::Worse; 3916 } 3917 3918 // -- conversion of B* to A* is better than conversion of C* to A*, 3919 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3920 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3921 return ImplicitConversionSequence::Better; 3922 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3923 return ImplicitConversionSequence::Worse; 3924 } 3925 } else if (SCS1.Second == ICK_Pointer_Conversion && 3926 SCS2.Second == ICK_Pointer_Conversion) { 3927 const ObjCObjectPointerType *FromPtr1 3928 = FromType1->getAs<ObjCObjectPointerType>(); 3929 const ObjCObjectPointerType *FromPtr2 3930 = FromType2->getAs<ObjCObjectPointerType>(); 3931 const ObjCObjectPointerType *ToPtr1 3932 = ToType1->getAs<ObjCObjectPointerType>(); 3933 const ObjCObjectPointerType *ToPtr2 3934 = ToType2->getAs<ObjCObjectPointerType>(); 3935 3936 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3937 // Apply the same conversion ranking rules for Objective-C pointer types 3938 // that we do for C++ pointers to class types. However, we employ the 3939 // Objective-C pseudo-subtyping relationship used for assignment of 3940 // Objective-C pointer types. 3941 bool FromAssignLeft 3942 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3943 bool FromAssignRight 3944 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3945 bool ToAssignLeft 3946 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3947 bool ToAssignRight 3948 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3949 3950 // A conversion to an a non-id object pointer type or qualified 'id' 3951 // type is better than a conversion to 'id'. 3952 if (ToPtr1->isObjCIdType() && 3953 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3954 return ImplicitConversionSequence::Worse; 3955 if (ToPtr2->isObjCIdType() && 3956 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3957 return ImplicitConversionSequence::Better; 3958 3959 // A conversion to a non-id object pointer type is better than a 3960 // conversion to a qualified 'id' type 3961 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3962 return ImplicitConversionSequence::Worse; 3963 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3964 return ImplicitConversionSequence::Better; 3965 3966 // A conversion to an a non-Class object pointer type or qualified 'Class' 3967 // type is better than a conversion to 'Class'. 3968 if (ToPtr1->isObjCClassType() && 3969 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3970 return ImplicitConversionSequence::Worse; 3971 if (ToPtr2->isObjCClassType() && 3972 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3973 return ImplicitConversionSequence::Better; 3974 3975 // A conversion to a non-Class object pointer type is better than a 3976 // conversion to a qualified 'Class' type. 3977 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3978 return ImplicitConversionSequence::Worse; 3979 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3980 return ImplicitConversionSequence::Better; 3981 3982 // -- "conversion of C* to B* is better than conversion of C* to A*," 3983 if (S.Context.hasSameType(FromType1, FromType2) && 3984 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3985 (ToAssignLeft != ToAssignRight)) 3986 return ToAssignLeft? ImplicitConversionSequence::Worse 3987 : ImplicitConversionSequence::Better; 3988 3989 // -- "conversion of B* to A* is better than conversion of C* to A*," 3990 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3991 (FromAssignLeft != FromAssignRight)) 3992 return FromAssignLeft? ImplicitConversionSequence::Better 3993 : ImplicitConversionSequence::Worse; 3994 } 3995 } 3996 3997 // Ranking of member-pointer types. 3998 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3999 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4000 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4001 const MemberPointerType * FromMemPointer1 = 4002 FromType1->getAs<MemberPointerType>(); 4003 const MemberPointerType * ToMemPointer1 = 4004 ToType1->getAs<MemberPointerType>(); 4005 const MemberPointerType * FromMemPointer2 = 4006 FromType2->getAs<MemberPointerType>(); 4007 const MemberPointerType * ToMemPointer2 = 4008 ToType2->getAs<MemberPointerType>(); 4009 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4010 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4011 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4012 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4013 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4014 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4015 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4016 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4017 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4018 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4019 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4020 return ImplicitConversionSequence::Worse; 4021 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4022 return ImplicitConversionSequence::Better; 4023 } 4024 // conversion of B::* to C::* is better than conversion of A::* to C::* 4025 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4026 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4027 return ImplicitConversionSequence::Better; 4028 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4029 return ImplicitConversionSequence::Worse; 4030 } 4031 } 4032 4033 if (SCS1.Second == ICK_Derived_To_Base) { 4034 // -- conversion of C to B is better than conversion of C to A, 4035 // -- binding of an expression of type C to a reference of type 4036 // B& is better than binding an expression of type C to a 4037 // reference of type A&, 4038 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4039 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4040 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4041 return ImplicitConversionSequence::Better; 4042 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4043 return ImplicitConversionSequence::Worse; 4044 } 4045 4046 // -- conversion of B to A is better than conversion of C to A. 4047 // -- binding of an expression of type B to a reference of type 4048 // A& is better than binding an expression of type C to a 4049 // reference of type A&, 4050 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4051 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4052 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4053 return ImplicitConversionSequence::Better; 4054 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4055 return ImplicitConversionSequence::Worse; 4056 } 4057 } 4058 4059 return ImplicitConversionSequence::Indistinguishable; 4060 } 4061 4062 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4063 /// C++ class. 4064 static bool isTypeValid(QualType T) { 4065 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4066 return !Record->isInvalidDecl(); 4067 4068 return true; 4069 } 4070 4071 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4072 /// determine whether they are reference-related, 4073 /// reference-compatible, reference-compatible with added 4074 /// qualification, or incompatible, for use in C++ initialization by 4075 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4076 /// type, and the first type (T1) is the pointee type of the reference 4077 /// type being initialized. 4078 Sema::ReferenceCompareResult 4079 Sema::CompareReferenceRelationship(SourceLocation Loc, 4080 QualType OrigT1, QualType OrigT2, 4081 bool &DerivedToBase, 4082 bool &ObjCConversion, 4083 bool &ObjCLifetimeConversion) { 4084 assert(!OrigT1->isReferenceType() && 4085 "T1 must be the pointee type of the reference type"); 4086 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4087 4088 QualType T1 = Context.getCanonicalType(OrigT1); 4089 QualType T2 = Context.getCanonicalType(OrigT2); 4090 Qualifiers T1Quals, T2Quals; 4091 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4092 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4093 4094 // C++ [dcl.init.ref]p4: 4095 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4096 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4097 // T1 is a base class of T2. 4098 DerivedToBase = false; 4099 ObjCConversion = false; 4100 ObjCLifetimeConversion = false; 4101 if (UnqualT1 == UnqualT2) { 4102 // Nothing to do. 4103 } else if (isCompleteType(Loc, OrigT2) && 4104 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4105 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4106 DerivedToBase = true; 4107 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4108 UnqualT2->isObjCObjectOrInterfaceType() && 4109 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4110 ObjCConversion = true; 4111 else 4112 return Ref_Incompatible; 4113 4114 // At this point, we know that T1 and T2 are reference-related (at 4115 // least). 4116 4117 // If the type is an array type, promote the element qualifiers to the type 4118 // for comparison. 4119 if (isa<ArrayType>(T1) && T1Quals) 4120 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4121 if (isa<ArrayType>(T2) && T2Quals) 4122 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4123 4124 // C++ [dcl.init.ref]p4: 4125 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4126 // reference-related to T2 and cv1 is the same cv-qualification 4127 // as, or greater cv-qualification than, cv2. For purposes of 4128 // overload resolution, cases for which cv1 is greater 4129 // cv-qualification than cv2 are identified as 4130 // reference-compatible with added qualification (see 13.3.3.2). 4131 // 4132 // Note that we also require equivalence of Objective-C GC and address-space 4133 // qualifiers when performing these computations, so that e.g., an int in 4134 // address space 1 is not reference-compatible with an int in address 4135 // space 2. 4136 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4137 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4138 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4139 ObjCLifetimeConversion = true; 4140 4141 T1Quals.removeObjCLifetime(); 4142 T2Quals.removeObjCLifetime(); 4143 } 4144 4145 // MS compiler ignores __unaligned qualifier for references; do the same. 4146 T1Quals.removeUnaligned(); 4147 T2Quals.removeUnaligned(); 4148 4149 if (T1Quals == T2Quals) 4150 return Ref_Compatible; 4151 else if (T1Quals.compatiblyIncludes(T2Quals)) 4152 return Ref_Compatible_With_Added_Qualification; 4153 else 4154 return Ref_Related; 4155 } 4156 4157 /// \brief Look for a user-defined conversion to an value reference-compatible 4158 /// with DeclType. Return true if something definite is found. 4159 static bool 4160 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4161 QualType DeclType, SourceLocation DeclLoc, 4162 Expr *Init, QualType T2, bool AllowRvalues, 4163 bool AllowExplicit) { 4164 assert(T2->isRecordType() && "Can only find conversions of record types."); 4165 CXXRecordDecl *T2RecordDecl 4166 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4167 4168 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4169 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4170 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4171 NamedDecl *D = *I; 4172 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4173 if (isa<UsingShadowDecl>(D)) 4174 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4175 4176 FunctionTemplateDecl *ConvTemplate 4177 = dyn_cast<FunctionTemplateDecl>(D); 4178 CXXConversionDecl *Conv; 4179 if (ConvTemplate) 4180 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4181 else 4182 Conv = cast<CXXConversionDecl>(D); 4183 4184 // If this is an explicit conversion, and we're not allowed to consider 4185 // explicit conversions, skip it. 4186 if (!AllowExplicit && Conv->isExplicit()) 4187 continue; 4188 4189 if (AllowRvalues) { 4190 bool DerivedToBase = false; 4191 bool ObjCConversion = false; 4192 bool ObjCLifetimeConversion = false; 4193 4194 // If we are initializing an rvalue reference, don't permit conversion 4195 // functions that return lvalues. 4196 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4197 const ReferenceType *RefType 4198 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4199 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4200 continue; 4201 } 4202 4203 if (!ConvTemplate && 4204 S.CompareReferenceRelationship( 4205 DeclLoc, 4206 Conv->getConversionType().getNonReferenceType() 4207 .getUnqualifiedType(), 4208 DeclType.getNonReferenceType().getUnqualifiedType(), 4209 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4210 Sema::Ref_Incompatible) 4211 continue; 4212 } else { 4213 // If the conversion function doesn't return a reference type, 4214 // it can't be considered for this conversion. An rvalue reference 4215 // is only acceptable if its referencee is a function type. 4216 4217 const ReferenceType *RefType = 4218 Conv->getConversionType()->getAs<ReferenceType>(); 4219 if (!RefType || 4220 (!RefType->isLValueReferenceType() && 4221 !RefType->getPointeeType()->isFunctionType())) 4222 continue; 4223 } 4224 4225 if (ConvTemplate) 4226 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4227 Init, DeclType, CandidateSet, 4228 /*AllowObjCConversionOnExplicit=*/false); 4229 else 4230 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4231 DeclType, CandidateSet, 4232 /*AllowObjCConversionOnExplicit=*/false); 4233 } 4234 4235 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4236 4237 OverloadCandidateSet::iterator Best; 4238 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4239 case OR_Success: 4240 // C++ [over.ics.ref]p1: 4241 // 4242 // [...] If the parameter binds directly to the result of 4243 // applying a conversion function to the argument 4244 // expression, the implicit conversion sequence is a 4245 // user-defined conversion sequence (13.3.3.1.2), with the 4246 // second standard conversion sequence either an identity 4247 // conversion or, if the conversion function returns an 4248 // entity of a type that is a derived class of the parameter 4249 // type, a derived-to-base Conversion. 4250 if (!Best->FinalConversion.DirectBinding) 4251 return false; 4252 4253 ICS.setUserDefined(); 4254 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4255 ICS.UserDefined.After = Best->FinalConversion; 4256 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4257 ICS.UserDefined.ConversionFunction = Best->Function; 4258 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4259 ICS.UserDefined.EllipsisConversion = false; 4260 assert(ICS.UserDefined.After.ReferenceBinding && 4261 ICS.UserDefined.After.DirectBinding && 4262 "Expected a direct reference binding!"); 4263 return true; 4264 4265 case OR_Ambiguous: 4266 ICS.setAmbiguous(); 4267 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4268 Cand != CandidateSet.end(); ++Cand) 4269 if (Cand->Viable) 4270 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4271 return true; 4272 4273 case OR_No_Viable_Function: 4274 case OR_Deleted: 4275 // There was no suitable conversion, or we found a deleted 4276 // conversion; continue with other checks. 4277 return false; 4278 } 4279 4280 llvm_unreachable("Invalid OverloadResult!"); 4281 } 4282 4283 /// \brief Compute an implicit conversion sequence for reference 4284 /// initialization. 4285 static ImplicitConversionSequence 4286 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4287 SourceLocation DeclLoc, 4288 bool SuppressUserConversions, 4289 bool AllowExplicit) { 4290 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4291 4292 // Most paths end in a failed conversion. 4293 ImplicitConversionSequence ICS; 4294 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4295 4296 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4297 QualType T2 = Init->getType(); 4298 4299 // If the initializer is the address of an overloaded function, try 4300 // to resolve the overloaded function. If all goes well, T2 is the 4301 // type of the resulting function. 4302 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4303 DeclAccessPair Found; 4304 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4305 false, Found)) 4306 T2 = Fn->getType(); 4307 } 4308 4309 // Compute some basic properties of the types and the initializer. 4310 bool isRValRef = DeclType->isRValueReferenceType(); 4311 bool DerivedToBase = false; 4312 bool ObjCConversion = false; 4313 bool ObjCLifetimeConversion = false; 4314 Expr::Classification InitCategory = Init->Classify(S.Context); 4315 Sema::ReferenceCompareResult RefRelationship 4316 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4317 ObjCConversion, ObjCLifetimeConversion); 4318 4319 4320 // C++0x [dcl.init.ref]p5: 4321 // A reference to type "cv1 T1" is initialized by an expression 4322 // of type "cv2 T2" as follows: 4323 4324 // -- If reference is an lvalue reference and the initializer expression 4325 if (!isRValRef) { 4326 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4327 // reference-compatible with "cv2 T2," or 4328 // 4329 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4330 if (InitCategory.isLValue() && 4331 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4332 // C++ [over.ics.ref]p1: 4333 // When a parameter of reference type binds directly (8.5.3) 4334 // to an argument expression, the implicit conversion sequence 4335 // is the identity conversion, unless the argument expression 4336 // has a type that is a derived class of the parameter type, 4337 // in which case the implicit conversion sequence is a 4338 // derived-to-base Conversion (13.3.3.1). 4339 ICS.setStandard(); 4340 ICS.Standard.First = ICK_Identity; 4341 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4342 : ObjCConversion? ICK_Compatible_Conversion 4343 : ICK_Identity; 4344 ICS.Standard.Third = ICK_Identity; 4345 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4346 ICS.Standard.setToType(0, T2); 4347 ICS.Standard.setToType(1, T1); 4348 ICS.Standard.setToType(2, T1); 4349 ICS.Standard.ReferenceBinding = true; 4350 ICS.Standard.DirectBinding = true; 4351 ICS.Standard.IsLvalueReference = !isRValRef; 4352 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4353 ICS.Standard.BindsToRvalue = false; 4354 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4355 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4356 ICS.Standard.CopyConstructor = nullptr; 4357 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4358 4359 // Nothing more to do: the inaccessibility/ambiguity check for 4360 // derived-to-base conversions is suppressed when we're 4361 // computing the implicit conversion sequence (C++ 4362 // [over.best.ics]p2). 4363 return ICS; 4364 } 4365 4366 // -- has a class type (i.e., T2 is a class type), where T1 is 4367 // not reference-related to T2, and can be implicitly 4368 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4369 // is reference-compatible with "cv3 T3" 92) (this 4370 // conversion is selected by enumerating the applicable 4371 // conversion functions (13.3.1.6) and choosing the best 4372 // one through overload resolution (13.3)), 4373 if (!SuppressUserConversions && T2->isRecordType() && 4374 S.isCompleteType(DeclLoc, T2) && 4375 RefRelationship == Sema::Ref_Incompatible) { 4376 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4377 Init, T2, /*AllowRvalues=*/false, 4378 AllowExplicit)) 4379 return ICS; 4380 } 4381 } 4382 4383 // -- Otherwise, the reference shall be an lvalue reference to a 4384 // non-volatile const type (i.e., cv1 shall be const), or the reference 4385 // shall be an rvalue reference. 4386 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4387 return ICS; 4388 4389 // -- If the initializer expression 4390 // 4391 // -- is an xvalue, class prvalue, array prvalue or function 4392 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4393 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4394 (InitCategory.isXValue() || 4395 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4396 (InitCategory.isLValue() && T2->isFunctionType()))) { 4397 ICS.setStandard(); 4398 ICS.Standard.First = ICK_Identity; 4399 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4400 : ObjCConversion? ICK_Compatible_Conversion 4401 : ICK_Identity; 4402 ICS.Standard.Third = ICK_Identity; 4403 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4404 ICS.Standard.setToType(0, T2); 4405 ICS.Standard.setToType(1, T1); 4406 ICS.Standard.setToType(2, T1); 4407 ICS.Standard.ReferenceBinding = true; 4408 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4409 // binding unless we're binding to a class prvalue. 4410 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4411 // allow the use of rvalue references in C++98/03 for the benefit of 4412 // standard library implementors; therefore, we need the xvalue check here. 4413 ICS.Standard.DirectBinding = 4414 S.getLangOpts().CPlusPlus11 || 4415 !(InitCategory.isPRValue() || T2->isRecordType()); 4416 ICS.Standard.IsLvalueReference = !isRValRef; 4417 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4418 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4419 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4420 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4421 ICS.Standard.CopyConstructor = nullptr; 4422 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4423 return ICS; 4424 } 4425 4426 // -- has a class type (i.e., T2 is a class type), where T1 is not 4427 // reference-related to T2, and can be implicitly converted to 4428 // an xvalue, class prvalue, or function lvalue of type 4429 // "cv3 T3", where "cv1 T1" is reference-compatible with 4430 // "cv3 T3", 4431 // 4432 // then the reference is bound to the value of the initializer 4433 // expression in the first case and to the result of the conversion 4434 // in the second case (or, in either case, to an appropriate base 4435 // class subobject). 4436 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4437 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4438 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4439 Init, T2, /*AllowRvalues=*/true, 4440 AllowExplicit)) { 4441 // In the second case, if the reference is an rvalue reference 4442 // and the second standard conversion sequence of the 4443 // user-defined conversion sequence includes an lvalue-to-rvalue 4444 // conversion, the program is ill-formed. 4445 if (ICS.isUserDefined() && isRValRef && 4446 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4447 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4448 4449 return ICS; 4450 } 4451 4452 // A temporary of function type cannot be created; don't even try. 4453 if (T1->isFunctionType()) 4454 return ICS; 4455 4456 // -- Otherwise, a temporary of type "cv1 T1" is created and 4457 // initialized from the initializer expression using the 4458 // rules for a non-reference copy initialization (8.5). The 4459 // reference is then bound to the temporary. If T1 is 4460 // reference-related to T2, cv1 must be the same 4461 // cv-qualification as, or greater cv-qualification than, 4462 // cv2; otherwise, the program is ill-formed. 4463 if (RefRelationship == Sema::Ref_Related) { 4464 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4465 // we would be reference-compatible or reference-compatible with 4466 // added qualification. But that wasn't the case, so the reference 4467 // initialization fails. 4468 // 4469 // Note that we only want to check address spaces and cvr-qualifiers here. 4470 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4471 Qualifiers T1Quals = T1.getQualifiers(); 4472 Qualifiers T2Quals = T2.getQualifiers(); 4473 T1Quals.removeObjCGCAttr(); 4474 T1Quals.removeObjCLifetime(); 4475 T2Quals.removeObjCGCAttr(); 4476 T2Quals.removeObjCLifetime(); 4477 // MS compiler ignores __unaligned qualifier for references; do the same. 4478 T1Quals.removeUnaligned(); 4479 T2Quals.removeUnaligned(); 4480 if (!T1Quals.compatiblyIncludes(T2Quals)) 4481 return ICS; 4482 } 4483 4484 // If at least one of the types is a class type, the types are not 4485 // related, and we aren't allowed any user conversions, the 4486 // reference binding fails. This case is important for breaking 4487 // recursion, since TryImplicitConversion below will attempt to 4488 // create a temporary through the use of a copy constructor. 4489 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4490 (T1->isRecordType() || T2->isRecordType())) 4491 return ICS; 4492 4493 // If T1 is reference-related to T2 and the reference is an rvalue 4494 // reference, the initializer expression shall not be an lvalue. 4495 if (RefRelationship >= Sema::Ref_Related && 4496 isRValRef && Init->Classify(S.Context).isLValue()) 4497 return ICS; 4498 4499 // C++ [over.ics.ref]p2: 4500 // When a parameter of reference type is not bound directly to 4501 // an argument expression, the conversion sequence is the one 4502 // required to convert the argument expression to the 4503 // underlying type of the reference according to 4504 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4505 // to copy-initializing a temporary of the underlying type with 4506 // the argument expression. Any difference in top-level 4507 // cv-qualification is subsumed by the initialization itself 4508 // and does not constitute a conversion. 4509 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4510 /*AllowExplicit=*/false, 4511 /*InOverloadResolution=*/false, 4512 /*CStyle=*/false, 4513 /*AllowObjCWritebackConversion=*/false, 4514 /*AllowObjCConversionOnExplicit=*/false); 4515 4516 // Of course, that's still a reference binding. 4517 if (ICS.isStandard()) { 4518 ICS.Standard.ReferenceBinding = true; 4519 ICS.Standard.IsLvalueReference = !isRValRef; 4520 ICS.Standard.BindsToFunctionLvalue = false; 4521 ICS.Standard.BindsToRvalue = true; 4522 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4523 ICS.Standard.ObjCLifetimeConversionBinding = false; 4524 } else if (ICS.isUserDefined()) { 4525 const ReferenceType *LValRefType = 4526 ICS.UserDefined.ConversionFunction->getReturnType() 4527 ->getAs<LValueReferenceType>(); 4528 4529 // C++ [over.ics.ref]p3: 4530 // Except for an implicit object parameter, for which see 13.3.1, a 4531 // standard conversion sequence cannot be formed if it requires [...] 4532 // binding an rvalue reference to an lvalue other than a function 4533 // lvalue. 4534 // Note that the function case is not possible here. 4535 if (DeclType->isRValueReferenceType() && LValRefType) { 4536 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4537 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4538 // reference to an rvalue! 4539 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4540 return ICS; 4541 } 4542 4543 ICS.UserDefined.After.ReferenceBinding = true; 4544 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4545 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4546 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4547 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4548 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4549 } 4550 4551 return ICS; 4552 } 4553 4554 static ImplicitConversionSequence 4555 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4556 bool SuppressUserConversions, 4557 bool InOverloadResolution, 4558 bool AllowObjCWritebackConversion, 4559 bool AllowExplicit = false); 4560 4561 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4562 /// initializer list From. 4563 static ImplicitConversionSequence 4564 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4565 bool SuppressUserConversions, 4566 bool InOverloadResolution, 4567 bool AllowObjCWritebackConversion) { 4568 // C++11 [over.ics.list]p1: 4569 // When an argument is an initializer list, it is not an expression and 4570 // special rules apply for converting it to a parameter type. 4571 4572 ImplicitConversionSequence Result; 4573 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4574 4575 // We need a complete type for what follows. Incomplete types can never be 4576 // initialized from init lists. 4577 if (!S.isCompleteType(From->getLocStart(), ToType)) 4578 return Result; 4579 4580 // Per DR1467: 4581 // If the parameter type is a class X and the initializer list has a single 4582 // element of type cv U, where U is X or a class derived from X, the 4583 // implicit conversion sequence is the one required to convert the element 4584 // to the parameter type. 4585 // 4586 // Otherwise, if the parameter type is a character array [... ] 4587 // and the initializer list has a single element that is an 4588 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4589 // implicit conversion sequence is the identity conversion. 4590 if (From->getNumInits() == 1) { 4591 if (ToType->isRecordType()) { 4592 QualType InitType = From->getInit(0)->getType(); 4593 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4594 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4595 return TryCopyInitialization(S, From->getInit(0), ToType, 4596 SuppressUserConversions, 4597 InOverloadResolution, 4598 AllowObjCWritebackConversion); 4599 } 4600 // FIXME: Check the other conditions here: array of character type, 4601 // initializer is a string literal. 4602 if (ToType->isArrayType()) { 4603 InitializedEntity Entity = 4604 InitializedEntity::InitializeParameter(S.Context, ToType, 4605 /*Consumed=*/false); 4606 if (S.CanPerformCopyInitialization(Entity, From)) { 4607 Result.setStandard(); 4608 Result.Standard.setAsIdentityConversion(); 4609 Result.Standard.setFromType(ToType); 4610 Result.Standard.setAllToTypes(ToType); 4611 return Result; 4612 } 4613 } 4614 } 4615 4616 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4617 // C++11 [over.ics.list]p2: 4618 // If the parameter type is std::initializer_list<X> or "array of X" and 4619 // all the elements can be implicitly converted to X, the implicit 4620 // conversion sequence is the worst conversion necessary to convert an 4621 // element of the list to X. 4622 // 4623 // C++14 [over.ics.list]p3: 4624 // Otherwise, if the parameter type is "array of N X", if the initializer 4625 // list has exactly N elements or if it has fewer than N elements and X is 4626 // default-constructible, and if all the elements of the initializer list 4627 // can be implicitly converted to X, the implicit conversion sequence is 4628 // the worst conversion necessary to convert an element of the list to X. 4629 // 4630 // FIXME: We're missing a lot of these checks. 4631 bool toStdInitializerList = false; 4632 QualType X; 4633 if (ToType->isArrayType()) 4634 X = S.Context.getAsArrayType(ToType)->getElementType(); 4635 else 4636 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4637 if (!X.isNull()) { 4638 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4639 Expr *Init = From->getInit(i); 4640 ImplicitConversionSequence ICS = 4641 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4642 InOverloadResolution, 4643 AllowObjCWritebackConversion); 4644 // If a single element isn't convertible, fail. 4645 if (ICS.isBad()) { 4646 Result = ICS; 4647 break; 4648 } 4649 // Otherwise, look for the worst conversion. 4650 if (Result.isBad() || 4651 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4652 Result) == 4653 ImplicitConversionSequence::Worse) 4654 Result = ICS; 4655 } 4656 4657 // For an empty list, we won't have computed any conversion sequence. 4658 // Introduce the identity conversion sequence. 4659 if (From->getNumInits() == 0) { 4660 Result.setStandard(); 4661 Result.Standard.setAsIdentityConversion(); 4662 Result.Standard.setFromType(ToType); 4663 Result.Standard.setAllToTypes(ToType); 4664 } 4665 4666 Result.setStdInitializerListElement(toStdInitializerList); 4667 return Result; 4668 } 4669 4670 // C++14 [over.ics.list]p4: 4671 // C++11 [over.ics.list]p3: 4672 // Otherwise, if the parameter is a non-aggregate class X and overload 4673 // resolution chooses a single best constructor [...] the implicit 4674 // conversion sequence is a user-defined conversion sequence. If multiple 4675 // constructors are viable but none is better than the others, the 4676 // implicit conversion sequence is a user-defined conversion sequence. 4677 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4678 // This function can deal with initializer lists. 4679 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4680 /*AllowExplicit=*/false, 4681 InOverloadResolution, /*CStyle=*/false, 4682 AllowObjCWritebackConversion, 4683 /*AllowObjCConversionOnExplicit=*/false); 4684 } 4685 4686 // C++14 [over.ics.list]p5: 4687 // C++11 [over.ics.list]p4: 4688 // Otherwise, if the parameter has an aggregate type which can be 4689 // initialized from the initializer list [...] the implicit conversion 4690 // sequence is a user-defined conversion sequence. 4691 if (ToType->isAggregateType()) { 4692 // Type is an aggregate, argument is an init list. At this point it comes 4693 // down to checking whether the initialization works. 4694 // FIXME: Find out whether this parameter is consumed or not. 4695 InitializedEntity Entity = 4696 InitializedEntity::InitializeParameter(S.Context, ToType, 4697 /*Consumed=*/false); 4698 if (S.CanPerformCopyInitialization(Entity, From)) { 4699 Result.setUserDefined(); 4700 Result.UserDefined.Before.setAsIdentityConversion(); 4701 // Initializer lists don't have a type. 4702 Result.UserDefined.Before.setFromType(QualType()); 4703 Result.UserDefined.Before.setAllToTypes(QualType()); 4704 4705 Result.UserDefined.After.setAsIdentityConversion(); 4706 Result.UserDefined.After.setFromType(ToType); 4707 Result.UserDefined.After.setAllToTypes(ToType); 4708 Result.UserDefined.ConversionFunction = nullptr; 4709 } 4710 return Result; 4711 } 4712 4713 // C++14 [over.ics.list]p6: 4714 // C++11 [over.ics.list]p5: 4715 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4716 if (ToType->isReferenceType()) { 4717 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4718 // mention initializer lists in any way. So we go by what list- 4719 // initialization would do and try to extrapolate from that. 4720 4721 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4722 4723 // If the initializer list has a single element that is reference-related 4724 // to the parameter type, we initialize the reference from that. 4725 if (From->getNumInits() == 1) { 4726 Expr *Init = From->getInit(0); 4727 4728 QualType T2 = Init->getType(); 4729 4730 // If the initializer is the address of an overloaded function, try 4731 // to resolve the overloaded function. If all goes well, T2 is the 4732 // type of the resulting function. 4733 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4734 DeclAccessPair Found; 4735 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4736 Init, ToType, false, Found)) 4737 T2 = Fn->getType(); 4738 } 4739 4740 // Compute some basic properties of the types and the initializer. 4741 bool dummy1 = false; 4742 bool dummy2 = false; 4743 bool dummy3 = false; 4744 Sema::ReferenceCompareResult RefRelationship 4745 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4746 dummy2, dummy3); 4747 4748 if (RefRelationship >= Sema::Ref_Related) { 4749 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4750 SuppressUserConversions, 4751 /*AllowExplicit=*/false); 4752 } 4753 } 4754 4755 // Otherwise, we bind the reference to a temporary created from the 4756 // initializer list. 4757 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4758 InOverloadResolution, 4759 AllowObjCWritebackConversion); 4760 if (Result.isFailure()) 4761 return Result; 4762 assert(!Result.isEllipsis() && 4763 "Sub-initialization cannot result in ellipsis conversion."); 4764 4765 // Can we even bind to a temporary? 4766 if (ToType->isRValueReferenceType() || 4767 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4768 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4769 Result.UserDefined.After; 4770 SCS.ReferenceBinding = true; 4771 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4772 SCS.BindsToRvalue = true; 4773 SCS.BindsToFunctionLvalue = false; 4774 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4775 SCS.ObjCLifetimeConversionBinding = false; 4776 } else 4777 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4778 From, ToType); 4779 return Result; 4780 } 4781 4782 // C++14 [over.ics.list]p7: 4783 // C++11 [over.ics.list]p6: 4784 // Otherwise, if the parameter type is not a class: 4785 if (!ToType->isRecordType()) { 4786 // - if the initializer list has one element that is not itself an 4787 // initializer list, the implicit conversion sequence is the one 4788 // required to convert the element to the parameter type. 4789 unsigned NumInits = From->getNumInits(); 4790 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4791 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4792 SuppressUserConversions, 4793 InOverloadResolution, 4794 AllowObjCWritebackConversion); 4795 // - if the initializer list has no elements, the implicit conversion 4796 // sequence is the identity conversion. 4797 else if (NumInits == 0) { 4798 Result.setStandard(); 4799 Result.Standard.setAsIdentityConversion(); 4800 Result.Standard.setFromType(ToType); 4801 Result.Standard.setAllToTypes(ToType); 4802 } 4803 return Result; 4804 } 4805 4806 // C++14 [over.ics.list]p8: 4807 // C++11 [over.ics.list]p7: 4808 // In all cases other than those enumerated above, no conversion is possible 4809 return Result; 4810 } 4811 4812 /// TryCopyInitialization - Try to copy-initialize a value of type 4813 /// ToType from the expression From. Return the implicit conversion 4814 /// sequence required to pass this argument, which may be a bad 4815 /// conversion sequence (meaning that the argument cannot be passed to 4816 /// a parameter of this type). If @p SuppressUserConversions, then we 4817 /// do not permit any user-defined conversion sequences. 4818 static ImplicitConversionSequence 4819 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4820 bool SuppressUserConversions, 4821 bool InOverloadResolution, 4822 bool AllowObjCWritebackConversion, 4823 bool AllowExplicit) { 4824 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4825 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4826 InOverloadResolution,AllowObjCWritebackConversion); 4827 4828 if (ToType->isReferenceType()) 4829 return TryReferenceInit(S, From, ToType, 4830 /*FIXME:*/From->getLocStart(), 4831 SuppressUserConversions, 4832 AllowExplicit); 4833 4834 return TryImplicitConversion(S, From, ToType, 4835 SuppressUserConversions, 4836 /*AllowExplicit=*/false, 4837 InOverloadResolution, 4838 /*CStyle=*/false, 4839 AllowObjCWritebackConversion, 4840 /*AllowObjCConversionOnExplicit=*/false); 4841 } 4842 4843 static bool TryCopyInitialization(const CanQualType FromQTy, 4844 const CanQualType ToQTy, 4845 Sema &S, 4846 SourceLocation Loc, 4847 ExprValueKind FromVK) { 4848 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4849 ImplicitConversionSequence ICS = 4850 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4851 4852 return !ICS.isBad(); 4853 } 4854 4855 /// TryObjectArgumentInitialization - Try to initialize the object 4856 /// parameter of the given member function (@c Method) from the 4857 /// expression @p From. 4858 static ImplicitConversionSequence 4859 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4860 Expr::Classification FromClassification, 4861 CXXMethodDecl *Method, 4862 CXXRecordDecl *ActingContext) { 4863 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4864 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4865 // const volatile object. 4866 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4867 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4868 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4869 4870 // Set up the conversion sequence as a "bad" conversion, to allow us 4871 // to exit early. 4872 ImplicitConversionSequence ICS; 4873 4874 // We need to have an object of class type. 4875 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4876 FromType = PT->getPointeeType(); 4877 4878 // When we had a pointer, it's implicitly dereferenced, so we 4879 // better have an lvalue. 4880 assert(FromClassification.isLValue()); 4881 } 4882 4883 assert(FromType->isRecordType()); 4884 4885 // C++0x [over.match.funcs]p4: 4886 // For non-static member functions, the type of the implicit object 4887 // parameter is 4888 // 4889 // - "lvalue reference to cv X" for functions declared without a 4890 // ref-qualifier or with the & ref-qualifier 4891 // - "rvalue reference to cv X" for functions declared with the && 4892 // ref-qualifier 4893 // 4894 // where X is the class of which the function is a member and cv is the 4895 // cv-qualification on the member function declaration. 4896 // 4897 // However, when finding an implicit conversion sequence for the argument, we 4898 // are not allowed to create temporaries or perform user-defined conversions 4899 // (C++ [over.match.funcs]p5). We perform a simplified version of 4900 // reference binding here, that allows class rvalues to bind to 4901 // non-constant references. 4902 4903 // First check the qualifiers. 4904 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4905 if (ImplicitParamType.getCVRQualifiers() 4906 != FromTypeCanon.getLocalCVRQualifiers() && 4907 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4908 ICS.setBad(BadConversionSequence::bad_qualifiers, 4909 FromType, ImplicitParamType); 4910 return ICS; 4911 } 4912 4913 // Check that we have either the same type or a derived type. It 4914 // affects the conversion rank. 4915 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4916 ImplicitConversionKind SecondKind; 4917 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4918 SecondKind = ICK_Identity; 4919 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4920 SecondKind = ICK_Derived_To_Base; 4921 else { 4922 ICS.setBad(BadConversionSequence::unrelated_class, 4923 FromType, ImplicitParamType); 4924 return ICS; 4925 } 4926 4927 // Check the ref-qualifier. 4928 switch (Method->getRefQualifier()) { 4929 case RQ_None: 4930 // Do nothing; we don't care about lvalueness or rvalueness. 4931 break; 4932 4933 case RQ_LValue: 4934 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4935 // non-const lvalue reference cannot bind to an rvalue 4936 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4937 ImplicitParamType); 4938 return ICS; 4939 } 4940 break; 4941 4942 case RQ_RValue: 4943 if (!FromClassification.isRValue()) { 4944 // rvalue reference cannot bind to an lvalue 4945 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4946 ImplicitParamType); 4947 return ICS; 4948 } 4949 break; 4950 } 4951 4952 // Success. Mark this as a reference binding. 4953 ICS.setStandard(); 4954 ICS.Standard.setAsIdentityConversion(); 4955 ICS.Standard.Second = SecondKind; 4956 ICS.Standard.setFromType(FromType); 4957 ICS.Standard.setAllToTypes(ImplicitParamType); 4958 ICS.Standard.ReferenceBinding = true; 4959 ICS.Standard.DirectBinding = true; 4960 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4961 ICS.Standard.BindsToFunctionLvalue = false; 4962 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4963 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4964 = (Method->getRefQualifier() == RQ_None); 4965 return ICS; 4966 } 4967 4968 /// PerformObjectArgumentInitialization - Perform initialization of 4969 /// the implicit object parameter for the given Method with the given 4970 /// expression. 4971 ExprResult 4972 Sema::PerformObjectArgumentInitialization(Expr *From, 4973 NestedNameSpecifier *Qualifier, 4974 NamedDecl *FoundDecl, 4975 CXXMethodDecl *Method) { 4976 QualType FromRecordType, DestType; 4977 QualType ImplicitParamRecordType = 4978 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4979 4980 Expr::Classification FromClassification; 4981 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4982 FromRecordType = PT->getPointeeType(); 4983 DestType = Method->getThisType(Context); 4984 FromClassification = Expr::Classification::makeSimpleLValue(); 4985 } else { 4986 FromRecordType = From->getType(); 4987 DestType = ImplicitParamRecordType; 4988 FromClassification = From->Classify(Context); 4989 } 4990 4991 // Note that we always use the true parent context when performing 4992 // the actual argument initialization. 4993 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4994 *this, From->getLocStart(), From->getType(), FromClassification, Method, 4995 Method->getParent()); 4996 if (ICS.isBad()) { 4997 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4998 Qualifiers FromQs = FromRecordType.getQualifiers(); 4999 Qualifiers ToQs = DestType.getQualifiers(); 5000 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5001 if (CVR) { 5002 Diag(From->getLocStart(), 5003 diag::err_member_function_call_bad_cvr) 5004 << Method->getDeclName() << FromRecordType << (CVR - 1) 5005 << From->getSourceRange(); 5006 Diag(Method->getLocation(), diag::note_previous_decl) 5007 << Method->getDeclName(); 5008 return ExprError(); 5009 } 5010 } 5011 5012 return Diag(From->getLocStart(), 5013 diag::err_implicit_object_parameter_init) 5014 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5015 } 5016 5017 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5018 ExprResult FromRes = 5019 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5020 if (FromRes.isInvalid()) 5021 return ExprError(); 5022 From = FromRes.get(); 5023 } 5024 5025 if (!Context.hasSameType(From->getType(), DestType)) 5026 From = ImpCastExprToType(From, DestType, CK_NoOp, 5027 From->getValueKind()).get(); 5028 return From; 5029 } 5030 5031 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5032 /// expression From to bool (C++0x [conv]p3). 5033 static ImplicitConversionSequence 5034 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5035 return TryImplicitConversion(S, From, S.Context.BoolTy, 5036 /*SuppressUserConversions=*/false, 5037 /*AllowExplicit=*/true, 5038 /*InOverloadResolution=*/false, 5039 /*CStyle=*/false, 5040 /*AllowObjCWritebackConversion=*/false, 5041 /*AllowObjCConversionOnExplicit=*/false); 5042 } 5043 5044 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5045 /// of the expression From to bool (C++0x [conv]p3). 5046 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5047 if (checkPlaceholderForOverload(*this, From)) 5048 return ExprError(); 5049 5050 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5051 if (!ICS.isBad()) 5052 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5053 5054 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5055 return Diag(From->getLocStart(), 5056 diag::err_typecheck_bool_condition) 5057 << From->getType() << From->getSourceRange(); 5058 return ExprError(); 5059 } 5060 5061 /// Check that the specified conversion is permitted in a converted constant 5062 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5063 /// is acceptable. 5064 static bool CheckConvertedConstantConversions(Sema &S, 5065 StandardConversionSequence &SCS) { 5066 // Since we know that the target type is an integral or unscoped enumeration 5067 // type, most conversion kinds are impossible. All possible First and Third 5068 // conversions are fine. 5069 switch (SCS.Second) { 5070 case ICK_Identity: 5071 case ICK_NoReturn_Adjustment: 5072 case ICK_Integral_Promotion: 5073 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5074 return true; 5075 5076 case ICK_Boolean_Conversion: 5077 // Conversion from an integral or unscoped enumeration type to bool is 5078 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5079 // conversion, so we allow it in a converted constant expression. 5080 // 5081 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5082 // a lot of popular code. We should at least add a warning for this 5083 // (non-conforming) extension. 5084 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5085 SCS.getToType(2)->isBooleanType(); 5086 5087 case ICK_Pointer_Conversion: 5088 case ICK_Pointer_Member: 5089 // C++1z: null pointer conversions and null member pointer conversions are 5090 // only permitted if the source type is std::nullptr_t. 5091 return SCS.getFromType()->isNullPtrType(); 5092 5093 case ICK_Floating_Promotion: 5094 case ICK_Complex_Promotion: 5095 case ICK_Floating_Conversion: 5096 case ICK_Complex_Conversion: 5097 case ICK_Floating_Integral: 5098 case ICK_Compatible_Conversion: 5099 case ICK_Derived_To_Base: 5100 case ICK_Vector_Conversion: 5101 case ICK_Vector_Splat: 5102 case ICK_Complex_Real: 5103 case ICK_Block_Pointer_Conversion: 5104 case ICK_TransparentUnionConversion: 5105 case ICK_Writeback_Conversion: 5106 case ICK_Zero_Event_Conversion: 5107 case ICK_C_Only_Conversion: 5108 return false; 5109 5110 case ICK_Lvalue_To_Rvalue: 5111 case ICK_Array_To_Pointer: 5112 case ICK_Function_To_Pointer: 5113 llvm_unreachable("found a first conversion kind in Second"); 5114 5115 case ICK_Qualification: 5116 llvm_unreachable("found a third conversion kind in Second"); 5117 5118 case ICK_Num_Conversion_Kinds: 5119 break; 5120 } 5121 5122 llvm_unreachable("unknown conversion kind"); 5123 } 5124 5125 /// CheckConvertedConstantExpression - Check that the expression From is a 5126 /// converted constant expression of type T, perform the conversion and produce 5127 /// the converted expression, per C++11 [expr.const]p3. 5128 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5129 QualType T, APValue &Value, 5130 Sema::CCEKind CCE, 5131 bool RequireInt) { 5132 assert(S.getLangOpts().CPlusPlus11 && 5133 "converted constant expression outside C++11"); 5134 5135 if (checkPlaceholderForOverload(S, From)) 5136 return ExprError(); 5137 5138 // C++1z [expr.const]p3: 5139 // A converted constant expression of type T is an expression, 5140 // implicitly converted to type T, where the converted 5141 // expression is a constant expression and the implicit conversion 5142 // sequence contains only [... list of conversions ...]. 5143 ImplicitConversionSequence ICS = 5144 TryCopyInitialization(S, From, T, 5145 /*SuppressUserConversions=*/false, 5146 /*InOverloadResolution=*/false, 5147 /*AllowObjcWritebackConversion=*/false, 5148 /*AllowExplicit=*/false); 5149 StandardConversionSequence *SCS = nullptr; 5150 switch (ICS.getKind()) { 5151 case ImplicitConversionSequence::StandardConversion: 5152 SCS = &ICS.Standard; 5153 break; 5154 case ImplicitConversionSequence::UserDefinedConversion: 5155 // We are converting to a non-class type, so the Before sequence 5156 // must be trivial. 5157 SCS = &ICS.UserDefined.After; 5158 break; 5159 case ImplicitConversionSequence::AmbiguousConversion: 5160 case ImplicitConversionSequence::BadConversion: 5161 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5162 return S.Diag(From->getLocStart(), 5163 diag::err_typecheck_converted_constant_expression) 5164 << From->getType() << From->getSourceRange() << T; 5165 return ExprError(); 5166 5167 case ImplicitConversionSequence::EllipsisConversion: 5168 llvm_unreachable("ellipsis conversion in converted constant expression"); 5169 } 5170 5171 // Check that we would only use permitted conversions. 5172 if (!CheckConvertedConstantConversions(S, *SCS)) { 5173 return S.Diag(From->getLocStart(), 5174 diag::err_typecheck_converted_constant_expression_disallowed) 5175 << From->getType() << From->getSourceRange() << T; 5176 } 5177 // [...] and where the reference binding (if any) binds directly. 5178 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5179 return S.Diag(From->getLocStart(), 5180 diag::err_typecheck_converted_constant_expression_indirect) 5181 << From->getType() << From->getSourceRange() << T; 5182 } 5183 5184 ExprResult Result = 5185 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5186 if (Result.isInvalid()) 5187 return Result; 5188 5189 // Check for a narrowing implicit conversion. 5190 APValue PreNarrowingValue; 5191 QualType PreNarrowingType; 5192 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5193 PreNarrowingType)) { 5194 case NK_Variable_Narrowing: 5195 // Implicit conversion to a narrower type, and the value is not a constant 5196 // expression. We'll diagnose this in a moment. 5197 case NK_Not_Narrowing: 5198 break; 5199 5200 case NK_Constant_Narrowing: 5201 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5202 << CCE << /*Constant*/1 5203 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5204 break; 5205 5206 case NK_Type_Narrowing: 5207 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5208 << CCE << /*Constant*/0 << From->getType() << T; 5209 break; 5210 } 5211 5212 // Check the expression is a constant expression. 5213 SmallVector<PartialDiagnosticAt, 8> Notes; 5214 Expr::EvalResult Eval; 5215 Eval.Diag = &Notes; 5216 5217 if ((T->isReferenceType() 5218 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5219 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5220 (RequireInt && !Eval.Val.isInt())) { 5221 // The expression can't be folded, so we can't keep it at this position in 5222 // the AST. 5223 Result = ExprError(); 5224 } else { 5225 Value = Eval.Val; 5226 5227 if (Notes.empty()) { 5228 // It's a constant expression. 5229 return Result; 5230 } 5231 } 5232 5233 // It's not a constant expression. Produce an appropriate diagnostic. 5234 if (Notes.size() == 1 && 5235 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5236 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5237 else { 5238 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5239 << CCE << From->getSourceRange(); 5240 for (unsigned I = 0; I < Notes.size(); ++I) 5241 S.Diag(Notes[I].first, Notes[I].second); 5242 } 5243 return ExprError(); 5244 } 5245 5246 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5247 APValue &Value, CCEKind CCE) { 5248 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5249 } 5250 5251 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5252 llvm::APSInt &Value, 5253 CCEKind CCE) { 5254 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5255 5256 APValue V; 5257 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5258 if (!R.isInvalid()) 5259 Value = V.getInt(); 5260 return R; 5261 } 5262 5263 5264 /// dropPointerConversions - If the given standard conversion sequence 5265 /// involves any pointer conversions, remove them. This may change 5266 /// the result type of the conversion sequence. 5267 static void dropPointerConversion(StandardConversionSequence &SCS) { 5268 if (SCS.Second == ICK_Pointer_Conversion) { 5269 SCS.Second = ICK_Identity; 5270 SCS.Third = ICK_Identity; 5271 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5272 } 5273 } 5274 5275 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5276 /// convert the expression From to an Objective-C pointer type. 5277 static ImplicitConversionSequence 5278 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5279 // Do an implicit conversion to 'id'. 5280 QualType Ty = S.Context.getObjCIdType(); 5281 ImplicitConversionSequence ICS 5282 = TryImplicitConversion(S, From, Ty, 5283 // FIXME: Are these flags correct? 5284 /*SuppressUserConversions=*/false, 5285 /*AllowExplicit=*/true, 5286 /*InOverloadResolution=*/false, 5287 /*CStyle=*/false, 5288 /*AllowObjCWritebackConversion=*/false, 5289 /*AllowObjCConversionOnExplicit=*/true); 5290 5291 // Strip off any final conversions to 'id'. 5292 switch (ICS.getKind()) { 5293 case ImplicitConversionSequence::BadConversion: 5294 case ImplicitConversionSequence::AmbiguousConversion: 5295 case ImplicitConversionSequence::EllipsisConversion: 5296 break; 5297 5298 case ImplicitConversionSequence::UserDefinedConversion: 5299 dropPointerConversion(ICS.UserDefined.After); 5300 break; 5301 5302 case ImplicitConversionSequence::StandardConversion: 5303 dropPointerConversion(ICS.Standard); 5304 break; 5305 } 5306 5307 return ICS; 5308 } 5309 5310 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5311 /// conversion of the expression From to an Objective-C pointer type. 5312 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5313 if (checkPlaceholderForOverload(*this, From)) 5314 return ExprError(); 5315 5316 QualType Ty = Context.getObjCIdType(); 5317 ImplicitConversionSequence ICS = 5318 TryContextuallyConvertToObjCPointer(*this, From); 5319 if (!ICS.isBad()) 5320 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5321 return ExprError(); 5322 } 5323 5324 /// Determine whether the provided type is an integral type, or an enumeration 5325 /// type of a permitted flavor. 5326 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5327 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5328 : T->isIntegralOrUnscopedEnumerationType(); 5329 } 5330 5331 static ExprResult 5332 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5333 Sema::ContextualImplicitConverter &Converter, 5334 QualType T, UnresolvedSetImpl &ViableConversions) { 5335 5336 if (Converter.Suppress) 5337 return ExprError(); 5338 5339 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5340 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5341 CXXConversionDecl *Conv = 5342 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5343 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5344 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5345 } 5346 return From; 5347 } 5348 5349 static bool 5350 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5351 Sema::ContextualImplicitConverter &Converter, 5352 QualType T, bool HadMultipleCandidates, 5353 UnresolvedSetImpl &ExplicitConversions) { 5354 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5355 DeclAccessPair Found = ExplicitConversions[0]; 5356 CXXConversionDecl *Conversion = 5357 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5358 5359 // The user probably meant to invoke the given explicit 5360 // conversion; use it. 5361 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5362 std::string TypeStr; 5363 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5364 5365 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5366 << FixItHint::CreateInsertion(From->getLocStart(), 5367 "static_cast<" + TypeStr + ">(") 5368 << FixItHint::CreateInsertion( 5369 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5370 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5371 5372 // If we aren't in a SFINAE context, build a call to the 5373 // explicit conversion function. 5374 if (SemaRef.isSFINAEContext()) 5375 return true; 5376 5377 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5378 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5379 HadMultipleCandidates); 5380 if (Result.isInvalid()) 5381 return true; 5382 // Record usage of conversion in an implicit cast. 5383 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5384 CK_UserDefinedConversion, Result.get(), 5385 nullptr, Result.get()->getValueKind()); 5386 } 5387 return false; 5388 } 5389 5390 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5391 Sema::ContextualImplicitConverter &Converter, 5392 QualType T, bool HadMultipleCandidates, 5393 DeclAccessPair &Found) { 5394 CXXConversionDecl *Conversion = 5395 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5396 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5397 5398 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5399 if (!Converter.SuppressConversion) { 5400 if (SemaRef.isSFINAEContext()) 5401 return true; 5402 5403 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5404 << From->getSourceRange(); 5405 } 5406 5407 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5408 HadMultipleCandidates); 5409 if (Result.isInvalid()) 5410 return true; 5411 // Record usage of conversion in an implicit cast. 5412 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5413 CK_UserDefinedConversion, Result.get(), 5414 nullptr, Result.get()->getValueKind()); 5415 return false; 5416 } 5417 5418 static ExprResult finishContextualImplicitConversion( 5419 Sema &SemaRef, SourceLocation Loc, Expr *From, 5420 Sema::ContextualImplicitConverter &Converter) { 5421 if (!Converter.match(From->getType()) && !Converter.Suppress) 5422 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5423 << From->getSourceRange(); 5424 5425 return SemaRef.DefaultLvalueConversion(From); 5426 } 5427 5428 static void 5429 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5430 UnresolvedSetImpl &ViableConversions, 5431 OverloadCandidateSet &CandidateSet) { 5432 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5433 DeclAccessPair FoundDecl = ViableConversions[I]; 5434 NamedDecl *D = FoundDecl.getDecl(); 5435 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5436 if (isa<UsingShadowDecl>(D)) 5437 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5438 5439 CXXConversionDecl *Conv; 5440 FunctionTemplateDecl *ConvTemplate; 5441 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5442 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5443 else 5444 Conv = cast<CXXConversionDecl>(D); 5445 5446 if (ConvTemplate) 5447 SemaRef.AddTemplateConversionCandidate( 5448 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5449 /*AllowObjCConversionOnExplicit=*/false); 5450 else 5451 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5452 ToType, CandidateSet, 5453 /*AllowObjCConversionOnExplicit=*/false); 5454 } 5455 } 5456 5457 /// \brief Attempt to convert the given expression to a type which is accepted 5458 /// by the given converter. 5459 /// 5460 /// This routine will attempt to convert an expression of class type to a 5461 /// type accepted by the specified converter. In C++11 and before, the class 5462 /// must have a single non-explicit conversion function converting to a matching 5463 /// type. In C++1y, there can be multiple such conversion functions, but only 5464 /// one target type. 5465 /// 5466 /// \param Loc The source location of the construct that requires the 5467 /// conversion. 5468 /// 5469 /// \param From The expression we're converting from. 5470 /// 5471 /// \param Converter Used to control and diagnose the conversion process. 5472 /// 5473 /// \returns The expression, converted to an integral or enumeration type if 5474 /// successful. 5475 ExprResult Sema::PerformContextualImplicitConversion( 5476 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5477 // We can't perform any more checking for type-dependent expressions. 5478 if (From->isTypeDependent()) 5479 return From; 5480 5481 // Process placeholders immediately. 5482 if (From->hasPlaceholderType()) { 5483 ExprResult result = CheckPlaceholderExpr(From); 5484 if (result.isInvalid()) 5485 return result; 5486 From = result.get(); 5487 } 5488 5489 // If the expression already has a matching type, we're golden. 5490 QualType T = From->getType(); 5491 if (Converter.match(T)) 5492 return DefaultLvalueConversion(From); 5493 5494 // FIXME: Check for missing '()' if T is a function type? 5495 5496 // We can only perform contextual implicit conversions on objects of class 5497 // type. 5498 const RecordType *RecordTy = T->getAs<RecordType>(); 5499 if (!RecordTy || !getLangOpts().CPlusPlus) { 5500 if (!Converter.Suppress) 5501 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5502 return From; 5503 } 5504 5505 // We must have a complete class type. 5506 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5507 ContextualImplicitConverter &Converter; 5508 Expr *From; 5509 5510 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5511 : Converter(Converter), From(From) {} 5512 5513 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5514 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5515 } 5516 } IncompleteDiagnoser(Converter, From); 5517 5518 if (Converter.Suppress ? !isCompleteType(Loc, T) 5519 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5520 return From; 5521 5522 // Look for a conversion to an integral or enumeration type. 5523 UnresolvedSet<4> 5524 ViableConversions; // These are *potentially* viable in C++1y. 5525 UnresolvedSet<4> ExplicitConversions; 5526 const auto &Conversions = 5527 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5528 5529 bool HadMultipleCandidates = 5530 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5531 5532 // To check that there is only one target type, in C++1y: 5533 QualType ToType; 5534 bool HasUniqueTargetType = true; 5535 5536 // Collect explicit or viable (potentially in C++1y) conversions. 5537 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5538 NamedDecl *D = (*I)->getUnderlyingDecl(); 5539 CXXConversionDecl *Conversion; 5540 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5541 if (ConvTemplate) { 5542 if (getLangOpts().CPlusPlus14) 5543 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5544 else 5545 continue; // C++11 does not consider conversion operator templates(?). 5546 } else 5547 Conversion = cast<CXXConversionDecl>(D); 5548 5549 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5550 "Conversion operator templates are considered potentially " 5551 "viable in C++1y"); 5552 5553 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5554 if (Converter.match(CurToType) || ConvTemplate) { 5555 5556 if (Conversion->isExplicit()) { 5557 // FIXME: For C++1y, do we need this restriction? 5558 // cf. diagnoseNoViableConversion() 5559 if (!ConvTemplate) 5560 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5561 } else { 5562 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5563 if (ToType.isNull()) 5564 ToType = CurToType.getUnqualifiedType(); 5565 else if (HasUniqueTargetType && 5566 (CurToType.getUnqualifiedType() != ToType)) 5567 HasUniqueTargetType = false; 5568 } 5569 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5570 } 5571 } 5572 } 5573 5574 if (getLangOpts().CPlusPlus14) { 5575 // C++1y [conv]p6: 5576 // ... An expression e of class type E appearing in such a context 5577 // is said to be contextually implicitly converted to a specified 5578 // type T and is well-formed if and only if e can be implicitly 5579 // converted to a type T that is determined as follows: E is searched 5580 // for conversion functions whose return type is cv T or reference to 5581 // cv T such that T is allowed by the context. There shall be 5582 // exactly one such T. 5583 5584 // If no unique T is found: 5585 if (ToType.isNull()) { 5586 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5587 HadMultipleCandidates, 5588 ExplicitConversions)) 5589 return ExprError(); 5590 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5591 } 5592 5593 // If more than one unique Ts are found: 5594 if (!HasUniqueTargetType) 5595 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5596 ViableConversions); 5597 5598 // If one unique T is found: 5599 // First, build a candidate set from the previously recorded 5600 // potentially viable conversions. 5601 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5602 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5603 CandidateSet); 5604 5605 // Then, perform overload resolution over the candidate set. 5606 OverloadCandidateSet::iterator Best; 5607 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5608 case OR_Success: { 5609 // Apply this conversion. 5610 DeclAccessPair Found = 5611 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5612 if (recordConversion(*this, Loc, From, Converter, T, 5613 HadMultipleCandidates, Found)) 5614 return ExprError(); 5615 break; 5616 } 5617 case OR_Ambiguous: 5618 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5619 ViableConversions); 5620 case OR_No_Viable_Function: 5621 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5622 HadMultipleCandidates, 5623 ExplicitConversions)) 5624 return ExprError(); 5625 // fall through 'OR_Deleted' case. 5626 case OR_Deleted: 5627 // We'll complain below about a non-integral condition type. 5628 break; 5629 } 5630 } else { 5631 switch (ViableConversions.size()) { 5632 case 0: { 5633 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5634 HadMultipleCandidates, 5635 ExplicitConversions)) 5636 return ExprError(); 5637 5638 // We'll complain below about a non-integral condition type. 5639 break; 5640 } 5641 case 1: { 5642 // Apply this conversion. 5643 DeclAccessPair Found = ViableConversions[0]; 5644 if (recordConversion(*this, Loc, From, Converter, T, 5645 HadMultipleCandidates, Found)) 5646 return ExprError(); 5647 break; 5648 } 5649 default: 5650 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5651 ViableConversions); 5652 } 5653 } 5654 5655 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5656 } 5657 5658 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5659 /// an acceptable non-member overloaded operator for a call whose 5660 /// arguments have types T1 (and, if non-empty, T2). This routine 5661 /// implements the check in C++ [over.match.oper]p3b2 concerning 5662 /// enumeration types. 5663 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5664 FunctionDecl *Fn, 5665 ArrayRef<Expr *> Args) { 5666 QualType T1 = Args[0]->getType(); 5667 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5668 5669 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5670 return true; 5671 5672 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5673 return true; 5674 5675 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5676 if (Proto->getNumParams() < 1) 5677 return false; 5678 5679 if (T1->isEnumeralType()) { 5680 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5681 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5682 return true; 5683 } 5684 5685 if (Proto->getNumParams() < 2) 5686 return false; 5687 5688 if (!T2.isNull() && T2->isEnumeralType()) { 5689 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5690 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5691 return true; 5692 } 5693 5694 return false; 5695 } 5696 5697 /// AddOverloadCandidate - Adds the given function to the set of 5698 /// candidate functions, using the given function call arguments. If 5699 /// @p SuppressUserConversions, then don't allow user-defined 5700 /// conversions via constructors or conversion operators. 5701 /// 5702 /// \param PartialOverloading true if we are performing "partial" overloading 5703 /// based on an incomplete set of function arguments. This feature is used by 5704 /// code completion. 5705 void 5706 Sema::AddOverloadCandidate(FunctionDecl *Function, 5707 DeclAccessPair FoundDecl, 5708 ArrayRef<Expr *> Args, 5709 OverloadCandidateSet &CandidateSet, 5710 bool SuppressUserConversions, 5711 bool PartialOverloading, 5712 bool AllowExplicit) { 5713 const FunctionProtoType *Proto 5714 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5715 assert(Proto && "Functions without a prototype cannot be overloaded"); 5716 assert(!Function->getDescribedFunctionTemplate() && 5717 "Use AddTemplateOverloadCandidate for function templates"); 5718 5719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5720 if (!isa<CXXConstructorDecl>(Method)) { 5721 // If we get here, it's because we're calling a member function 5722 // that is named without a member access expression (e.g., 5723 // "this->f") that was either written explicitly or created 5724 // implicitly. This can happen with a qualified call to a member 5725 // function, e.g., X::f(). We use an empty type for the implied 5726 // object argument (C++ [over.call.func]p3), and the acting context 5727 // is irrelevant. 5728 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5729 QualType(), Expr::Classification::makeSimpleLValue(), 5730 Args, CandidateSet, SuppressUserConversions, 5731 PartialOverloading); 5732 return; 5733 } 5734 // We treat a constructor like a non-member function, since its object 5735 // argument doesn't participate in overload resolution. 5736 } 5737 5738 if (!CandidateSet.isNewCandidate(Function)) 5739 return; 5740 5741 // C++ [over.match.oper]p3: 5742 // if no operand has a class type, only those non-member functions in the 5743 // lookup set that have a first parameter of type T1 or "reference to 5744 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5745 // is a right operand) a second parameter of type T2 or "reference to 5746 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5747 // candidate functions. 5748 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5749 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5750 return; 5751 5752 // C++11 [class.copy]p11: [DR1402] 5753 // A defaulted move constructor that is defined as deleted is ignored by 5754 // overload resolution. 5755 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5756 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5757 Constructor->isMoveConstructor()) 5758 return; 5759 5760 // Overload resolution is always an unevaluated context. 5761 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5762 5763 // Add this candidate 5764 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5765 Candidate.FoundDecl = FoundDecl; 5766 Candidate.Function = Function; 5767 Candidate.Viable = true; 5768 Candidate.IsSurrogate = false; 5769 Candidate.IgnoreObjectArgument = false; 5770 Candidate.ExplicitCallArguments = Args.size(); 5771 5772 if (Constructor) { 5773 // C++ [class.copy]p3: 5774 // A member function template is never instantiated to perform the copy 5775 // of a class object to an object of its class type. 5776 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5777 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5778 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5779 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5780 ClassType))) { 5781 Candidate.Viable = false; 5782 Candidate.FailureKind = ovl_fail_illegal_constructor; 5783 return; 5784 } 5785 } 5786 5787 unsigned NumParams = Proto->getNumParams(); 5788 5789 // (C++ 13.3.2p2): A candidate function having fewer than m 5790 // parameters is viable only if it has an ellipsis in its parameter 5791 // list (8.3.5). 5792 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5793 !Proto->isVariadic()) { 5794 Candidate.Viable = false; 5795 Candidate.FailureKind = ovl_fail_too_many_arguments; 5796 return; 5797 } 5798 5799 // (C++ 13.3.2p2): A candidate function having more than m parameters 5800 // is viable only if the (m+1)st parameter has a default argument 5801 // (8.3.6). For the purposes of overload resolution, the 5802 // parameter list is truncated on the right, so that there are 5803 // exactly m parameters. 5804 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5805 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5806 // Not enough arguments. 5807 Candidate.Viable = false; 5808 Candidate.FailureKind = ovl_fail_too_few_arguments; 5809 return; 5810 } 5811 5812 // (CUDA B.1): Check for invalid calls between targets. 5813 if (getLangOpts().CUDA) 5814 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5815 // Skip the check for callers that are implicit members, because in this 5816 // case we may not yet know what the member's target is; the target is 5817 // inferred for the member automatically, based on the bases and fields of 5818 // the class. 5819 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5820 Candidate.Viable = false; 5821 Candidate.FailureKind = ovl_fail_bad_target; 5822 return; 5823 } 5824 5825 // Determine the implicit conversion sequences for each of the 5826 // arguments. 5827 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5828 if (ArgIdx < NumParams) { 5829 // (C++ 13.3.2p3): for F to be a viable function, there shall 5830 // exist for each argument an implicit conversion sequence 5831 // (13.3.3.1) that converts that argument to the corresponding 5832 // parameter of F. 5833 QualType ParamType = Proto->getParamType(ArgIdx); 5834 Candidate.Conversions[ArgIdx] 5835 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5836 SuppressUserConversions, 5837 /*InOverloadResolution=*/true, 5838 /*AllowObjCWritebackConversion=*/ 5839 getLangOpts().ObjCAutoRefCount, 5840 AllowExplicit); 5841 if (Candidate.Conversions[ArgIdx].isBad()) { 5842 Candidate.Viable = false; 5843 Candidate.FailureKind = ovl_fail_bad_conversion; 5844 return; 5845 } 5846 } else { 5847 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5848 // argument for which there is no corresponding parameter is 5849 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5850 Candidate.Conversions[ArgIdx].setEllipsis(); 5851 } 5852 } 5853 5854 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5855 Candidate.Viable = false; 5856 Candidate.FailureKind = ovl_fail_enable_if; 5857 Candidate.DeductionFailure.Data = FailedAttr; 5858 return; 5859 } 5860 } 5861 5862 ObjCMethodDecl * 5863 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 5864 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5865 if (Methods.size() <= 1) 5866 return nullptr; 5867 5868 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5869 bool Match = true; 5870 ObjCMethodDecl *Method = Methods[b]; 5871 unsigned NumNamedArgs = Sel.getNumArgs(); 5872 // Method might have more arguments than selector indicates. This is due 5873 // to addition of c-style arguments in method. 5874 if (Method->param_size() > NumNamedArgs) 5875 NumNamedArgs = Method->param_size(); 5876 if (Args.size() < NumNamedArgs) 5877 continue; 5878 5879 for (unsigned i = 0; i < NumNamedArgs; i++) { 5880 // We can't do any type-checking on a type-dependent argument. 5881 if (Args[i]->isTypeDependent()) { 5882 Match = false; 5883 break; 5884 } 5885 5886 ParmVarDecl *param = Method->parameters()[i]; 5887 Expr *argExpr = Args[i]; 5888 assert(argExpr && "SelectBestMethod(): missing expression"); 5889 5890 // Strip the unbridged-cast placeholder expression off unless it's 5891 // a consumed argument. 5892 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5893 !param->hasAttr<CFConsumedAttr>()) 5894 argExpr = stripARCUnbridgedCast(argExpr); 5895 5896 // If the parameter is __unknown_anytype, move on to the next method. 5897 if (param->getType() == Context.UnknownAnyTy) { 5898 Match = false; 5899 break; 5900 } 5901 5902 ImplicitConversionSequence ConversionState 5903 = TryCopyInitialization(*this, argExpr, param->getType(), 5904 /*SuppressUserConversions*/false, 5905 /*InOverloadResolution=*/true, 5906 /*AllowObjCWritebackConversion=*/ 5907 getLangOpts().ObjCAutoRefCount, 5908 /*AllowExplicit*/false); 5909 if (ConversionState.isBad()) { 5910 Match = false; 5911 break; 5912 } 5913 } 5914 // Promote additional arguments to variadic methods. 5915 if (Match && Method->isVariadic()) { 5916 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5917 if (Args[i]->isTypeDependent()) { 5918 Match = false; 5919 break; 5920 } 5921 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5922 nullptr); 5923 if (Arg.isInvalid()) { 5924 Match = false; 5925 break; 5926 } 5927 } 5928 } else { 5929 // Check for extra arguments to non-variadic methods. 5930 if (Args.size() != NumNamedArgs) 5931 Match = false; 5932 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5933 // Special case when selectors have no argument. In this case, select 5934 // one with the most general result type of 'id'. 5935 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5936 QualType ReturnT = Methods[b]->getReturnType(); 5937 if (ReturnT->isObjCIdType()) 5938 return Methods[b]; 5939 } 5940 } 5941 } 5942 5943 if (Match) 5944 return Method; 5945 } 5946 return nullptr; 5947 } 5948 5949 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5950 // enable_if is order-sensitive. As a result, we need to reverse things 5951 // sometimes. Size of 4 elements is arbitrary. 5952 static SmallVector<EnableIfAttr *, 4> 5953 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5954 SmallVector<EnableIfAttr *, 4> Result; 5955 if (!Function->hasAttrs()) 5956 return Result; 5957 5958 const auto &FuncAttrs = Function->getAttrs(); 5959 for (Attr *Attr : FuncAttrs) 5960 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5961 Result.push_back(EnableIf); 5962 5963 std::reverse(Result.begin(), Result.end()); 5964 return Result; 5965 } 5966 5967 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5968 bool MissingImplicitThis) { 5969 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5970 if (EnableIfAttrs.empty()) 5971 return nullptr; 5972 5973 SFINAETrap Trap(*this); 5974 SmallVector<Expr *, 16> ConvertedArgs; 5975 bool InitializationFailed = false; 5976 5977 // Ignore any variadic arguments. Converting them is pointless, since the 5978 // user can't refer to them in the enable_if condition. 5979 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 5980 5981 // Convert the arguments. 5982 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 5983 ExprResult R; 5984 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5985 !cast<CXXMethodDecl>(Function)->isStatic() && 5986 !isa<CXXConstructorDecl>(Function)) { 5987 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5988 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5989 Method, Method); 5990 } else { 5991 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 5992 Context, Function->getParamDecl(I)), 5993 SourceLocation(), Args[I]); 5994 } 5995 5996 if (R.isInvalid()) { 5997 InitializationFailed = true; 5998 break; 5999 } 6000 6001 ConvertedArgs.push_back(R.get()); 6002 } 6003 6004 if (InitializationFailed || Trap.hasErrorOccurred()) 6005 return EnableIfAttrs[0]; 6006 6007 // Push default arguments if needed. 6008 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6009 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6010 ParmVarDecl *P = Function->getParamDecl(i); 6011 ExprResult R = PerformCopyInitialization( 6012 InitializedEntity::InitializeParameter(Context, 6013 Function->getParamDecl(i)), 6014 SourceLocation(), 6015 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6016 : P->getDefaultArg()); 6017 if (R.isInvalid()) { 6018 InitializationFailed = true; 6019 break; 6020 } 6021 ConvertedArgs.push_back(R.get()); 6022 } 6023 6024 if (InitializationFailed || Trap.hasErrorOccurred()) 6025 return EnableIfAttrs[0]; 6026 } 6027 6028 for (auto *EIA : EnableIfAttrs) { 6029 APValue Result; 6030 // FIXME: This doesn't consider value-dependent cases, because doing so is 6031 // very difficult. Ideally, we should handle them more gracefully. 6032 if (!EIA->getCond()->EvaluateWithSubstitution( 6033 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6034 return EIA; 6035 6036 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6037 return EIA; 6038 } 6039 return nullptr; 6040 } 6041 6042 /// \brief Add all of the function declarations in the given function set to 6043 /// the overload candidate set. 6044 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6045 ArrayRef<Expr *> Args, 6046 OverloadCandidateSet& CandidateSet, 6047 TemplateArgumentListInfo *ExplicitTemplateArgs, 6048 bool SuppressUserConversions, 6049 bool PartialOverloading) { 6050 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6051 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6052 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6053 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6054 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6055 cast<CXXMethodDecl>(FD)->getParent(), 6056 Args[0]->getType(), Args[0]->Classify(Context), 6057 Args.slice(1), CandidateSet, 6058 SuppressUserConversions, PartialOverloading); 6059 else 6060 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6061 SuppressUserConversions, PartialOverloading); 6062 } else { 6063 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6064 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6065 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6066 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6067 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6068 ExplicitTemplateArgs, 6069 Args[0]->getType(), 6070 Args[0]->Classify(Context), Args.slice(1), 6071 CandidateSet, SuppressUserConversions, 6072 PartialOverloading); 6073 else 6074 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6075 ExplicitTemplateArgs, Args, 6076 CandidateSet, SuppressUserConversions, 6077 PartialOverloading); 6078 } 6079 } 6080 } 6081 6082 /// AddMethodCandidate - Adds a named decl (which is some kind of 6083 /// method) as a method candidate to the given overload set. 6084 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6085 QualType ObjectType, 6086 Expr::Classification ObjectClassification, 6087 ArrayRef<Expr *> Args, 6088 OverloadCandidateSet& CandidateSet, 6089 bool SuppressUserConversions) { 6090 NamedDecl *Decl = FoundDecl.getDecl(); 6091 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6092 6093 if (isa<UsingShadowDecl>(Decl)) 6094 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6095 6096 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6097 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6098 "Expected a member function template"); 6099 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6100 /*ExplicitArgs*/ nullptr, 6101 ObjectType, ObjectClassification, 6102 Args, CandidateSet, 6103 SuppressUserConversions); 6104 } else { 6105 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6106 ObjectType, ObjectClassification, 6107 Args, 6108 CandidateSet, SuppressUserConversions); 6109 } 6110 } 6111 6112 /// AddMethodCandidate - Adds the given C++ member function to the set 6113 /// of candidate functions, using the given function call arguments 6114 /// and the object argument (@c Object). For example, in a call 6115 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6116 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6117 /// allow user-defined conversions via constructors or conversion 6118 /// operators. 6119 void 6120 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6121 CXXRecordDecl *ActingContext, QualType ObjectType, 6122 Expr::Classification ObjectClassification, 6123 ArrayRef<Expr *> Args, 6124 OverloadCandidateSet &CandidateSet, 6125 bool SuppressUserConversions, 6126 bool PartialOverloading) { 6127 const FunctionProtoType *Proto 6128 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6129 assert(Proto && "Methods without a prototype cannot be overloaded"); 6130 assert(!isa<CXXConstructorDecl>(Method) && 6131 "Use AddOverloadCandidate for constructors"); 6132 6133 if (!CandidateSet.isNewCandidate(Method)) 6134 return; 6135 6136 // C++11 [class.copy]p23: [DR1402] 6137 // A defaulted move assignment operator that is defined as deleted is 6138 // ignored by overload resolution. 6139 if (Method->isDefaulted() && Method->isDeleted() && 6140 Method->isMoveAssignmentOperator()) 6141 return; 6142 6143 // Overload resolution is always an unevaluated context. 6144 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6145 6146 // Add this candidate 6147 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6148 Candidate.FoundDecl = FoundDecl; 6149 Candidate.Function = Method; 6150 Candidate.IsSurrogate = false; 6151 Candidate.IgnoreObjectArgument = false; 6152 Candidate.ExplicitCallArguments = Args.size(); 6153 6154 unsigned NumParams = Proto->getNumParams(); 6155 6156 // (C++ 13.3.2p2): A candidate function having fewer than m 6157 // parameters is viable only if it has an ellipsis in its parameter 6158 // list (8.3.5). 6159 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6160 !Proto->isVariadic()) { 6161 Candidate.Viable = false; 6162 Candidate.FailureKind = ovl_fail_too_many_arguments; 6163 return; 6164 } 6165 6166 // (C++ 13.3.2p2): A candidate function having more than m parameters 6167 // is viable only if the (m+1)st parameter has a default argument 6168 // (8.3.6). For the purposes of overload resolution, the 6169 // parameter list is truncated on the right, so that there are 6170 // exactly m parameters. 6171 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6172 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6173 // Not enough arguments. 6174 Candidate.Viable = false; 6175 Candidate.FailureKind = ovl_fail_too_few_arguments; 6176 return; 6177 } 6178 6179 Candidate.Viable = true; 6180 6181 if (Method->isStatic() || ObjectType.isNull()) 6182 // The implicit object argument is ignored. 6183 Candidate.IgnoreObjectArgument = true; 6184 else { 6185 // Determine the implicit conversion sequence for the object 6186 // parameter. 6187 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6188 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6189 Method, ActingContext); 6190 if (Candidate.Conversions[0].isBad()) { 6191 Candidate.Viable = false; 6192 Candidate.FailureKind = ovl_fail_bad_conversion; 6193 return; 6194 } 6195 } 6196 6197 // (CUDA B.1): Check for invalid calls between targets. 6198 if (getLangOpts().CUDA) 6199 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6200 if (!IsAllowedCUDACall(Caller, Method)) { 6201 Candidate.Viable = false; 6202 Candidate.FailureKind = ovl_fail_bad_target; 6203 return; 6204 } 6205 6206 // Determine the implicit conversion sequences for each of the 6207 // arguments. 6208 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6209 if (ArgIdx < NumParams) { 6210 // (C++ 13.3.2p3): for F to be a viable function, there shall 6211 // exist for each argument an implicit conversion sequence 6212 // (13.3.3.1) that converts that argument to the corresponding 6213 // parameter of F. 6214 QualType ParamType = Proto->getParamType(ArgIdx); 6215 Candidate.Conversions[ArgIdx + 1] 6216 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6217 SuppressUserConversions, 6218 /*InOverloadResolution=*/true, 6219 /*AllowObjCWritebackConversion=*/ 6220 getLangOpts().ObjCAutoRefCount); 6221 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6222 Candidate.Viable = false; 6223 Candidate.FailureKind = ovl_fail_bad_conversion; 6224 return; 6225 } 6226 } else { 6227 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6228 // argument for which there is no corresponding parameter is 6229 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6230 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6231 } 6232 } 6233 6234 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6235 Candidate.Viable = false; 6236 Candidate.FailureKind = ovl_fail_enable_if; 6237 Candidate.DeductionFailure.Data = FailedAttr; 6238 return; 6239 } 6240 } 6241 6242 /// \brief Add a C++ member function template as a candidate to the candidate 6243 /// set, using template argument deduction to produce an appropriate member 6244 /// function template specialization. 6245 void 6246 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6247 DeclAccessPair FoundDecl, 6248 CXXRecordDecl *ActingContext, 6249 TemplateArgumentListInfo *ExplicitTemplateArgs, 6250 QualType ObjectType, 6251 Expr::Classification ObjectClassification, 6252 ArrayRef<Expr *> Args, 6253 OverloadCandidateSet& CandidateSet, 6254 bool SuppressUserConversions, 6255 bool PartialOverloading) { 6256 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6257 return; 6258 6259 // C++ [over.match.funcs]p7: 6260 // In each case where a candidate is a function template, candidate 6261 // function template specializations are generated using template argument 6262 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6263 // candidate functions in the usual way.113) A given name can refer to one 6264 // or more function templates and also to a set of overloaded non-template 6265 // functions. In such a case, the candidate functions generated from each 6266 // function template are combined with the set of non-template candidate 6267 // functions. 6268 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6269 FunctionDecl *Specialization = nullptr; 6270 if (TemplateDeductionResult Result 6271 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6272 Specialization, Info, PartialOverloading)) { 6273 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6274 Candidate.FoundDecl = FoundDecl; 6275 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6276 Candidate.Viable = false; 6277 Candidate.FailureKind = ovl_fail_bad_deduction; 6278 Candidate.IsSurrogate = false; 6279 Candidate.IgnoreObjectArgument = false; 6280 Candidate.ExplicitCallArguments = Args.size(); 6281 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6282 Info); 6283 return; 6284 } 6285 6286 // Add the function template specialization produced by template argument 6287 // deduction as a candidate. 6288 assert(Specialization && "Missing member function template specialization?"); 6289 assert(isa<CXXMethodDecl>(Specialization) && 6290 "Specialization is not a member function?"); 6291 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6292 ActingContext, ObjectType, ObjectClassification, Args, 6293 CandidateSet, SuppressUserConversions, PartialOverloading); 6294 } 6295 6296 /// \brief Add a C++ function template specialization as a candidate 6297 /// in the candidate set, using template argument deduction to produce 6298 /// an appropriate function template specialization. 6299 void 6300 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6301 DeclAccessPair FoundDecl, 6302 TemplateArgumentListInfo *ExplicitTemplateArgs, 6303 ArrayRef<Expr *> Args, 6304 OverloadCandidateSet& CandidateSet, 6305 bool SuppressUserConversions, 6306 bool PartialOverloading) { 6307 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6308 return; 6309 6310 // C++ [over.match.funcs]p7: 6311 // In each case where a candidate is a function template, candidate 6312 // function template specializations are generated using template argument 6313 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6314 // candidate functions in the usual way.113) A given name can refer to one 6315 // or more function templates and also to a set of overloaded non-template 6316 // functions. In such a case, the candidate functions generated from each 6317 // function template are combined with the set of non-template candidate 6318 // functions. 6319 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6320 FunctionDecl *Specialization = nullptr; 6321 if (TemplateDeductionResult Result 6322 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6323 Specialization, Info, PartialOverloading)) { 6324 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6325 Candidate.FoundDecl = FoundDecl; 6326 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6327 Candidate.Viable = false; 6328 Candidate.FailureKind = ovl_fail_bad_deduction; 6329 Candidate.IsSurrogate = false; 6330 Candidate.IgnoreObjectArgument = false; 6331 Candidate.ExplicitCallArguments = Args.size(); 6332 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6333 Info); 6334 return; 6335 } 6336 6337 // Add the function template specialization produced by template argument 6338 // deduction as a candidate. 6339 assert(Specialization && "Missing function template specialization?"); 6340 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6341 SuppressUserConversions, PartialOverloading); 6342 } 6343 6344 /// Determine whether this is an allowable conversion from the result 6345 /// of an explicit conversion operator to the expected type, per C++ 6346 /// [over.match.conv]p1 and [over.match.ref]p1. 6347 /// 6348 /// \param ConvType The return type of the conversion function. 6349 /// 6350 /// \param ToType The type we are converting to. 6351 /// 6352 /// \param AllowObjCPointerConversion Allow a conversion from one 6353 /// Objective-C pointer to another. 6354 /// 6355 /// \returns true if the conversion is allowable, false otherwise. 6356 static bool isAllowableExplicitConversion(Sema &S, 6357 QualType ConvType, QualType ToType, 6358 bool AllowObjCPointerConversion) { 6359 QualType ToNonRefType = ToType.getNonReferenceType(); 6360 6361 // Easy case: the types are the same. 6362 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6363 return true; 6364 6365 // Allow qualification conversions. 6366 bool ObjCLifetimeConversion; 6367 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6368 ObjCLifetimeConversion)) 6369 return true; 6370 6371 // If we're not allowed to consider Objective-C pointer conversions, 6372 // we're done. 6373 if (!AllowObjCPointerConversion) 6374 return false; 6375 6376 // Is this an Objective-C pointer conversion? 6377 bool IncompatibleObjC = false; 6378 QualType ConvertedType; 6379 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6380 IncompatibleObjC); 6381 } 6382 6383 /// AddConversionCandidate - Add a C++ conversion function as a 6384 /// candidate in the candidate set (C++ [over.match.conv], 6385 /// C++ [over.match.copy]). From is the expression we're converting from, 6386 /// and ToType is the type that we're eventually trying to convert to 6387 /// (which may or may not be the same type as the type that the 6388 /// conversion function produces). 6389 void 6390 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6391 DeclAccessPair FoundDecl, 6392 CXXRecordDecl *ActingContext, 6393 Expr *From, QualType ToType, 6394 OverloadCandidateSet& CandidateSet, 6395 bool AllowObjCConversionOnExplicit) { 6396 assert(!Conversion->getDescribedFunctionTemplate() && 6397 "Conversion function templates use AddTemplateConversionCandidate"); 6398 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6399 if (!CandidateSet.isNewCandidate(Conversion)) 6400 return; 6401 6402 // If the conversion function has an undeduced return type, trigger its 6403 // deduction now. 6404 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6405 if (DeduceReturnType(Conversion, From->getExprLoc())) 6406 return; 6407 ConvType = Conversion->getConversionType().getNonReferenceType(); 6408 } 6409 6410 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6411 // operator is only a candidate if its return type is the target type or 6412 // can be converted to the target type with a qualification conversion. 6413 if (Conversion->isExplicit() && 6414 !isAllowableExplicitConversion(*this, ConvType, ToType, 6415 AllowObjCConversionOnExplicit)) 6416 return; 6417 6418 // Overload resolution is always an unevaluated context. 6419 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6420 6421 // Add this candidate 6422 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6423 Candidate.FoundDecl = FoundDecl; 6424 Candidate.Function = Conversion; 6425 Candidate.IsSurrogate = false; 6426 Candidate.IgnoreObjectArgument = false; 6427 Candidate.FinalConversion.setAsIdentityConversion(); 6428 Candidate.FinalConversion.setFromType(ConvType); 6429 Candidate.FinalConversion.setAllToTypes(ToType); 6430 Candidate.Viable = true; 6431 Candidate.ExplicitCallArguments = 1; 6432 6433 // C++ [over.match.funcs]p4: 6434 // For conversion functions, the function is considered to be a member of 6435 // the class of the implicit implied object argument for the purpose of 6436 // defining the type of the implicit object parameter. 6437 // 6438 // Determine the implicit conversion sequence for the implicit 6439 // object parameter. 6440 QualType ImplicitParamType = From->getType(); 6441 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6442 ImplicitParamType = FromPtrType->getPointeeType(); 6443 CXXRecordDecl *ConversionContext 6444 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6445 6446 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6447 *this, CandidateSet.getLocation(), From->getType(), 6448 From->Classify(Context), Conversion, ConversionContext); 6449 6450 if (Candidate.Conversions[0].isBad()) { 6451 Candidate.Viable = false; 6452 Candidate.FailureKind = ovl_fail_bad_conversion; 6453 return; 6454 } 6455 6456 // We won't go through a user-defined type conversion function to convert a 6457 // derived to base as such conversions are given Conversion Rank. They only 6458 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6459 QualType FromCanon 6460 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6461 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6462 if (FromCanon == ToCanon || 6463 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6464 Candidate.Viable = false; 6465 Candidate.FailureKind = ovl_fail_trivial_conversion; 6466 return; 6467 } 6468 6469 // To determine what the conversion from the result of calling the 6470 // conversion function to the type we're eventually trying to 6471 // convert to (ToType), we need to synthesize a call to the 6472 // conversion function and attempt copy initialization from it. This 6473 // makes sure that we get the right semantics with respect to 6474 // lvalues/rvalues and the type. Fortunately, we can allocate this 6475 // call on the stack and we don't need its arguments to be 6476 // well-formed. 6477 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6478 VK_LValue, From->getLocStart()); 6479 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6480 Context.getPointerType(Conversion->getType()), 6481 CK_FunctionToPointerDecay, 6482 &ConversionRef, VK_RValue); 6483 6484 QualType ConversionType = Conversion->getConversionType(); 6485 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6486 Candidate.Viable = false; 6487 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6488 return; 6489 } 6490 6491 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6492 6493 // Note that it is safe to allocate CallExpr on the stack here because 6494 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6495 // allocator). 6496 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6497 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6498 From->getLocStart()); 6499 ImplicitConversionSequence ICS = 6500 TryCopyInitialization(*this, &Call, ToType, 6501 /*SuppressUserConversions=*/true, 6502 /*InOverloadResolution=*/false, 6503 /*AllowObjCWritebackConversion=*/false); 6504 6505 switch (ICS.getKind()) { 6506 case ImplicitConversionSequence::StandardConversion: 6507 Candidate.FinalConversion = ICS.Standard; 6508 6509 // C++ [over.ics.user]p3: 6510 // If the user-defined conversion is specified by a specialization of a 6511 // conversion function template, the second standard conversion sequence 6512 // shall have exact match rank. 6513 if (Conversion->getPrimaryTemplate() && 6514 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6515 Candidate.Viable = false; 6516 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6517 return; 6518 } 6519 6520 // C++0x [dcl.init.ref]p5: 6521 // In the second case, if the reference is an rvalue reference and 6522 // the second standard conversion sequence of the user-defined 6523 // conversion sequence includes an lvalue-to-rvalue conversion, the 6524 // program is ill-formed. 6525 if (ToType->isRValueReferenceType() && 6526 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6527 Candidate.Viable = false; 6528 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6529 return; 6530 } 6531 break; 6532 6533 case ImplicitConversionSequence::BadConversion: 6534 Candidate.Viable = false; 6535 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6536 return; 6537 6538 default: 6539 llvm_unreachable( 6540 "Can only end up with a standard conversion sequence or failure"); 6541 } 6542 6543 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6544 Candidate.Viable = false; 6545 Candidate.FailureKind = ovl_fail_enable_if; 6546 Candidate.DeductionFailure.Data = FailedAttr; 6547 return; 6548 } 6549 } 6550 6551 /// \brief Adds a conversion function template specialization 6552 /// candidate to the overload set, using template argument deduction 6553 /// to deduce the template arguments of the conversion function 6554 /// template from the type that we are converting to (C++ 6555 /// [temp.deduct.conv]). 6556 void 6557 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6558 DeclAccessPair FoundDecl, 6559 CXXRecordDecl *ActingDC, 6560 Expr *From, QualType ToType, 6561 OverloadCandidateSet &CandidateSet, 6562 bool AllowObjCConversionOnExplicit) { 6563 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6564 "Only conversion function templates permitted here"); 6565 6566 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6567 return; 6568 6569 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6570 CXXConversionDecl *Specialization = nullptr; 6571 if (TemplateDeductionResult Result 6572 = DeduceTemplateArguments(FunctionTemplate, ToType, 6573 Specialization, Info)) { 6574 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6575 Candidate.FoundDecl = FoundDecl; 6576 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6577 Candidate.Viable = false; 6578 Candidate.FailureKind = ovl_fail_bad_deduction; 6579 Candidate.IsSurrogate = false; 6580 Candidate.IgnoreObjectArgument = false; 6581 Candidate.ExplicitCallArguments = 1; 6582 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6583 Info); 6584 return; 6585 } 6586 6587 // Add the conversion function template specialization produced by 6588 // template argument deduction as a candidate. 6589 assert(Specialization && "Missing function template specialization?"); 6590 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6591 CandidateSet, AllowObjCConversionOnExplicit); 6592 } 6593 6594 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6595 /// converts the given @c Object to a function pointer via the 6596 /// conversion function @c Conversion, and then attempts to call it 6597 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6598 /// the type of function that we'll eventually be calling. 6599 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6600 DeclAccessPair FoundDecl, 6601 CXXRecordDecl *ActingContext, 6602 const FunctionProtoType *Proto, 6603 Expr *Object, 6604 ArrayRef<Expr *> Args, 6605 OverloadCandidateSet& CandidateSet) { 6606 if (!CandidateSet.isNewCandidate(Conversion)) 6607 return; 6608 6609 // Overload resolution is always an unevaluated context. 6610 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6611 6612 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6613 Candidate.FoundDecl = FoundDecl; 6614 Candidate.Function = nullptr; 6615 Candidate.Surrogate = Conversion; 6616 Candidate.Viable = true; 6617 Candidate.IsSurrogate = true; 6618 Candidate.IgnoreObjectArgument = false; 6619 Candidate.ExplicitCallArguments = Args.size(); 6620 6621 // Determine the implicit conversion sequence for the implicit 6622 // object parameter. 6623 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6624 *this, CandidateSet.getLocation(), Object->getType(), 6625 Object->Classify(Context), Conversion, ActingContext); 6626 if (ObjectInit.isBad()) { 6627 Candidate.Viable = false; 6628 Candidate.FailureKind = ovl_fail_bad_conversion; 6629 Candidate.Conversions[0] = ObjectInit; 6630 return; 6631 } 6632 6633 // The first conversion is actually a user-defined conversion whose 6634 // first conversion is ObjectInit's standard conversion (which is 6635 // effectively a reference binding). Record it as such. 6636 Candidate.Conversions[0].setUserDefined(); 6637 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6638 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6639 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6640 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6641 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6642 Candidate.Conversions[0].UserDefined.After 6643 = Candidate.Conversions[0].UserDefined.Before; 6644 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6645 6646 // Find the 6647 unsigned NumParams = Proto->getNumParams(); 6648 6649 // (C++ 13.3.2p2): A candidate function having fewer than m 6650 // parameters is viable only if it has an ellipsis in its parameter 6651 // list (8.3.5). 6652 if (Args.size() > NumParams && !Proto->isVariadic()) { 6653 Candidate.Viable = false; 6654 Candidate.FailureKind = ovl_fail_too_many_arguments; 6655 return; 6656 } 6657 6658 // Function types don't have any default arguments, so just check if 6659 // we have enough arguments. 6660 if (Args.size() < NumParams) { 6661 // Not enough arguments. 6662 Candidate.Viable = false; 6663 Candidate.FailureKind = ovl_fail_too_few_arguments; 6664 return; 6665 } 6666 6667 // Determine the implicit conversion sequences for each of the 6668 // arguments. 6669 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6670 if (ArgIdx < NumParams) { 6671 // (C++ 13.3.2p3): for F to be a viable function, there shall 6672 // exist for each argument an implicit conversion sequence 6673 // (13.3.3.1) that converts that argument to the corresponding 6674 // parameter of F. 6675 QualType ParamType = Proto->getParamType(ArgIdx); 6676 Candidate.Conversions[ArgIdx + 1] 6677 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6678 /*SuppressUserConversions=*/false, 6679 /*InOverloadResolution=*/false, 6680 /*AllowObjCWritebackConversion=*/ 6681 getLangOpts().ObjCAutoRefCount); 6682 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6683 Candidate.Viable = false; 6684 Candidate.FailureKind = ovl_fail_bad_conversion; 6685 return; 6686 } 6687 } else { 6688 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6689 // argument for which there is no corresponding parameter is 6690 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6691 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6692 } 6693 } 6694 6695 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6696 Candidate.Viable = false; 6697 Candidate.FailureKind = ovl_fail_enable_if; 6698 Candidate.DeductionFailure.Data = FailedAttr; 6699 return; 6700 } 6701 } 6702 6703 /// \brief Add overload candidates for overloaded operators that are 6704 /// member functions. 6705 /// 6706 /// Add the overloaded operator candidates that are member functions 6707 /// for the operator Op that was used in an operator expression such 6708 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6709 /// CandidateSet will store the added overload candidates. (C++ 6710 /// [over.match.oper]). 6711 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6712 SourceLocation OpLoc, 6713 ArrayRef<Expr *> Args, 6714 OverloadCandidateSet& CandidateSet, 6715 SourceRange OpRange) { 6716 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6717 6718 // C++ [over.match.oper]p3: 6719 // For a unary operator @ with an operand of a type whose 6720 // cv-unqualified version is T1, and for a binary operator @ with 6721 // a left operand of a type whose cv-unqualified version is T1 and 6722 // a right operand of a type whose cv-unqualified version is T2, 6723 // three sets of candidate functions, designated member 6724 // candidates, non-member candidates and built-in candidates, are 6725 // constructed as follows: 6726 QualType T1 = Args[0]->getType(); 6727 6728 // -- If T1 is a complete class type or a class currently being 6729 // defined, the set of member candidates is the result of the 6730 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6731 // the set of member candidates is empty. 6732 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6733 // Complete the type if it can be completed. 6734 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6735 return; 6736 // If the type is neither complete nor being defined, bail out now. 6737 if (!T1Rec->getDecl()->getDefinition()) 6738 return; 6739 6740 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6741 LookupQualifiedName(Operators, T1Rec->getDecl()); 6742 Operators.suppressDiagnostics(); 6743 6744 for (LookupResult::iterator Oper = Operators.begin(), 6745 OperEnd = Operators.end(); 6746 Oper != OperEnd; 6747 ++Oper) 6748 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6749 Args[0]->Classify(Context), 6750 Args.slice(1), 6751 CandidateSet, 6752 /* SuppressUserConversions = */ false); 6753 } 6754 } 6755 6756 /// AddBuiltinCandidate - Add a candidate for a built-in 6757 /// operator. ResultTy and ParamTys are the result and parameter types 6758 /// of the built-in candidate, respectively. Args and NumArgs are the 6759 /// arguments being passed to the candidate. IsAssignmentOperator 6760 /// should be true when this built-in candidate is an assignment 6761 /// operator. NumContextualBoolArguments is the number of arguments 6762 /// (at the beginning of the argument list) that will be contextually 6763 /// converted to bool. 6764 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6765 ArrayRef<Expr *> Args, 6766 OverloadCandidateSet& CandidateSet, 6767 bool IsAssignmentOperator, 6768 unsigned NumContextualBoolArguments) { 6769 // Overload resolution is always an unevaluated context. 6770 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6771 6772 // Add this candidate 6773 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6774 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6775 Candidate.Function = nullptr; 6776 Candidate.IsSurrogate = false; 6777 Candidate.IgnoreObjectArgument = false; 6778 Candidate.BuiltinTypes.ResultTy = ResultTy; 6779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6780 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6781 6782 // Determine the implicit conversion sequences for each of the 6783 // arguments. 6784 Candidate.Viable = true; 6785 Candidate.ExplicitCallArguments = Args.size(); 6786 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6787 // C++ [over.match.oper]p4: 6788 // For the built-in assignment operators, conversions of the 6789 // left operand are restricted as follows: 6790 // -- no temporaries are introduced to hold the left operand, and 6791 // -- no user-defined conversions are applied to the left 6792 // operand to achieve a type match with the left-most 6793 // parameter of a built-in candidate. 6794 // 6795 // We block these conversions by turning off user-defined 6796 // conversions, since that is the only way that initialization of 6797 // a reference to a non-class type can occur from something that 6798 // is not of the same type. 6799 if (ArgIdx < NumContextualBoolArguments) { 6800 assert(ParamTys[ArgIdx] == Context.BoolTy && 6801 "Contextual conversion to bool requires bool type"); 6802 Candidate.Conversions[ArgIdx] 6803 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6804 } else { 6805 Candidate.Conversions[ArgIdx] 6806 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6807 ArgIdx == 0 && IsAssignmentOperator, 6808 /*InOverloadResolution=*/false, 6809 /*AllowObjCWritebackConversion=*/ 6810 getLangOpts().ObjCAutoRefCount); 6811 } 6812 if (Candidate.Conversions[ArgIdx].isBad()) { 6813 Candidate.Viable = false; 6814 Candidate.FailureKind = ovl_fail_bad_conversion; 6815 break; 6816 } 6817 } 6818 } 6819 6820 namespace { 6821 6822 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6823 /// candidate operator functions for built-in operators (C++ 6824 /// [over.built]). The types are separated into pointer types and 6825 /// enumeration types. 6826 class BuiltinCandidateTypeSet { 6827 /// TypeSet - A set of types. 6828 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6829 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6830 6831 /// PointerTypes - The set of pointer types that will be used in the 6832 /// built-in candidates. 6833 TypeSet PointerTypes; 6834 6835 /// MemberPointerTypes - The set of member pointer types that will be 6836 /// used in the built-in candidates. 6837 TypeSet MemberPointerTypes; 6838 6839 /// EnumerationTypes - The set of enumeration types that will be 6840 /// used in the built-in candidates. 6841 TypeSet EnumerationTypes; 6842 6843 /// \brief The set of vector types that will be used in the built-in 6844 /// candidates. 6845 TypeSet VectorTypes; 6846 6847 /// \brief A flag indicating non-record types are viable candidates 6848 bool HasNonRecordTypes; 6849 6850 /// \brief A flag indicating whether either arithmetic or enumeration types 6851 /// were present in the candidate set. 6852 bool HasArithmeticOrEnumeralTypes; 6853 6854 /// \brief A flag indicating whether the nullptr type was present in the 6855 /// candidate set. 6856 bool HasNullPtrType; 6857 6858 /// Sema - The semantic analysis instance where we are building the 6859 /// candidate type set. 6860 Sema &SemaRef; 6861 6862 /// Context - The AST context in which we will build the type sets. 6863 ASTContext &Context; 6864 6865 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6866 const Qualifiers &VisibleQuals); 6867 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6868 6869 public: 6870 /// iterator - Iterates through the types that are part of the set. 6871 typedef TypeSet::iterator iterator; 6872 6873 BuiltinCandidateTypeSet(Sema &SemaRef) 6874 : HasNonRecordTypes(false), 6875 HasArithmeticOrEnumeralTypes(false), 6876 HasNullPtrType(false), 6877 SemaRef(SemaRef), 6878 Context(SemaRef.Context) { } 6879 6880 void AddTypesConvertedFrom(QualType Ty, 6881 SourceLocation Loc, 6882 bool AllowUserConversions, 6883 bool AllowExplicitConversions, 6884 const Qualifiers &VisibleTypeConversionsQuals); 6885 6886 /// pointer_begin - First pointer type found; 6887 iterator pointer_begin() { return PointerTypes.begin(); } 6888 6889 /// pointer_end - Past the last pointer type found; 6890 iterator pointer_end() { return PointerTypes.end(); } 6891 6892 /// member_pointer_begin - First member pointer type found; 6893 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6894 6895 /// member_pointer_end - Past the last member pointer type found; 6896 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6897 6898 /// enumeration_begin - First enumeration type found; 6899 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6900 6901 /// enumeration_end - Past the last enumeration type found; 6902 iterator enumeration_end() { return EnumerationTypes.end(); } 6903 6904 iterator vector_begin() { return VectorTypes.begin(); } 6905 iterator vector_end() { return VectorTypes.end(); } 6906 6907 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6908 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6909 bool hasNullPtrType() const { return HasNullPtrType; } 6910 }; 6911 6912 } // end anonymous namespace 6913 6914 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6915 /// the set of pointer types along with any more-qualified variants of 6916 /// that type. For example, if @p Ty is "int const *", this routine 6917 /// will add "int const *", "int const volatile *", "int const 6918 /// restrict *", and "int const volatile restrict *" to the set of 6919 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6920 /// false otherwise. 6921 /// 6922 /// FIXME: what to do about extended qualifiers? 6923 bool 6924 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6925 const Qualifiers &VisibleQuals) { 6926 6927 // Insert this type. 6928 if (!PointerTypes.insert(Ty)) 6929 return false; 6930 6931 QualType PointeeTy; 6932 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6933 bool buildObjCPtr = false; 6934 if (!PointerTy) { 6935 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6936 PointeeTy = PTy->getPointeeType(); 6937 buildObjCPtr = true; 6938 } else { 6939 PointeeTy = PointerTy->getPointeeType(); 6940 } 6941 6942 // Don't add qualified variants of arrays. For one, they're not allowed 6943 // (the qualifier would sink to the element type), and for another, the 6944 // only overload situation where it matters is subscript or pointer +- int, 6945 // and those shouldn't have qualifier variants anyway. 6946 if (PointeeTy->isArrayType()) 6947 return true; 6948 6949 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6950 bool hasVolatile = VisibleQuals.hasVolatile(); 6951 bool hasRestrict = VisibleQuals.hasRestrict(); 6952 6953 // Iterate through all strict supersets of BaseCVR. 6954 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6955 if ((CVR | BaseCVR) != CVR) continue; 6956 // Skip over volatile if no volatile found anywhere in the types. 6957 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6958 6959 // Skip over restrict if no restrict found anywhere in the types, or if 6960 // the type cannot be restrict-qualified. 6961 if ((CVR & Qualifiers::Restrict) && 6962 (!hasRestrict || 6963 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6964 continue; 6965 6966 // Build qualified pointee type. 6967 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6968 6969 // Build qualified pointer type. 6970 QualType QPointerTy; 6971 if (!buildObjCPtr) 6972 QPointerTy = Context.getPointerType(QPointeeTy); 6973 else 6974 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6975 6976 // Insert qualified pointer type. 6977 PointerTypes.insert(QPointerTy); 6978 } 6979 6980 return true; 6981 } 6982 6983 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6984 /// to the set of pointer types along with any more-qualified variants of 6985 /// that type. For example, if @p Ty is "int const *", this routine 6986 /// will add "int const *", "int const volatile *", "int const 6987 /// restrict *", and "int const volatile restrict *" to the set of 6988 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6989 /// false otherwise. 6990 /// 6991 /// FIXME: what to do about extended qualifiers? 6992 bool 6993 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6994 QualType Ty) { 6995 // Insert this type. 6996 if (!MemberPointerTypes.insert(Ty)) 6997 return false; 6998 6999 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7000 assert(PointerTy && "type was not a member pointer type!"); 7001 7002 QualType PointeeTy = PointerTy->getPointeeType(); 7003 // Don't add qualified variants of arrays. For one, they're not allowed 7004 // (the qualifier would sink to the element type), and for another, the 7005 // only overload situation where it matters is subscript or pointer +- int, 7006 // and those shouldn't have qualifier variants anyway. 7007 if (PointeeTy->isArrayType()) 7008 return true; 7009 const Type *ClassTy = PointerTy->getClass(); 7010 7011 // Iterate through all strict supersets of the pointee type's CVR 7012 // qualifiers. 7013 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7014 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7015 if ((CVR | BaseCVR) != CVR) continue; 7016 7017 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7018 MemberPointerTypes.insert( 7019 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7020 } 7021 7022 return true; 7023 } 7024 7025 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7026 /// Ty can be implicit converted to the given set of @p Types. We're 7027 /// primarily interested in pointer types and enumeration types. We also 7028 /// take member pointer types, for the conditional operator. 7029 /// AllowUserConversions is true if we should look at the conversion 7030 /// functions of a class type, and AllowExplicitConversions if we 7031 /// should also include the explicit conversion functions of a class 7032 /// type. 7033 void 7034 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7035 SourceLocation Loc, 7036 bool AllowUserConversions, 7037 bool AllowExplicitConversions, 7038 const Qualifiers &VisibleQuals) { 7039 // Only deal with canonical types. 7040 Ty = Context.getCanonicalType(Ty); 7041 7042 // Look through reference types; they aren't part of the type of an 7043 // expression for the purposes of conversions. 7044 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7045 Ty = RefTy->getPointeeType(); 7046 7047 // If we're dealing with an array type, decay to the pointer. 7048 if (Ty->isArrayType()) 7049 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7050 7051 // Otherwise, we don't care about qualifiers on the type. 7052 Ty = Ty.getLocalUnqualifiedType(); 7053 7054 // Flag if we ever add a non-record type. 7055 const RecordType *TyRec = Ty->getAs<RecordType>(); 7056 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7057 7058 // Flag if we encounter an arithmetic type. 7059 HasArithmeticOrEnumeralTypes = 7060 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7061 7062 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7063 PointerTypes.insert(Ty); 7064 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7065 // Insert our type, and its more-qualified variants, into the set 7066 // of types. 7067 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7068 return; 7069 } else if (Ty->isMemberPointerType()) { 7070 // Member pointers are far easier, since the pointee can't be converted. 7071 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7072 return; 7073 } else if (Ty->isEnumeralType()) { 7074 HasArithmeticOrEnumeralTypes = true; 7075 EnumerationTypes.insert(Ty); 7076 } else if (Ty->isVectorType()) { 7077 // We treat vector types as arithmetic types in many contexts as an 7078 // extension. 7079 HasArithmeticOrEnumeralTypes = true; 7080 VectorTypes.insert(Ty); 7081 } else if (Ty->isNullPtrType()) { 7082 HasNullPtrType = true; 7083 } else if (AllowUserConversions && TyRec) { 7084 // No conversion functions in incomplete types. 7085 if (!SemaRef.isCompleteType(Loc, Ty)) 7086 return; 7087 7088 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7089 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7090 if (isa<UsingShadowDecl>(D)) 7091 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7092 7093 // Skip conversion function templates; they don't tell us anything 7094 // about which builtin types we can convert to. 7095 if (isa<FunctionTemplateDecl>(D)) 7096 continue; 7097 7098 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7099 if (AllowExplicitConversions || !Conv->isExplicit()) { 7100 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7101 VisibleQuals); 7102 } 7103 } 7104 } 7105 } 7106 7107 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7108 /// the volatile- and non-volatile-qualified assignment operators for the 7109 /// given type to the candidate set. 7110 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7111 QualType T, 7112 ArrayRef<Expr *> Args, 7113 OverloadCandidateSet &CandidateSet) { 7114 QualType ParamTypes[2]; 7115 7116 // T& operator=(T&, T) 7117 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7118 ParamTypes[1] = T; 7119 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7120 /*IsAssignmentOperator=*/true); 7121 7122 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7123 // volatile T& operator=(volatile T&, T) 7124 ParamTypes[0] 7125 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7126 ParamTypes[1] = T; 7127 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7128 /*IsAssignmentOperator=*/true); 7129 } 7130 } 7131 7132 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7133 /// if any, found in visible type conversion functions found in ArgExpr's type. 7134 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7135 Qualifiers VRQuals; 7136 const RecordType *TyRec; 7137 if (const MemberPointerType *RHSMPType = 7138 ArgExpr->getType()->getAs<MemberPointerType>()) 7139 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7140 else 7141 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7142 if (!TyRec) { 7143 // Just to be safe, assume the worst case. 7144 VRQuals.addVolatile(); 7145 VRQuals.addRestrict(); 7146 return VRQuals; 7147 } 7148 7149 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7150 if (!ClassDecl->hasDefinition()) 7151 return VRQuals; 7152 7153 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7154 if (isa<UsingShadowDecl>(D)) 7155 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7156 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7157 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7158 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7159 CanTy = ResTypeRef->getPointeeType(); 7160 // Need to go down the pointer/mempointer chain and add qualifiers 7161 // as see them. 7162 bool done = false; 7163 while (!done) { 7164 if (CanTy.isRestrictQualified()) 7165 VRQuals.addRestrict(); 7166 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7167 CanTy = ResTypePtr->getPointeeType(); 7168 else if (const MemberPointerType *ResTypeMPtr = 7169 CanTy->getAs<MemberPointerType>()) 7170 CanTy = ResTypeMPtr->getPointeeType(); 7171 else 7172 done = true; 7173 if (CanTy.isVolatileQualified()) 7174 VRQuals.addVolatile(); 7175 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7176 return VRQuals; 7177 } 7178 } 7179 } 7180 return VRQuals; 7181 } 7182 7183 namespace { 7184 7185 /// \brief Helper class to manage the addition of builtin operator overload 7186 /// candidates. It provides shared state and utility methods used throughout 7187 /// the process, as well as a helper method to add each group of builtin 7188 /// operator overloads from the standard to a candidate set. 7189 class BuiltinOperatorOverloadBuilder { 7190 // Common instance state available to all overload candidate addition methods. 7191 Sema &S; 7192 ArrayRef<Expr *> Args; 7193 Qualifiers VisibleTypeConversionsQuals; 7194 bool HasArithmeticOrEnumeralCandidateType; 7195 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7196 OverloadCandidateSet &CandidateSet; 7197 7198 // Define some constants used to index and iterate over the arithemetic types 7199 // provided via the getArithmeticType() method below. 7200 // The "promoted arithmetic types" are the arithmetic 7201 // types are that preserved by promotion (C++ [over.built]p2). 7202 static const unsigned FirstIntegralType = 4; 7203 static const unsigned LastIntegralType = 21; 7204 static const unsigned FirstPromotedIntegralType = 4, 7205 LastPromotedIntegralType = 12; 7206 static const unsigned FirstPromotedArithmeticType = 0, 7207 LastPromotedArithmeticType = 12; 7208 static const unsigned NumArithmeticTypes = 21; 7209 7210 /// \brief Get the canonical type for a given arithmetic type index. 7211 CanQualType getArithmeticType(unsigned index) { 7212 assert(index < NumArithmeticTypes); 7213 static CanQualType ASTContext::* const 7214 ArithmeticTypes[NumArithmeticTypes] = { 7215 // Start of promoted types. 7216 &ASTContext::FloatTy, 7217 &ASTContext::DoubleTy, 7218 &ASTContext::LongDoubleTy, 7219 &ASTContext::Float128Ty, 7220 7221 // Start of integral types. 7222 &ASTContext::IntTy, 7223 &ASTContext::LongTy, 7224 &ASTContext::LongLongTy, 7225 &ASTContext::Int128Ty, 7226 &ASTContext::UnsignedIntTy, 7227 &ASTContext::UnsignedLongTy, 7228 &ASTContext::UnsignedLongLongTy, 7229 &ASTContext::UnsignedInt128Ty, 7230 // End of promoted types. 7231 7232 &ASTContext::BoolTy, 7233 &ASTContext::CharTy, 7234 &ASTContext::WCharTy, 7235 &ASTContext::Char16Ty, 7236 &ASTContext::Char32Ty, 7237 &ASTContext::SignedCharTy, 7238 &ASTContext::ShortTy, 7239 &ASTContext::UnsignedCharTy, 7240 &ASTContext::UnsignedShortTy, 7241 // End of integral types. 7242 // FIXME: What about complex? What about half? 7243 }; 7244 return S.Context.*ArithmeticTypes[index]; 7245 } 7246 7247 /// \brief Gets the canonical type resulting from the usual arithemetic 7248 /// converions for the given arithmetic types. 7249 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7250 // Accelerator table for performing the usual arithmetic conversions. 7251 // The rules are basically: 7252 // - if either is floating-point, use the wider floating-point 7253 // - if same signedness, use the higher rank 7254 // - if same size, use unsigned of the higher rank 7255 // - use the larger type 7256 // These rules, together with the axiom that higher ranks are 7257 // never smaller, are sufficient to precompute all of these results 7258 // *except* when dealing with signed types of higher rank. 7259 // (we could precompute SLL x UI for all known platforms, but it's 7260 // better not to make any assumptions). 7261 // We assume that int128 has a higher rank than long long on all platforms. 7262 enum PromotedType : int8_t { 7263 Dep=-1, 7264 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7265 }; 7266 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7267 [LastPromotedArithmeticType] = { 7268 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7269 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7270 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7271 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7272 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7273 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7274 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7275 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7276 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7277 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7278 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7279 }; 7280 7281 assert(L < LastPromotedArithmeticType); 7282 assert(R < LastPromotedArithmeticType); 7283 int Idx = ConversionsTable[L][R]; 7284 7285 // Fast path: the table gives us a concrete answer. 7286 if (Idx != Dep) return getArithmeticType(Idx); 7287 7288 // Slow path: we need to compare widths. 7289 // An invariant is that the signed type has higher rank. 7290 CanQualType LT = getArithmeticType(L), 7291 RT = getArithmeticType(R); 7292 unsigned LW = S.Context.getIntWidth(LT), 7293 RW = S.Context.getIntWidth(RT); 7294 7295 // If they're different widths, use the signed type. 7296 if (LW > RW) return LT; 7297 else if (LW < RW) return RT; 7298 7299 // Otherwise, use the unsigned type of the signed type's rank. 7300 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7301 assert(L == SLL || R == SLL); 7302 return S.Context.UnsignedLongLongTy; 7303 } 7304 7305 /// \brief Helper method to factor out the common pattern of adding overloads 7306 /// for '++' and '--' builtin operators. 7307 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7308 bool HasVolatile, 7309 bool HasRestrict) { 7310 QualType ParamTypes[2] = { 7311 S.Context.getLValueReferenceType(CandidateTy), 7312 S.Context.IntTy 7313 }; 7314 7315 // Non-volatile version. 7316 if (Args.size() == 1) 7317 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7318 else 7319 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7320 7321 // Use a heuristic to reduce number of builtin candidates in the set: 7322 // add volatile version only if there are conversions to a volatile type. 7323 if (HasVolatile) { 7324 ParamTypes[0] = 7325 S.Context.getLValueReferenceType( 7326 S.Context.getVolatileType(CandidateTy)); 7327 if (Args.size() == 1) 7328 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7329 else 7330 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7331 } 7332 7333 // Add restrict version only if there are conversions to a restrict type 7334 // and our candidate type is a non-restrict-qualified pointer. 7335 if (HasRestrict && CandidateTy->isAnyPointerType() && 7336 !CandidateTy.isRestrictQualified()) { 7337 ParamTypes[0] 7338 = S.Context.getLValueReferenceType( 7339 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7340 if (Args.size() == 1) 7341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7342 else 7343 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7344 7345 if (HasVolatile) { 7346 ParamTypes[0] 7347 = S.Context.getLValueReferenceType( 7348 S.Context.getCVRQualifiedType(CandidateTy, 7349 (Qualifiers::Volatile | 7350 Qualifiers::Restrict))); 7351 if (Args.size() == 1) 7352 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7353 else 7354 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7355 } 7356 } 7357 7358 } 7359 7360 public: 7361 BuiltinOperatorOverloadBuilder( 7362 Sema &S, ArrayRef<Expr *> Args, 7363 Qualifiers VisibleTypeConversionsQuals, 7364 bool HasArithmeticOrEnumeralCandidateType, 7365 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7366 OverloadCandidateSet &CandidateSet) 7367 : S(S), Args(Args), 7368 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7369 HasArithmeticOrEnumeralCandidateType( 7370 HasArithmeticOrEnumeralCandidateType), 7371 CandidateTypes(CandidateTypes), 7372 CandidateSet(CandidateSet) { 7373 // Validate some of our static helper constants in debug builds. 7374 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7375 "Invalid first promoted integral type"); 7376 assert(getArithmeticType(LastPromotedIntegralType - 1) 7377 == S.Context.UnsignedInt128Ty && 7378 "Invalid last promoted integral type"); 7379 assert(getArithmeticType(FirstPromotedArithmeticType) 7380 == S.Context.FloatTy && 7381 "Invalid first promoted arithmetic type"); 7382 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7383 == S.Context.UnsignedInt128Ty && 7384 "Invalid last promoted arithmetic type"); 7385 } 7386 7387 // C++ [over.built]p3: 7388 // 7389 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7390 // is either volatile or empty, there exist candidate operator 7391 // functions of the form 7392 // 7393 // VQ T& operator++(VQ T&); 7394 // T operator++(VQ T&, int); 7395 // 7396 // C++ [over.built]p4: 7397 // 7398 // For every pair (T, VQ), where T is an arithmetic type other 7399 // than bool, and VQ is either volatile or empty, there exist 7400 // candidate operator functions of the form 7401 // 7402 // VQ T& operator--(VQ T&); 7403 // T operator--(VQ T&, int); 7404 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7405 if (!HasArithmeticOrEnumeralCandidateType) 7406 return; 7407 7408 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7409 Arith < NumArithmeticTypes; ++Arith) { 7410 addPlusPlusMinusMinusStyleOverloads( 7411 getArithmeticType(Arith), 7412 VisibleTypeConversionsQuals.hasVolatile(), 7413 VisibleTypeConversionsQuals.hasRestrict()); 7414 } 7415 } 7416 7417 // C++ [over.built]p5: 7418 // 7419 // For every pair (T, VQ), where T is a cv-qualified or 7420 // cv-unqualified object type, and VQ is either volatile or 7421 // empty, there exist candidate operator functions of the form 7422 // 7423 // T*VQ& operator++(T*VQ&); 7424 // T*VQ& operator--(T*VQ&); 7425 // T* operator++(T*VQ&, int); 7426 // T* operator--(T*VQ&, int); 7427 void addPlusPlusMinusMinusPointerOverloads() { 7428 for (BuiltinCandidateTypeSet::iterator 7429 Ptr = CandidateTypes[0].pointer_begin(), 7430 PtrEnd = CandidateTypes[0].pointer_end(); 7431 Ptr != PtrEnd; ++Ptr) { 7432 // Skip pointer types that aren't pointers to object types. 7433 if (!(*Ptr)->getPointeeType()->isObjectType()) 7434 continue; 7435 7436 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7437 (!(*Ptr).isVolatileQualified() && 7438 VisibleTypeConversionsQuals.hasVolatile()), 7439 (!(*Ptr).isRestrictQualified() && 7440 VisibleTypeConversionsQuals.hasRestrict())); 7441 } 7442 } 7443 7444 // C++ [over.built]p6: 7445 // For every cv-qualified or cv-unqualified object type T, there 7446 // exist candidate operator functions of the form 7447 // 7448 // T& operator*(T*); 7449 // 7450 // C++ [over.built]p7: 7451 // For every function type T that does not have cv-qualifiers or a 7452 // ref-qualifier, there exist candidate operator functions of the form 7453 // T& operator*(T*); 7454 void addUnaryStarPointerOverloads() { 7455 for (BuiltinCandidateTypeSet::iterator 7456 Ptr = CandidateTypes[0].pointer_begin(), 7457 PtrEnd = CandidateTypes[0].pointer_end(); 7458 Ptr != PtrEnd; ++Ptr) { 7459 QualType ParamTy = *Ptr; 7460 QualType PointeeTy = ParamTy->getPointeeType(); 7461 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7462 continue; 7463 7464 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7465 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7466 continue; 7467 7468 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7469 &ParamTy, Args, CandidateSet); 7470 } 7471 } 7472 7473 // C++ [over.built]p9: 7474 // For every promoted arithmetic type T, there exist candidate 7475 // operator functions of the form 7476 // 7477 // T operator+(T); 7478 // T operator-(T); 7479 void addUnaryPlusOrMinusArithmeticOverloads() { 7480 if (!HasArithmeticOrEnumeralCandidateType) 7481 return; 7482 7483 for (unsigned Arith = FirstPromotedArithmeticType; 7484 Arith < LastPromotedArithmeticType; ++Arith) { 7485 QualType ArithTy = getArithmeticType(Arith); 7486 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7487 } 7488 7489 // Extension: We also add these operators for vector types. 7490 for (BuiltinCandidateTypeSet::iterator 7491 Vec = CandidateTypes[0].vector_begin(), 7492 VecEnd = CandidateTypes[0].vector_end(); 7493 Vec != VecEnd; ++Vec) { 7494 QualType VecTy = *Vec; 7495 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7496 } 7497 } 7498 7499 // C++ [over.built]p8: 7500 // For every type T, there exist candidate operator functions of 7501 // the form 7502 // 7503 // T* operator+(T*); 7504 void addUnaryPlusPointerOverloads() { 7505 for (BuiltinCandidateTypeSet::iterator 7506 Ptr = CandidateTypes[0].pointer_begin(), 7507 PtrEnd = CandidateTypes[0].pointer_end(); 7508 Ptr != PtrEnd; ++Ptr) { 7509 QualType ParamTy = *Ptr; 7510 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7511 } 7512 } 7513 7514 // C++ [over.built]p10: 7515 // For every promoted integral type T, there exist candidate 7516 // operator functions of the form 7517 // 7518 // T operator~(T); 7519 void addUnaryTildePromotedIntegralOverloads() { 7520 if (!HasArithmeticOrEnumeralCandidateType) 7521 return; 7522 7523 for (unsigned Int = FirstPromotedIntegralType; 7524 Int < LastPromotedIntegralType; ++Int) { 7525 QualType IntTy = getArithmeticType(Int); 7526 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7527 } 7528 7529 // Extension: We also add this operator for vector types. 7530 for (BuiltinCandidateTypeSet::iterator 7531 Vec = CandidateTypes[0].vector_begin(), 7532 VecEnd = CandidateTypes[0].vector_end(); 7533 Vec != VecEnd; ++Vec) { 7534 QualType VecTy = *Vec; 7535 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7536 } 7537 } 7538 7539 // C++ [over.match.oper]p16: 7540 // For every pointer to member type T, there exist candidate operator 7541 // functions of the form 7542 // 7543 // bool operator==(T,T); 7544 // bool operator!=(T,T); 7545 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7546 /// Set of (canonical) types that we've already handled. 7547 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7548 7549 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7550 for (BuiltinCandidateTypeSet::iterator 7551 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7552 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7553 MemPtr != MemPtrEnd; 7554 ++MemPtr) { 7555 // Don't add the same builtin candidate twice. 7556 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7557 continue; 7558 7559 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7560 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7561 } 7562 } 7563 } 7564 7565 // C++ [over.built]p15: 7566 // 7567 // For every T, where T is an enumeration type, a pointer type, or 7568 // std::nullptr_t, there exist candidate operator functions of the form 7569 // 7570 // bool operator<(T, T); 7571 // bool operator>(T, T); 7572 // bool operator<=(T, T); 7573 // bool operator>=(T, T); 7574 // bool operator==(T, T); 7575 // bool operator!=(T, T); 7576 void addRelationalPointerOrEnumeralOverloads() { 7577 // C++ [over.match.oper]p3: 7578 // [...]the built-in candidates include all of the candidate operator 7579 // functions defined in 13.6 that, compared to the given operator, [...] 7580 // do not have the same parameter-type-list as any non-template non-member 7581 // candidate. 7582 // 7583 // Note that in practice, this only affects enumeration types because there 7584 // aren't any built-in candidates of record type, and a user-defined operator 7585 // must have an operand of record or enumeration type. Also, the only other 7586 // overloaded operator with enumeration arguments, operator=, 7587 // cannot be overloaded for enumeration types, so this is the only place 7588 // where we must suppress candidates like this. 7589 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7590 UserDefinedBinaryOperators; 7591 7592 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7593 if (CandidateTypes[ArgIdx].enumeration_begin() != 7594 CandidateTypes[ArgIdx].enumeration_end()) { 7595 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7596 CEnd = CandidateSet.end(); 7597 C != CEnd; ++C) { 7598 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7599 continue; 7600 7601 if (C->Function->isFunctionTemplateSpecialization()) 7602 continue; 7603 7604 QualType FirstParamType = 7605 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7606 QualType SecondParamType = 7607 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7608 7609 // Skip if either parameter isn't of enumeral type. 7610 if (!FirstParamType->isEnumeralType() || 7611 !SecondParamType->isEnumeralType()) 7612 continue; 7613 7614 // Add this operator to the set of known user-defined operators. 7615 UserDefinedBinaryOperators.insert( 7616 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7617 S.Context.getCanonicalType(SecondParamType))); 7618 } 7619 } 7620 } 7621 7622 /// Set of (canonical) types that we've already handled. 7623 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7624 7625 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7626 for (BuiltinCandidateTypeSet::iterator 7627 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7628 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7629 Ptr != PtrEnd; ++Ptr) { 7630 // Don't add the same builtin candidate twice. 7631 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7632 continue; 7633 7634 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7635 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7636 } 7637 for (BuiltinCandidateTypeSet::iterator 7638 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7639 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7640 Enum != EnumEnd; ++Enum) { 7641 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7642 7643 // Don't add the same builtin candidate twice, or if a user defined 7644 // candidate exists. 7645 if (!AddedTypes.insert(CanonType).second || 7646 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7647 CanonType))) 7648 continue; 7649 7650 QualType ParamTypes[2] = { *Enum, *Enum }; 7651 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7652 } 7653 7654 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7655 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7656 if (AddedTypes.insert(NullPtrTy).second && 7657 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7658 NullPtrTy))) { 7659 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7660 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7661 CandidateSet); 7662 } 7663 } 7664 } 7665 } 7666 7667 // C++ [over.built]p13: 7668 // 7669 // For every cv-qualified or cv-unqualified object type T 7670 // there exist candidate operator functions of the form 7671 // 7672 // T* operator+(T*, ptrdiff_t); 7673 // T& operator[](T*, ptrdiff_t); [BELOW] 7674 // T* operator-(T*, ptrdiff_t); 7675 // T* operator+(ptrdiff_t, T*); 7676 // T& operator[](ptrdiff_t, T*); [BELOW] 7677 // 7678 // C++ [over.built]p14: 7679 // 7680 // For every T, where T is a pointer to object type, there 7681 // exist candidate operator functions of the form 7682 // 7683 // ptrdiff_t operator-(T, T); 7684 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7685 /// Set of (canonical) types that we've already handled. 7686 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7687 7688 for (int Arg = 0; Arg < 2; ++Arg) { 7689 QualType AsymmetricParamTypes[2] = { 7690 S.Context.getPointerDiffType(), 7691 S.Context.getPointerDiffType(), 7692 }; 7693 for (BuiltinCandidateTypeSet::iterator 7694 Ptr = CandidateTypes[Arg].pointer_begin(), 7695 PtrEnd = CandidateTypes[Arg].pointer_end(); 7696 Ptr != PtrEnd; ++Ptr) { 7697 QualType PointeeTy = (*Ptr)->getPointeeType(); 7698 if (!PointeeTy->isObjectType()) 7699 continue; 7700 7701 AsymmetricParamTypes[Arg] = *Ptr; 7702 if (Arg == 0 || Op == OO_Plus) { 7703 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7704 // T* operator+(ptrdiff_t, T*); 7705 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7706 } 7707 if (Op == OO_Minus) { 7708 // ptrdiff_t operator-(T, T); 7709 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7710 continue; 7711 7712 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7713 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7714 Args, CandidateSet); 7715 } 7716 } 7717 } 7718 } 7719 7720 // C++ [over.built]p12: 7721 // 7722 // For every pair of promoted arithmetic types L and R, there 7723 // exist candidate operator functions of the form 7724 // 7725 // LR operator*(L, R); 7726 // LR operator/(L, R); 7727 // LR operator+(L, R); 7728 // LR operator-(L, R); 7729 // bool operator<(L, R); 7730 // bool operator>(L, R); 7731 // bool operator<=(L, R); 7732 // bool operator>=(L, R); 7733 // bool operator==(L, R); 7734 // bool operator!=(L, R); 7735 // 7736 // where LR is the result of the usual arithmetic conversions 7737 // between types L and R. 7738 // 7739 // C++ [over.built]p24: 7740 // 7741 // For every pair of promoted arithmetic types L and R, there exist 7742 // candidate operator functions of the form 7743 // 7744 // LR operator?(bool, L, R); 7745 // 7746 // where LR is the result of the usual arithmetic conversions 7747 // between types L and R. 7748 // Our candidates ignore the first parameter. 7749 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7750 if (!HasArithmeticOrEnumeralCandidateType) 7751 return; 7752 7753 for (unsigned Left = FirstPromotedArithmeticType; 7754 Left < LastPromotedArithmeticType; ++Left) { 7755 for (unsigned Right = FirstPromotedArithmeticType; 7756 Right < LastPromotedArithmeticType; ++Right) { 7757 QualType LandR[2] = { getArithmeticType(Left), 7758 getArithmeticType(Right) }; 7759 QualType Result = 7760 isComparison ? S.Context.BoolTy 7761 : getUsualArithmeticConversions(Left, Right); 7762 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7763 } 7764 } 7765 7766 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7767 // conditional operator for vector types. 7768 for (BuiltinCandidateTypeSet::iterator 7769 Vec1 = CandidateTypes[0].vector_begin(), 7770 Vec1End = CandidateTypes[0].vector_end(); 7771 Vec1 != Vec1End; ++Vec1) { 7772 for (BuiltinCandidateTypeSet::iterator 7773 Vec2 = CandidateTypes[1].vector_begin(), 7774 Vec2End = CandidateTypes[1].vector_end(); 7775 Vec2 != Vec2End; ++Vec2) { 7776 QualType LandR[2] = { *Vec1, *Vec2 }; 7777 QualType Result = S.Context.BoolTy; 7778 if (!isComparison) { 7779 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7780 Result = *Vec1; 7781 else 7782 Result = *Vec2; 7783 } 7784 7785 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7786 } 7787 } 7788 } 7789 7790 // C++ [over.built]p17: 7791 // 7792 // For every pair of promoted integral types L and R, there 7793 // exist candidate operator functions of the form 7794 // 7795 // LR operator%(L, R); 7796 // LR operator&(L, R); 7797 // LR operator^(L, R); 7798 // LR operator|(L, R); 7799 // L operator<<(L, R); 7800 // L operator>>(L, R); 7801 // 7802 // where LR is the result of the usual arithmetic conversions 7803 // between types L and R. 7804 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7805 if (!HasArithmeticOrEnumeralCandidateType) 7806 return; 7807 7808 for (unsigned Left = FirstPromotedIntegralType; 7809 Left < LastPromotedIntegralType; ++Left) { 7810 for (unsigned Right = FirstPromotedIntegralType; 7811 Right < LastPromotedIntegralType; ++Right) { 7812 QualType LandR[2] = { getArithmeticType(Left), 7813 getArithmeticType(Right) }; 7814 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7815 ? LandR[0] 7816 : getUsualArithmeticConversions(Left, Right); 7817 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7818 } 7819 } 7820 } 7821 7822 // C++ [over.built]p20: 7823 // 7824 // For every pair (T, VQ), where T is an enumeration or 7825 // pointer to member type and VQ is either volatile or 7826 // empty, there exist candidate operator functions of the form 7827 // 7828 // VQ T& operator=(VQ T&, T); 7829 void addAssignmentMemberPointerOrEnumeralOverloads() { 7830 /// Set of (canonical) types that we've already handled. 7831 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7832 7833 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7834 for (BuiltinCandidateTypeSet::iterator 7835 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7836 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7837 Enum != EnumEnd; ++Enum) { 7838 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7839 continue; 7840 7841 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7842 } 7843 7844 for (BuiltinCandidateTypeSet::iterator 7845 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7846 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7847 MemPtr != MemPtrEnd; ++MemPtr) { 7848 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7849 continue; 7850 7851 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7852 } 7853 } 7854 } 7855 7856 // C++ [over.built]p19: 7857 // 7858 // For every pair (T, VQ), where T is any type and VQ is either 7859 // volatile or empty, there exist candidate operator functions 7860 // of the form 7861 // 7862 // T*VQ& operator=(T*VQ&, T*); 7863 // 7864 // C++ [over.built]p21: 7865 // 7866 // For every pair (T, VQ), where T is a cv-qualified or 7867 // cv-unqualified object type and VQ is either volatile or 7868 // empty, there exist candidate operator functions of the form 7869 // 7870 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7871 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7872 void addAssignmentPointerOverloads(bool isEqualOp) { 7873 /// Set of (canonical) types that we've already handled. 7874 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7875 7876 for (BuiltinCandidateTypeSet::iterator 7877 Ptr = CandidateTypes[0].pointer_begin(), 7878 PtrEnd = CandidateTypes[0].pointer_end(); 7879 Ptr != PtrEnd; ++Ptr) { 7880 // If this is operator=, keep track of the builtin candidates we added. 7881 if (isEqualOp) 7882 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7883 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7884 continue; 7885 7886 // non-volatile version 7887 QualType ParamTypes[2] = { 7888 S.Context.getLValueReferenceType(*Ptr), 7889 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7890 }; 7891 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7892 /*IsAssigmentOperator=*/ isEqualOp); 7893 7894 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7895 VisibleTypeConversionsQuals.hasVolatile(); 7896 if (NeedVolatile) { 7897 // volatile version 7898 ParamTypes[0] = 7899 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7900 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7901 /*IsAssigmentOperator=*/isEqualOp); 7902 } 7903 7904 if (!(*Ptr).isRestrictQualified() && 7905 VisibleTypeConversionsQuals.hasRestrict()) { 7906 // restrict version 7907 ParamTypes[0] 7908 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7909 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7910 /*IsAssigmentOperator=*/isEqualOp); 7911 7912 if (NeedVolatile) { 7913 // volatile restrict version 7914 ParamTypes[0] 7915 = S.Context.getLValueReferenceType( 7916 S.Context.getCVRQualifiedType(*Ptr, 7917 (Qualifiers::Volatile | 7918 Qualifiers::Restrict))); 7919 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7920 /*IsAssigmentOperator=*/isEqualOp); 7921 } 7922 } 7923 } 7924 7925 if (isEqualOp) { 7926 for (BuiltinCandidateTypeSet::iterator 7927 Ptr = CandidateTypes[1].pointer_begin(), 7928 PtrEnd = CandidateTypes[1].pointer_end(); 7929 Ptr != PtrEnd; ++Ptr) { 7930 // Make sure we don't add the same candidate twice. 7931 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7932 continue; 7933 7934 QualType ParamTypes[2] = { 7935 S.Context.getLValueReferenceType(*Ptr), 7936 *Ptr, 7937 }; 7938 7939 // non-volatile version 7940 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7941 /*IsAssigmentOperator=*/true); 7942 7943 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7944 VisibleTypeConversionsQuals.hasVolatile(); 7945 if (NeedVolatile) { 7946 // volatile version 7947 ParamTypes[0] = 7948 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7949 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7950 /*IsAssigmentOperator=*/true); 7951 } 7952 7953 if (!(*Ptr).isRestrictQualified() && 7954 VisibleTypeConversionsQuals.hasRestrict()) { 7955 // restrict version 7956 ParamTypes[0] 7957 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7958 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7959 /*IsAssigmentOperator=*/true); 7960 7961 if (NeedVolatile) { 7962 // volatile restrict version 7963 ParamTypes[0] 7964 = S.Context.getLValueReferenceType( 7965 S.Context.getCVRQualifiedType(*Ptr, 7966 (Qualifiers::Volatile | 7967 Qualifiers::Restrict))); 7968 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7969 /*IsAssigmentOperator=*/true); 7970 } 7971 } 7972 } 7973 } 7974 } 7975 7976 // C++ [over.built]p18: 7977 // 7978 // For every triple (L, VQ, R), where L is an arithmetic type, 7979 // VQ is either volatile or empty, and R is a promoted 7980 // arithmetic type, there exist candidate operator functions of 7981 // the form 7982 // 7983 // VQ L& operator=(VQ L&, R); 7984 // VQ L& operator*=(VQ L&, R); 7985 // VQ L& operator/=(VQ L&, R); 7986 // VQ L& operator+=(VQ L&, R); 7987 // VQ L& operator-=(VQ L&, R); 7988 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7989 if (!HasArithmeticOrEnumeralCandidateType) 7990 return; 7991 7992 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7993 for (unsigned Right = FirstPromotedArithmeticType; 7994 Right < LastPromotedArithmeticType; ++Right) { 7995 QualType ParamTypes[2]; 7996 ParamTypes[1] = getArithmeticType(Right); 7997 7998 // Add this built-in operator as a candidate (VQ is empty). 7999 ParamTypes[0] = 8000 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8001 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8002 /*IsAssigmentOperator=*/isEqualOp); 8003 8004 // Add this built-in operator as a candidate (VQ is 'volatile'). 8005 if (VisibleTypeConversionsQuals.hasVolatile()) { 8006 ParamTypes[0] = 8007 S.Context.getVolatileType(getArithmeticType(Left)); 8008 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8009 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8010 /*IsAssigmentOperator=*/isEqualOp); 8011 } 8012 } 8013 } 8014 8015 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8016 for (BuiltinCandidateTypeSet::iterator 8017 Vec1 = CandidateTypes[0].vector_begin(), 8018 Vec1End = CandidateTypes[0].vector_end(); 8019 Vec1 != Vec1End; ++Vec1) { 8020 for (BuiltinCandidateTypeSet::iterator 8021 Vec2 = CandidateTypes[1].vector_begin(), 8022 Vec2End = CandidateTypes[1].vector_end(); 8023 Vec2 != Vec2End; ++Vec2) { 8024 QualType ParamTypes[2]; 8025 ParamTypes[1] = *Vec2; 8026 // Add this built-in operator as a candidate (VQ is empty). 8027 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8028 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8029 /*IsAssigmentOperator=*/isEqualOp); 8030 8031 // Add this built-in operator as a candidate (VQ is 'volatile'). 8032 if (VisibleTypeConversionsQuals.hasVolatile()) { 8033 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8034 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8035 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8036 /*IsAssigmentOperator=*/isEqualOp); 8037 } 8038 } 8039 } 8040 } 8041 8042 // C++ [over.built]p22: 8043 // 8044 // For every triple (L, VQ, R), where L is an integral type, VQ 8045 // is either volatile or empty, and R is a promoted integral 8046 // type, there exist candidate operator functions of the form 8047 // 8048 // VQ L& operator%=(VQ L&, R); 8049 // VQ L& operator<<=(VQ L&, R); 8050 // VQ L& operator>>=(VQ L&, R); 8051 // VQ L& operator&=(VQ L&, R); 8052 // VQ L& operator^=(VQ L&, R); 8053 // VQ L& operator|=(VQ L&, R); 8054 void addAssignmentIntegralOverloads() { 8055 if (!HasArithmeticOrEnumeralCandidateType) 8056 return; 8057 8058 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8059 for (unsigned Right = FirstPromotedIntegralType; 8060 Right < LastPromotedIntegralType; ++Right) { 8061 QualType ParamTypes[2]; 8062 ParamTypes[1] = getArithmeticType(Right); 8063 8064 // Add this built-in operator as a candidate (VQ is empty). 8065 ParamTypes[0] = 8066 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8067 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8068 if (VisibleTypeConversionsQuals.hasVolatile()) { 8069 // Add this built-in operator as a candidate (VQ is 'volatile'). 8070 ParamTypes[0] = getArithmeticType(Left); 8071 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8072 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8073 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8074 } 8075 } 8076 } 8077 } 8078 8079 // C++ [over.operator]p23: 8080 // 8081 // There also exist candidate operator functions of the form 8082 // 8083 // bool operator!(bool); 8084 // bool operator&&(bool, bool); 8085 // bool operator||(bool, bool); 8086 void addExclaimOverload() { 8087 QualType ParamTy = S.Context.BoolTy; 8088 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8089 /*IsAssignmentOperator=*/false, 8090 /*NumContextualBoolArguments=*/1); 8091 } 8092 void addAmpAmpOrPipePipeOverload() { 8093 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8094 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8095 /*IsAssignmentOperator=*/false, 8096 /*NumContextualBoolArguments=*/2); 8097 } 8098 8099 // C++ [over.built]p13: 8100 // 8101 // For every cv-qualified or cv-unqualified object type T there 8102 // exist candidate operator functions of the form 8103 // 8104 // T* operator+(T*, ptrdiff_t); [ABOVE] 8105 // T& operator[](T*, ptrdiff_t); 8106 // T* operator-(T*, ptrdiff_t); [ABOVE] 8107 // T* operator+(ptrdiff_t, T*); [ABOVE] 8108 // T& operator[](ptrdiff_t, T*); 8109 void addSubscriptOverloads() { 8110 for (BuiltinCandidateTypeSet::iterator 8111 Ptr = CandidateTypes[0].pointer_begin(), 8112 PtrEnd = CandidateTypes[0].pointer_end(); 8113 Ptr != PtrEnd; ++Ptr) { 8114 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8115 QualType PointeeType = (*Ptr)->getPointeeType(); 8116 if (!PointeeType->isObjectType()) 8117 continue; 8118 8119 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8120 8121 // T& operator[](T*, ptrdiff_t) 8122 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8123 } 8124 8125 for (BuiltinCandidateTypeSet::iterator 8126 Ptr = CandidateTypes[1].pointer_begin(), 8127 PtrEnd = CandidateTypes[1].pointer_end(); 8128 Ptr != PtrEnd; ++Ptr) { 8129 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8130 QualType PointeeType = (*Ptr)->getPointeeType(); 8131 if (!PointeeType->isObjectType()) 8132 continue; 8133 8134 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8135 8136 // T& operator[](ptrdiff_t, T*) 8137 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8138 } 8139 } 8140 8141 // C++ [over.built]p11: 8142 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8143 // C1 is the same type as C2 or is a derived class of C2, T is an object 8144 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8145 // there exist candidate operator functions of the form 8146 // 8147 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8148 // 8149 // where CV12 is the union of CV1 and CV2. 8150 void addArrowStarOverloads() { 8151 for (BuiltinCandidateTypeSet::iterator 8152 Ptr = CandidateTypes[0].pointer_begin(), 8153 PtrEnd = CandidateTypes[0].pointer_end(); 8154 Ptr != PtrEnd; ++Ptr) { 8155 QualType C1Ty = (*Ptr); 8156 QualType C1; 8157 QualifierCollector Q1; 8158 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8159 if (!isa<RecordType>(C1)) 8160 continue; 8161 // heuristic to reduce number of builtin candidates in the set. 8162 // Add volatile/restrict version only if there are conversions to a 8163 // volatile/restrict type. 8164 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8165 continue; 8166 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8167 continue; 8168 for (BuiltinCandidateTypeSet::iterator 8169 MemPtr = CandidateTypes[1].member_pointer_begin(), 8170 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8171 MemPtr != MemPtrEnd; ++MemPtr) { 8172 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8173 QualType C2 = QualType(mptr->getClass(), 0); 8174 C2 = C2.getUnqualifiedType(); 8175 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8176 break; 8177 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8178 // build CV12 T& 8179 QualType T = mptr->getPointeeType(); 8180 if (!VisibleTypeConversionsQuals.hasVolatile() && 8181 T.isVolatileQualified()) 8182 continue; 8183 if (!VisibleTypeConversionsQuals.hasRestrict() && 8184 T.isRestrictQualified()) 8185 continue; 8186 T = Q1.apply(S.Context, T); 8187 QualType ResultTy = S.Context.getLValueReferenceType(T); 8188 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8189 } 8190 } 8191 } 8192 8193 // Note that we don't consider the first argument, since it has been 8194 // contextually converted to bool long ago. The candidates below are 8195 // therefore added as binary. 8196 // 8197 // C++ [over.built]p25: 8198 // For every type T, where T is a pointer, pointer-to-member, or scoped 8199 // enumeration type, there exist candidate operator functions of the form 8200 // 8201 // T operator?(bool, T, T); 8202 // 8203 void addConditionalOperatorOverloads() { 8204 /// Set of (canonical) types that we've already handled. 8205 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8206 8207 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8208 for (BuiltinCandidateTypeSet::iterator 8209 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8210 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8211 Ptr != PtrEnd; ++Ptr) { 8212 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8213 continue; 8214 8215 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8216 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8217 } 8218 8219 for (BuiltinCandidateTypeSet::iterator 8220 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8221 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8222 MemPtr != MemPtrEnd; ++MemPtr) { 8223 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8224 continue; 8225 8226 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8227 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8228 } 8229 8230 if (S.getLangOpts().CPlusPlus11) { 8231 for (BuiltinCandidateTypeSet::iterator 8232 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8233 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8234 Enum != EnumEnd; ++Enum) { 8235 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8236 continue; 8237 8238 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8239 continue; 8240 8241 QualType ParamTypes[2] = { *Enum, *Enum }; 8242 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8243 } 8244 } 8245 } 8246 } 8247 }; 8248 8249 } // end anonymous namespace 8250 8251 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8252 /// operator overloads to the candidate set (C++ [over.built]), based 8253 /// on the operator @p Op and the arguments given. For example, if the 8254 /// operator is a binary '+', this routine might add "int 8255 /// operator+(int, int)" to cover integer addition. 8256 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8257 SourceLocation OpLoc, 8258 ArrayRef<Expr *> Args, 8259 OverloadCandidateSet &CandidateSet) { 8260 // Find all of the types that the arguments can convert to, but only 8261 // if the operator we're looking at has built-in operator candidates 8262 // that make use of these types. Also record whether we encounter non-record 8263 // candidate types or either arithmetic or enumeral candidate types. 8264 Qualifiers VisibleTypeConversionsQuals; 8265 VisibleTypeConversionsQuals.addConst(); 8266 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8267 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8268 8269 bool HasNonRecordCandidateType = false; 8270 bool HasArithmeticOrEnumeralCandidateType = false; 8271 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8272 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8273 CandidateTypes.emplace_back(*this); 8274 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8275 OpLoc, 8276 true, 8277 (Op == OO_Exclaim || 8278 Op == OO_AmpAmp || 8279 Op == OO_PipePipe), 8280 VisibleTypeConversionsQuals); 8281 HasNonRecordCandidateType = HasNonRecordCandidateType || 8282 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8283 HasArithmeticOrEnumeralCandidateType = 8284 HasArithmeticOrEnumeralCandidateType || 8285 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8286 } 8287 8288 // Exit early when no non-record types have been added to the candidate set 8289 // for any of the arguments to the operator. 8290 // 8291 // We can't exit early for !, ||, or &&, since there we have always have 8292 // 'bool' overloads. 8293 if (!HasNonRecordCandidateType && 8294 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8295 return; 8296 8297 // Setup an object to manage the common state for building overloads. 8298 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8299 VisibleTypeConversionsQuals, 8300 HasArithmeticOrEnumeralCandidateType, 8301 CandidateTypes, CandidateSet); 8302 8303 // Dispatch over the operation to add in only those overloads which apply. 8304 switch (Op) { 8305 case OO_None: 8306 case NUM_OVERLOADED_OPERATORS: 8307 llvm_unreachable("Expected an overloaded operator"); 8308 8309 case OO_New: 8310 case OO_Delete: 8311 case OO_Array_New: 8312 case OO_Array_Delete: 8313 case OO_Call: 8314 llvm_unreachable( 8315 "Special operators don't use AddBuiltinOperatorCandidates"); 8316 8317 case OO_Comma: 8318 case OO_Arrow: 8319 case OO_Coawait: 8320 // C++ [over.match.oper]p3: 8321 // -- For the operator ',', the unary operator '&', the 8322 // operator '->', or the operator 'co_await', the 8323 // built-in candidates set is empty. 8324 break; 8325 8326 case OO_Plus: // '+' is either unary or binary 8327 if (Args.size() == 1) 8328 OpBuilder.addUnaryPlusPointerOverloads(); 8329 // Fall through. 8330 8331 case OO_Minus: // '-' is either unary or binary 8332 if (Args.size() == 1) { 8333 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8334 } else { 8335 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8336 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8337 } 8338 break; 8339 8340 case OO_Star: // '*' is either unary or binary 8341 if (Args.size() == 1) 8342 OpBuilder.addUnaryStarPointerOverloads(); 8343 else 8344 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8345 break; 8346 8347 case OO_Slash: 8348 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8349 break; 8350 8351 case OO_PlusPlus: 8352 case OO_MinusMinus: 8353 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8354 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8355 break; 8356 8357 case OO_EqualEqual: 8358 case OO_ExclaimEqual: 8359 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8360 // Fall through. 8361 8362 case OO_Less: 8363 case OO_Greater: 8364 case OO_LessEqual: 8365 case OO_GreaterEqual: 8366 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8367 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8368 break; 8369 8370 case OO_Percent: 8371 case OO_Caret: 8372 case OO_Pipe: 8373 case OO_LessLess: 8374 case OO_GreaterGreater: 8375 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8376 break; 8377 8378 case OO_Amp: // '&' is either unary or binary 8379 if (Args.size() == 1) 8380 // C++ [over.match.oper]p3: 8381 // -- For the operator ',', the unary operator '&', or the 8382 // operator '->', the built-in candidates set is empty. 8383 break; 8384 8385 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8386 break; 8387 8388 case OO_Tilde: 8389 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8390 break; 8391 8392 case OO_Equal: 8393 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8394 // Fall through. 8395 8396 case OO_PlusEqual: 8397 case OO_MinusEqual: 8398 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8399 // Fall through. 8400 8401 case OO_StarEqual: 8402 case OO_SlashEqual: 8403 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8404 break; 8405 8406 case OO_PercentEqual: 8407 case OO_LessLessEqual: 8408 case OO_GreaterGreaterEqual: 8409 case OO_AmpEqual: 8410 case OO_CaretEqual: 8411 case OO_PipeEqual: 8412 OpBuilder.addAssignmentIntegralOverloads(); 8413 break; 8414 8415 case OO_Exclaim: 8416 OpBuilder.addExclaimOverload(); 8417 break; 8418 8419 case OO_AmpAmp: 8420 case OO_PipePipe: 8421 OpBuilder.addAmpAmpOrPipePipeOverload(); 8422 break; 8423 8424 case OO_Subscript: 8425 OpBuilder.addSubscriptOverloads(); 8426 break; 8427 8428 case OO_ArrowStar: 8429 OpBuilder.addArrowStarOverloads(); 8430 break; 8431 8432 case OO_Conditional: 8433 OpBuilder.addConditionalOperatorOverloads(); 8434 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8435 break; 8436 } 8437 } 8438 8439 /// \brief Add function candidates found via argument-dependent lookup 8440 /// to the set of overloading candidates. 8441 /// 8442 /// This routine performs argument-dependent name lookup based on the 8443 /// given function name (which may also be an operator name) and adds 8444 /// all of the overload candidates found by ADL to the overload 8445 /// candidate set (C++ [basic.lookup.argdep]). 8446 void 8447 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8448 SourceLocation Loc, 8449 ArrayRef<Expr *> Args, 8450 TemplateArgumentListInfo *ExplicitTemplateArgs, 8451 OverloadCandidateSet& CandidateSet, 8452 bool PartialOverloading) { 8453 ADLResult Fns; 8454 8455 // FIXME: This approach for uniquing ADL results (and removing 8456 // redundant candidates from the set) relies on pointer-equality, 8457 // which means we need to key off the canonical decl. However, 8458 // always going back to the canonical decl might not get us the 8459 // right set of default arguments. What default arguments are 8460 // we supposed to consider on ADL candidates, anyway? 8461 8462 // FIXME: Pass in the explicit template arguments? 8463 ArgumentDependentLookup(Name, Loc, Args, Fns); 8464 8465 // Erase all of the candidates we already knew about. 8466 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8467 CandEnd = CandidateSet.end(); 8468 Cand != CandEnd; ++Cand) 8469 if (Cand->Function) { 8470 Fns.erase(Cand->Function); 8471 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8472 Fns.erase(FunTmpl); 8473 } 8474 8475 // For each of the ADL candidates we found, add it to the overload 8476 // set. 8477 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8478 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8479 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8480 if (ExplicitTemplateArgs) 8481 continue; 8482 8483 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8484 PartialOverloading); 8485 } else 8486 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8487 FoundDecl, ExplicitTemplateArgs, 8488 Args, CandidateSet, PartialOverloading); 8489 } 8490 } 8491 8492 namespace { 8493 enum class Comparison { Equal, Better, Worse }; 8494 } 8495 8496 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8497 /// overload resolution. 8498 /// 8499 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8500 /// Cand1's first N enable_if attributes have precisely the same conditions as 8501 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8502 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8503 /// 8504 /// Note that you can have a pair of candidates such that Cand1's enable_if 8505 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8506 /// worse than Cand1's. 8507 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8508 const FunctionDecl *Cand2) { 8509 // Common case: One (or both) decls don't have enable_if attrs. 8510 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8511 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8512 if (!Cand1Attr || !Cand2Attr) { 8513 if (Cand1Attr == Cand2Attr) 8514 return Comparison::Equal; 8515 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8516 } 8517 8518 // FIXME: The next several lines are just 8519 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8520 // instead of reverse order which is how they're stored in the AST. 8521 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8522 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8523 8524 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8525 // has fewer enable_if attributes than Cand2. 8526 if (Cand1Attrs.size() < Cand2Attrs.size()) 8527 return Comparison::Worse; 8528 8529 auto Cand1I = Cand1Attrs.begin(); 8530 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8531 for (auto &Cand2A : Cand2Attrs) { 8532 Cand1ID.clear(); 8533 Cand2ID.clear(); 8534 8535 auto &Cand1A = *Cand1I++; 8536 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8537 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8538 if (Cand1ID != Cand2ID) 8539 return Comparison::Worse; 8540 } 8541 8542 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8543 } 8544 8545 /// isBetterOverloadCandidate - Determines whether the first overload 8546 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8547 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8548 const OverloadCandidate &Cand2, 8549 SourceLocation Loc, 8550 bool UserDefinedConversion) { 8551 // Define viable functions to be better candidates than non-viable 8552 // functions. 8553 if (!Cand2.Viable) 8554 return Cand1.Viable; 8555 else if (!Cand1.Viable) 8556 return false; 8557 8558 // C++ [over.match.best]p1: 8559 // 8560 // -- if F is a static member function, ICS1(F) is defined such 8561 // that ICS1(F) is neither better nor worse than ICS1(G) for 8562 // any function G, and, symmetrically, ICS1(G) is neither 8563 // better nor worse than ICS1(F). 8564 unsigned StartArg = 0; 8565 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8566 StartArg = 1; 8567 8568 // C++ [over.match.best]p1: 8569 // A viable function F1 is defined to be a better function than another 8570 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8571 // conversion sequence than ICSi(F2), and then... 8572 unsigned NumArgs = Cand1.NumConversions; 8573 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8574 bool HasBetterConversion = false; 8575 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8576 switch (CompareImplicitConversionSequences(S, Loc, 8577 Cand1.Conversions[ArgIdx], 8578 Cand2.Conversions[ArgIdx])) { 8579 case ImplicitConversionSequence::Better: 8580 // Cand1 has a better conversion sequence. 8581 HasBetterConversion = true; 8582 break; 8583 8584 case ImplicitConversionSequence::Worse: 8585 // Cand1 can't be better than Cand2. 8586 return false; 8587 8588 case ImplicitConversionSequence::Indistinguishable: 8589 // Do nothing. 8590 break; 8591 } 8592 } 8593 8594 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8595 // ICSj(F2), or, if not that, 8596 if (HasBetterConversion) 8597 return true; 8598 8599 // -- the context is an initialization by user-defined conversion 8600 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8601 // from the return type of F1 to the destination type (i.e., 8602 // the type of the entity being initialized) is a better 8603 // conversion sequence than the standard conversion sequence 8604 // from the return type of F2 to the destination type. 8605 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8606 isa<CXXConversionDecl>(Cand1.Function) && 8607 isa<CXXConversionDecl>(Cand2.Function)) { 8608 // First check whether we prefer one of the conversion functions over the 8609 // other. This only distinguishes the results in non-standard, extension 8610 // cases such as the conversion from a lambda closure type to a function 8611 // pointer or block. 8612 ImplicitConversionSequence::CompareKind Result = 8613 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8614 if (Result == ImplicitConversionSequence::Indistinguishable) 8615 Result = CompareStandardConversionSequences(S, Loc, 8616 Cand1.FinalConversion, 8617 Cand2.FinalConversion); 8618 8619 if (Result != ImplicitConversionSequence::Indistinguishable) 8620 return Result == ImplicitConversionSequence::Better; 8621 8622 // FIXME: Compare kind of reference binding if conversion functions 8623 // convert to a reference type used in direct reference binding, per 8624 // C++14 [over.match.best]p1 section 2 bullet 3. 8625 } 8626 8627 // -- F1 is a non-template function and F2 is a function template 8628 // specialization, or, if not that, 8629 bool Cand1IsSpecialization = Cand1.Function && 8630 Cand1.Function->getPrimaryTemplate(); 8631 bool Cand2IsSpecialization = Cand2.Function && 8632 Cand2.Function->getPrimaryTemplate(); 8633 if (Cand1IsSpecialization != Cand2IsSpecialization) 8634 return Cand2IsSpecialization; 8635 8636 // -- F1 and F2 are function template specializations, and the function 8637 // template for F1 is more specialized than the template for F2 8638 // according to the partial ordering rules described in 14.5.5.2, or, 8639 // if not that, 8640 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8641 if (FunctionTemplateDecl *BetterTemplate 8642 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8643 Cand2.Function->getPrimaryTemplate(), 8644 Loc, 8645 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8646 : TPOC_Call, 8647 Cand1.ExplicitCallArguments, 8648 Cand2.ExplicitCallArguments)) 8649 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8650 } 8651 8652 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 8653 // A derived-class constructor beats an (inherited) base class constructor. 8654 bool Cand1IsInherited = 8655 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 8656 bool Cand2IsInherited = 8657 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 8658 if (Cand1IsInherited != Cand2IsInherited) 8659 return Cand2IsInherited; 8660 else if (Cand1IsInherited) { 8661 assert(Cand2IsInherited); 8662 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 8663 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 8664 if (Cand1Class->isDerivedFrom(Cand2Class)) 8665 return true; 8666 if (Cand2Class->isDerivedFrom(Cand1Class)) 8667 return false; 8668 // Inherited from sibling base classes: still ambiguous. 8669 } 8670 8671 // Check for enable_if value-based overload resolution. 8672 if (Cand1.Function && Cand2.Function) { 8673 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8674 if (Cmp != Comparison::Equal) 8675 return Cmp == Comparison::Better; 8676 } 8677 8678 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8679 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8680 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8681 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8682 } 8683 8684 bool HasPS1 = Cand1.Function != nullptr && 8685 functionHasPassObjectSizeParams(Cand1.Function); 8686 bool HasPS2 = Cand2.Function != nullptr && 8687 functionHasPassObjectSizeParams(Cand2.Function); 8688 return HasPS1 != HasPS2 && HasPS1; 8689 } 8690 8691 /// Determine whether two declarations are "equivalent" for the purposes of 8692 /// name lookup and overload resolution. This applies when the same internal/no 8693 /// linkage entity is defined by two modules (probably by textually including 8694 /// the same header). In such a case, we don't consider the declarations to 8695 /// declare the same entity, but we also don't want lookups with both 8696 /// declarations visible to be ambiguous in some cases (this happens when using 8697 /// a modularized libstdc++). 8698 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8699 const NamedDecl *B) { 8700 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8701 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8702 if (!VA || !VB) 8703 return false; 8704 8705 // The declarations must be declaring the same name as an internal linkage 8706 // entity in different modules. 8707 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8708 VB->getDeclContext()->getRedeclContext()) || 8709 getOwningModule(const_cast<ValueDecl *>(VA)) == 8710 getOwningModule(const_cast<ValueDecl *>(VB)) || 8711 VA->isExternallyVisible() || VB->isExternallyVisible()) 8712 return false; 8713 8714 // Check that the declarations appear to be equivalent. 8715 // 8716 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8717 // For constants and functions, we should check the initializer or body is 8718 // the same. For non-constant variables, we shouldn't allow it at all. 8719 if (Context.hasSameType(VA->getType(), VB->getType())) 8720 return true; 8721 8722 // Enum constants within unnamed enumerations will have different types, but 8723 // may still be similar enough to be interchangeable for our purposes. 8724 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8725 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8726 // Only handle anonymous enums. If the enumerations were named and 8727 // equivalent, they would have been merged to the same type. 8728 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8729 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8730 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8731 !Context.hasSameType(EnumA->getIntegerType(), 8732 EnumB->getIntegerType())) 8733 return false; 8734 // Allow this only if the value is the same for both enumerators. 8735 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8736 } 8737 } 8738 8739 // Nothing else is sufficiently similar. 8740 return false; 8741 } 8742 8743 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8744 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8745 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8746 8747 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8748 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8749 << !M << (M ? M->getFullModuleName() : ""); 8750 8751 for (auto *E : Equiv) { 8752 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8753 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8754 << !M << (M ? M->getFullModuleName() : ""); 8755 } 8756 } 8757 8758 /// \brief Computes the best viable function (C++ 13.3.3) 8759 /// within an overload candidate set. 8760 /// 8761 /// \param Loc The location of the function name (or operator symbol) for 8762 /// which overload resolution occurs. 8763 /// 8764 /// \param Best If overload resolution was successful or found a deleted 8765 /// function, \p Best points to the candidate function found. 8766 /// 8767 /// \returns The result of overload resolution. 8768 OverloadingResult 8769 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8770 iterator &Best, 8771 bool UserDefinedConversion) { 8772 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8773 std::transform(begin(), end(), std::back_inserter(Candidates), 8774 [](OverloadCandidate &Cand) { return &Cand; }); 8775 8776 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 8777 // are accepted by both clang and NVCC. However, during a particular 8778 // compilation mode only one call variant is viable. We need to 8779 // exclude non-viable overload candidates from consideration based 8780 // only on their host/device attributes. Specifically, if one 8781 // candidate call is WrongSide and the other is SameSide, we ignore 8782 // the WrongSide candidate. 8783 if (S.getLangOpts().CUDA) { 8784 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8785 bool ContainsSameSideCandidate = 8786 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8787 return Cand->Function && 8788 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8789 Sema::CFP_SameSide; 8790 }); 8791 if (ContainsSameSideCandidate) { 8792 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8793 return Cand->Function && 8794 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8795 Sema::CFP_WrongSide; 8796 }; 8797 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8798 IsWrongSideCandidate), 8799 Candidates.end()); 8800 } 8801 } 8802 8803 // Find the best viable function. 8804 Best = end(); 8805 for (auto *Cand : Candidates) 8806 if (Cand->Viable) 8807 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8808 UserDefinedConversion)) 8809 Best = Cand; 8810 8811 // If we didn't find any viable functions, abort. 8812 if (Best == end()) 8813 return OR_No_Viable_Function; 8814 8815 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8816 8817 // Make sure that this function is better than every other viable 8818 // function. If not, we have an ambiguity. 8819 for (auto *Cand : Candidates) { 8820 if (Cand->Viable && 8821 Cand != Best && 8822 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8823 UserDefinedConversion)) { 8824 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8825 Cand->Function)) { 8826 EquivalentCands.push_back(Cand->Function); 8827 continue; 8828 } 8829 8830 Best = end(); 8831 return OR_Ambiguous; 8832 } 8833 } 8834 8835 // Best is the best viable function. 8836 if (Best->Function && 8837 (Best->Function->isDeleted() || 8838 S.isFunctionConsideredUnavailable(Best->Function))) 8839 return OR_Deleted; 8840 8841 if (!EquivalentCands.empty()) 8842 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8843 EquivalentCands); 8844 8845 return OR_Success; 8846 } 8847 8848 namespace { 8849 8850 enum OverloadCandidateKind { 8851 oc_function, 8852 oc_method, 8853 oc_constructor, 8854 oc_function_template, 8855 oc_method_template, 8856 oc_constructor_template, 8857 oc_implicit_default_constructor, 8858 oc_implicit_copy_constructor, 8859 oc_implicit_move_constructor, 8860 oc_implicit_copy_assignment, 8861 oc_implicit_move_assignment, 8862 oc_inherited_constructor, 8863 oc_inherited_constructor_template 8864 }; 8865 8866 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8867 NamedDecl *Found, 8868 FunctionDecl *Fn, 8869 std::string &Description) { 8870 bool isTemplate = false; 8871 8872 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8873 isTemplate = true; 8874 Description = S.getTemplateArgumentBindingsText( 8875 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8876 } 8877 8878 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8879 if (!Ctor->isImplicit()) { 8880 if (isa<ConstructorUsingShadowDecl>(Found)) 8881 return isTemplate ? oc_inherited_constructor_template 8882 : oc_inherited_constructor; 8883 else 8884 return isTemplate ? oc_constructor_template : oc_constructor; 8885 } 8886 8887 if (Ctor->isDefaultConstructor()) 8888 return oc_implicit_default_constructor; 8889 8890 if (Ctor->isMoveConstructor()) 8891 return oc_implicit_move_constructor; 8892 8893 assert(Ctor->isCopyConstructor() && 8894 "unexpected sort of implicit constructor"); 8895 return oc_implicit_copy_constructor; 8896 } 8897 8898 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8899 // This actually gets spelled 'candidate function' for now, but 8900 // it doesn't hurt to split it out. 8901 if (!Meth->isImplicit()) 8902 return isTemplate ? oc_method_template : oc_method; 8903 8904 if (Meth->isMoveAssignmentOperator()) 8905 return oc_implicit_move_assignment; 8906 8907 if (Meth->isCopyAssignmentOperator()) 8908 return oc_implicit_copy_assignment; 8909 8910 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8911 return oc_method; 8912 } 8913 8914 return isTemplate ? oc_function_template : oc_function; 8915 } 8916 8917 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 8918 // FIXME: It'd be nice to only emit a note once per using-decl per overload 8919 // set. 8920 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 8921 S.Diag(FoundDecl->getLocation(), 8922 diag::note_ovl_candidate_inherited_constructor) 8923 << Shadow->getNominatedBaseClass(); 8924 } 8925 8926 } // end anonymous namespace 8927 8928 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8929 const FunctionDecl *FD) { 8930 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8931 bool AlwaysTrue; 8932 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8933 return false; 8934 if (!AlwaysTrue) 8935 return false; 8936 } 8937 return true; 8938 } 8939 8940 /// \brief Returns true if we can take the address of the function. 8941 /// 8942 /// \param Complain - If true, we'll emit a diagnostic 8943 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8944 /// we in overload resolution? 8945 /// \param Loc - The location of the statement we're complaining about. Ignored 8946 /// if we're not complaining, or if we're in overload resolution. 8947 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8948 bool Complain, 8949 bool InOverloadResolution, 8950 SourceLocation Loc) { 8951 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8952 if (Complain) { 8953 if (InOverloadResolution) 8954 S.Diag(FD->getLocStart(), 8955 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8956 else 8957 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8958 } 8959 return false; 8960 } 8961 8962 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 8963 return P->hasAttr<PassObjectSizeAttr>(); 8964 }); 8965 if (I == FD->param_end()) 8966 return true; 8967 8968 if (Complain) { 8969 // Add one to ParamNo because it's user-facing 8970 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8971 if (InOverloadResolution) 8972 S.Diag(FD->getLocation(), 8973 diag::note_ovl_candidate_has_pass_object_size_params) 8974 << ParamNo; 8975 else 8976 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8977 << FD << ParamNo; 8978 } 8979 return false; 8980 } 8981 8982 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8983 const FunctionDecl *FD) { 8984 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8985 /*InOverloadResolution=*/true, 8986 /*Loc=*/SourceLocation()); 8987 } 8988 8989 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8990 bool Complain, 8991 SourceLocation Loc) { 8992 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8993 /*InOverloadResolution=*/false, 8994 Loc); 8995 } 8996 8997 // Notes the location of an overload candidate. 8998 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 8999 QualType DestType, bool TakingAddress) { 9000 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9001 return; 9002 9003 std::string FnDesc; 9004 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9005 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9006 << (unsigned) K << FnDesc; 9007 9008 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9009 Diag(Fn->getLocation(), PD); 9010 MaybeEmitInheritedConstructorNote(*this, Found); 9011 } 9012 9013 // Notes the location of all overload candidates designated through 9014 // OverloadedExpr 9015 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9016 bool TakingAddress) { 9017 assert(OverloadedExpr->getType() == Context.OverloadTy); 9018 9019 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9020 OverloadExpr *OvlExpr = Ovl.Expression; 9021 9022 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9023 IEnd = OvlExpr->decls_end(); 9024 I != IEnd; ++I) { 9025 if (FunctionTemplateDecl *FunTmpl = 9026 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9027 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9028 TakingAddress); 9029 } else if (FunctionDecl *Fun 9030 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9031 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9032 } 9033 } 9034 } 9035 9036 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9037 /// "lead" diagnostic; it will be given two arguments, the source and 9038 /// target types of the conversion. 9039 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9040 Sema &S, 9041 SourceLocation CaretLoc, 9042 const PartialDiagnostic &PDiag) const { 9043 S.Diag(CaretLoc, PDiag) 9044 << Ambiguous.getFromType() << Ambiguous.getToType(); 9045 // FIXME: The note limiting machinery is borrowed from 9046 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9047 // refactoring here. 9048 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9049 unsigned CandsShown = 0; 9050 AmbiguousConversionSequence::const_iterator I, E; 9051 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9052 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9053 break; 9054 ++CandsShown; 9055 S.NoteOverloadCandidate(I->first, I->second); 9056 } 9057 if (I != E) 9058 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9059 } 9060 9061 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9062 unsigned I, bool TakingCandidateAddress) { 9063 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9064 assert(Conv.isBad()); 9065 assert(Cand->Function && "for now, candidate must be a function"); 9066 FunctionDecl *Fn = Cand->Function; 9067 9068 // There's a conversion slot for the object argument if this is a 9069 // non-constructor method. Note that 'I' corresponds the 9070 // conversion-slot index. 9071 bool isObjectArgument = false; 9072 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9073 if (I == 0) 9074 isObjectArgument = true; 9075 else 9076 I--; 9077 } 9078 9079 std::string FnDesc; 9080 OverloadCandidateKind FnKind = 9081 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9082 9083 Expr *FromExpr = Conv.Bad.FromExpr; 9084 QualType FromTy = Conv.Bad.getFromType(); 9085 QualType ToTy = Conv.Bad.getToType(); 9086 9087 if (FromTy == S.Context.OverloadTy) { 9088 assert(FromExpr && "overload set argument came from implicit argument?"); 9089 Expr *E = FromExpr->IgnoreParens(); 9090 if (isa<UnaryOperator>(E)) 9091 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9092 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9093 9094 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9095 << (unsigned) FnKind << FnDesc 9096 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9097 << ToTy << Name << I+1; 9098 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9099 return; 9100 } 9101 9102 // Do some hand-waving analysis to see if the non-viability is due 9103 // to a qualifier mismatch. 9104 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9105 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9106 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9107 CToTy = RT->getPointeeType(); 9108 else { 9109 // TODO: detect and diagnose the full richness of const mismatches. 9110 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9111 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9112 CFromTy = FromPT->getPointeeType(); 9113 CToTy = ToPT->getPointeeType(); 9114 } 9115 } 9116 9117 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9118 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9119 Qualifiers FromQs = CFromTy.getQualifiers(); 9120 Qualifiers ToQs = CToTy.getQualifiers(); 9121 9122 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9124 << (unsigned) FnKind << FnDesc 9125 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9126 << FromTy 9127 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9128 << (unsigned) isObjectArgument << I+1; 9129 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9130 return; 9131 } 9132 9133 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9134 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9135 << (unsigned) FnKind << FnDesc 9136 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9137 << FromTy 9138 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9139 << (unsigned) isObjectArgument << I+1; 9140 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9141 return; 9142 } 9143 9144 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9145 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9146 << (unsigned) FnKind << FnDesc 9147 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9148 << FromTy 9149 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9150 << (unsigned) isObjectArgument << I+1; 9151 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9152 return; 9153 } 9154 9155 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9156 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9157 << (unsigned) FnKind << FnDesc 9158 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9159 << FromTy << FromQs.hasUnaligned() << I+1; 9160 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9161 return; 9162 } 9163 9164 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9165 assert(CVR && "unexpected qualifiers mismatch"); 9166 9167 if (isObjectArgument) { 9168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9169 << (unsigned) FnKind << FnDesc 9170 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9171 << FromTy << (CVR - 1); 9172 } else { 9173 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9174 << (unsigned) FnKind << FnDesc 9175 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9176 << FromTy << (CVR - 1) << I+1; 9177 } 9178 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9179 return; 9180 } 9181 9182 // Special diagnostic for failure to convert an initializer list, since 9183 // telling the user that it has type void is not useful. 9184 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9185 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9186 << (unsigned) FnKind << FnDesc 9187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9188 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9189 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9190 return; 9191 } 9192 9193 // Diagnose references or pointers to incomplete types differently, 9194 // since it's far from impossible that the incompleteness triggered 9195 // the failure. 9196 QualType TempFromTy = FromTy.getNonReferenceType(); 9197 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9198 TempFromTy = PTy->getPointeeType(); 9199 if (TempFromTy->isIncompleteType()) { 9200 // Emit the generic diagnostic and, optionally, add the hints to it. 9201 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9202 << (unsigned) FnKind << FnDesc 9203 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9204 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9205 << (unsigned) (Cand->Fix.Kind); 9206 9207 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9208 return; 9209 } 9210 9211 // Diagnose base -> derived pointer conversions. 9212 unsigned BaseToDerivedConversion = 0; 9213 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9214 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9215 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9216 FromPtrTy->getPointeeType()) && 9217 !FromPtrTy->getPointeeType()->isIncompleteType() && 9218 !ToPtrTy->getPointeeType()->isIncompleteType() && 9219 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9220 FromPtrTy->getPointeeType())) 9221 BaseToDerivedConversion = 1; 9222 } 9223 } else if (const ObjCObjectPointerType *FromPtrTy 9224 = FromTy->getAs<ObjCObjectPointerType>()) { 9225 if (const ObjCObjectPointerType *ToPtrTy 9226 = ToTy->getAs<ObjCObjectPointerType>()) 9227 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9228 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9229 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9230 FromPtrTy->getPointeeType()) && 9231 FromIface->isSuperClassOf(ToIface)) 9232 BaseToDerivedConversion = 2; 9233 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9234 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9235 !FromTy->isIncompleteType() && 9236 !ToRefTy->getPointeeType()->isIncompleteType() && 9237 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9238 BaseToDerivedConversion = 3; 9239 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9240 ToTy.getNonReferenceType().getCanonicalType() == 9241 FromTy.getNonReferenceType().getCanonicalType()) { 9242 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9243 << (unsigned) FnKind << FnDesc 9244 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9245 << (unsigned) isObjectArgument << I + 1; 9246 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9247 return; 9248 } 9249 } 9250 9251 if (BaseToDerivedConversion) { 9252 S.Diag(Fn->getLocation(), 9253 diag::note_ovl_candidate_bad_base_to_derived_conv) 9254 << (unsigned) FnKind << FnDesc 9255 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9256 << (BaseToDerivedConversion - 1) 9257 << FromTy << ToTy << I+1; 9258 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9259 return; 9260 } 9261 9262 if (isa<ObjCObjectPointerType>(CFromTy) && 9263 isa<PointerType>(CToTy)) { 9264 Qualifiers FromQs = CFromTy.getQualifiers(); 9265 Qualifiers ToQs = CToTy.getQualifiers(); 9266 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9267 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9268 << (unsigned) FnKind << FnDesc 9269 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9270 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9271 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9272 return; 9273 } 9274 } 9275 9276 if (TakingCandidateAddress && 9277 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9278 return; 9279 9280 // Emit the generic diagnostic and, optionally, add the hints to it. 9281 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9282 FDiag << (unsigned) FnKind << FnDesc 9283 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9284 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9285 << (unsigned) (Cand->Fix.Kind); 9286 9287 // If we can fix the conversion, suggest the FixIts. 9288 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9289 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9290 FDiag << *HI; 9291 S.Diag(Fn->getLocation(), FDiag); 9292 9293 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9294 } 9295 9296 /// Additional arity mismatch diagnosis specific to a function overload 9297 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9298 /// over a candidate in any candidate set. 9299 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9300 unsigned NumArgs) { 9301 FunctionDecl *Fn = Cand->Function; 9302 unsigned MinParams = Fn->getMinRequiredArguments(); 9303 9304 // With invalid overloaded operators, it's possible that we think we 9305 // have an arity mismatch when in fact it looks like we have the 9306 // right number of arguments, because only overloaded operators have 9307 // the weird behavior of overloading member and non-member functions. 9308 // Just don't report anything. 9309 if (Fn->isInvalidDecl() && 9310 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9311 return true; 9312 9313 if (NumArgs < MinParams) { 9314 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9315 (Cand->FailureKind == ovl_fail_bad_deduction && 9316 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9317 } else { 9318 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9319 (Cand->FailureKind == ovl_fail_bad_deduction && 9320 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9321 } 9322 9323 return false; 9324 } 9325 9326 /// General arity mismatch diagnosis over a candidate in a candidate set. 9327 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9328 unsigned NumFormalArgs) { 9329 assert(isa<FunctionDecl>(D) && 9330 "The templated declaration should at least be a function" 9331 " when diagnosing bad template argument deduction due to too many" 9332 " or too few arguments"); 9333 9334 FunctionDecl *Fn = cast<FunctionDecl>(D); 9335 9336 // TODO: treat calls to a missing default constructor as a special case 9337 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9338 unsigned MinParams = Fn->getMinRequiredArguments(); 9339 9340 // at least / at most / exactly 9341 unsigned mode, modeCount; 9342 if (NumFormalArgs < MinParams) { 9343 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9344 FnTy->isTemplateVariadic()) 9345 mode = 0; // "at least" 9346 else 9347 mode = 2; // "exactly" 9348 modeCount = MinParams; 9349 } else { 9350 if (MinParams != FnTy->getNumParams()) 9351 mode = 1; // "at most" 9352 else 9353 mode = 2; // "exactly" 9354 modeCount = FnTy->getNumParams(); 9355 } 9356 9357 std::string Description; 9358 OverloadCandidateKind FnKind = 9359 ClassifyOverloadCandidate(S, Found, Fn, Description); 9360 9361 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9362 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9363 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9364 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9365 else 9366 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9367 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9368 << mode << modeCount << NumFormalArgs; 9369 MaybeEmitInheritedConstructorNote(S, Found); 9370 } 9371 9372 /// Arity mismatch diagnosis specific to a function overload candidate. 9373 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9374 unsigned NumFormalArgs) { 9375 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9376 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9377 } 9378 9379 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9380 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9381 return TD; 9382 llvm_unreachable("Unsupported: Getting the described template declaration" 9383 " for bad deduction diagnosis"); 9384 } 9385 9386 /// Diagnose a failed template-argument deduction. 9387 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9388 DeductionFailureInfo &DeductionFailure, 9389 unsigned NumArgs, 9390 bool TakingCandidateAddress) { 9391 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9392 NamedDecl *ParamD; 9393 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9394 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9395 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9396 switch (DeductionFailure.Result) { 9397 case Sema::TDK_Success: 9398 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9399 9400 case Sema::TDK_Incomplete: { 9401 assert(ParamD && "no parameter found for incomplete deduction result"); 9402 S.Diag(Templated->getLocation(), 9403 diag::note_ovl_candidate_incomplete_deduction) 9404 << ParamD->getDeclName(); 9405 MaybeEmitInheritedConstructorNote(S, Found); 9406 return; 9407 } 9408 9409 case Sema::TDK_Underqualified: { 9410 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9411 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9412 9413 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9414 9415 // Param will have been canonicalized, but it should just be a 9416 // qualified version of ParamD, so move the qualifiers to that. 9417 QualifierCollector Qs; 9418 Qs.strip(Param); 9419 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9420 assert(S.Context.hasSameType(Param, NonCanonParam)); 9421 9422 // Arg has also been canonicalized, but there's nothing we can do 9423 // about that. It also doesn't matter as much, because it won't 9424 // have any template parameters in it (because deduction isn't 9425 // done on dependent types). 9426 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9427 9428 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9429 << ParamD->getDeclName() << Arg << NonCanonParam; 9430 MaybeEmitInheritedConstructorNote(S, Found); 9431 return; 9432 } 9433 9434 case Sema::TDK_Inconsistent: { 9435 assert(ParamD && "no parameter found for inconsistent deduction result"); 9436 int which = 0; 9437 if (isa<TemplateTypeParmDecl>(ParamD)) 9438 which = 0; 9439 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9440 which = 1; 9441 else { 9442 which = 2; 9443 } 9444 9445 S.Diag(Templated->getLocation(), 9446 diag::note_ovl_candidate_inconsistent_deduction) 9447 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9448 << *DeductionFailure.getSecondArg(); 9449 MaybeEmitInheritedConstructorNote(S, Found); 9450 return; 9451 } 9452 9453 case Sema::TDK_InvalidExplicitArguments: 9454 assert(ParamD && "no parameter found for invalid explicit arguments"); 9455 if (ParamD->getDeclName()) 9456 S.Diag(Templated->getLocation(), 9457 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9458 << ParamD->getDeclName(); 9459 else { 9460 int index = 0; 9461 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9462 index = TTP->getIndex(); 9463 else if (NonTypeTemplateParmDecl *NTTP 9464 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9465 index = NTTP->getIndex(); 9466 else 9467 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9468 S.Diag(Templated->getLocation(), 9469 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9470 << (index + 1); 9471 } 9472 MaybeEmitInheritedConstructorNote(S, Found); 9473 return; 9474 9475 case Sema::TDK_TooManyArguments: 9476 case Sema::TDK_TooFewArguments: 9477 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9478 return; 9479 9480 case Sema::TDK_InstantiationDepth: 9481 S.Diag(Templated->getLocation(), 9482 diag::note_ovl_candidate_instantiation_depth); 9483 MaybeEmitInheritedConstructorNote(S, Found); 9484 return; 9485 9486 case Sema::TDK_SubstitutionFailure: { 9487 // Format the template argument list into the argument string. 9488 SmallString<128> TemplateArgString; 9489 if (TemplateArgumentList *Args = 9490 DeductionFailure.getTemplateArgumentList()) { 9491 TemplateArgString = " "; 9492 TemplateArgString += S.getTemplateArgumentBindingsText( 9493 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9494 } 9495 9496 // If this candidate was disabled by enable_if, say so. 9497 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9498 if (PDiag && PDiag->second.getDiagID() == 9499 diag::err_typename_nested_not_found_enable_if) { 9500 // FIXME: Use the source range of the condition, and the fully-qualified 9501 // name of the enable_if template. These are both present in PDiag. 9502 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9503 << "'enable_if'" << TemplateArgString; 9504 return; 9505 } 9506 9507 // Format the SFINAE diagnostic into the argument string. 9508 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9509 // formatted message in another diagnostic. 9510 SmallString<128> SFINAEArgString; 9511 SourceRange R; 9512 if (PDiag) { 9513 SFINAEArgString = ": "; 9514 R = SourceRange(PDiag->first, PDiag->first); 9515 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9516 } 9517 9518 S.Diag(Templated->getLocation(), 9519 diag::note_ovl_candidate_substitution_failure) 9520 << TemplateArgString << SFINAEArgString << R; 9521 MaybeEmitInheritedConstructorNote(S, Found); 9522 return; 9523 } 9524 9525 case Sema::TDK_FailedOverloadResolution: { 9526 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9527 S.Diag(Templated->getLocation(), 9528 diag::note_ovl_candidate_failed_overload_resolution) 9529 << R.Expression->getName(); 9530 return; 9531 } 9532 9533 case Sema::TDK_DeducedMismatch: { 9534 // Format the template argument list into the argument string. 9535 SmallString<128> TemplateArgString; 9536 if (TemplateArgumentList *Args = 9537 DeductionFailure.getTemplateArgumentList()) { 9538 TemplateArgString = " "; 9539 TemplateArgString += S.getTemplateArgumentBindingsText( 9540 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9541 } 9542 9543 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9544 << (*DeductionFailure.getCallArgIndex() + 1) 9545 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9546 << TemplateArgString; 9547 break; 9548 } 9549 9550 case Sema::TDK_NonDeducedMismatch: { 9551 // FIXME: Provide a source location to indicate what we couldn't match. 9552 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9553 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9554 if (FirstTA.getKind() == TemplateArgument::Template && 9555 SecondTA.getKind() == TemplateArgument::Template) { 9556 TemplateName FirstTN = FirstTA.getAsTemplate(); 9557 TemplateName SecondTN = SecondTA.getAsTemplate(); 9558 if (FirstTN.getKind() == TemplateName::Template && 9559 SecondTN.getKind() == TemplateName::Template) { 9560 if (FirstTN.getAsTemplateDecl()->getName() == 9561 SecondTN.getAsTemplateDecl()->getName()) { 9562 // FIXME: This fixes a bad diagnostic where both templates are named 9563 // the same. This particular case is a bit difficult since: 9564 // 1) It is passed as a string to the diagnostic printer. 9565 // 2) The diagnostic printer only attempts to find a better 9566 // name for types, not decls. 9567 // Ideally, this should folded into the diagnostic printer. 9568 S.Diag(Templated->getLocation(), 9569 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9570 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9571 return; 9572 } 9573 } 9574 } 9575 9576 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9577 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9578 return; 9579 9580 // FIXME: For generic lambda parameters, check if the function is a lambda 9581 // call operator, and if so, emit a prettier and more informative 9582 // diagnostic that mentions 'auto' and lambda in addition to 9583 // (or instead of?) the canonical template type parameters. 9584 S.Diag(Templated->getLocation(), 9585 diag::note_ovl_candidate_non_deduced_mismatch) 9586 << FirstTA << SecondTA; 9587 return; 9588 } 9589 // TODO: diagnose these individually, then kill off 9590 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9591 case Sema::TDK_MiscellaneousDeductionFailure: 9592 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9593 MaybeEmitInheritedConstructorNote(S, Found); 9594 return; 9595 } 9596 } 9597 9598 /// Diagnose a failed template-argument deduction, for function calls. 9599 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9600 unsigned NumArgs, 9601 bool TakingCandidateAddress) { 9602 unsigned TDK = Cand->DeductionFailure.Result; 9603 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9604 if (CheckArityMismatch(S, Cand, NumArgs)) 9605 return; 9606 } 9607 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9608 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9609 } 9610 9611 /// CUDA: diagnose an invalid call across targets. 9612 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9613 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9614 FunctionDecl *Callee = Cand->Function; 9615 9616 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9617 CalleeTarget = S.IdentifyCUDATarget(Callee); 9618 9619 std::string FnDesc; 9620 OverloadCandidateKind FnKind = 9621 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 9622 9623 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9624 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9625 9626 // This could be an implicit constructor for which we could not infer the 9627 // target due to a collsion. Diagnose that case. 9628 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9629 if (Meth != nullptr && Meth->isImplicit()) { 9630 CXXRecordDecl *ParentClass = Meth->getParent(); 9631 Sema::CXXSpecialMember CSM; 9632 9633 switch (FnKind) { 9634 default: 9635 return; 9636 case oc_implicit_default_constructor: 9637 CSM = Sema::CXXDefaultConstructor; 9638 break; 9639 case oc_implicit_copy_constructor: 9640 CSM = Sema::CXXCopyConstructor; 9641 break; 9642 case oc_implicit_move_constructor: 9643 CSM = Sema::CXXMoveConstructor; 9644 break; 9645 case oc_implicit_copy_assignment: 9646 CSM = Sema::CXXCopyAssignment; 9647 break; 9648 case oc_implicit_move_assignment: 9649 CSM = Sema::CXXMoveAssignment; 9650 break; 9651 }; 9652 9653 bool ConstRHS = false; 9654 if (Meth->getNumParams()) { 9655 if (const ReferenceType *RT = 9656 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9657 ConstRHS = RT->getPointeeType().isConstQualified(); 9658 } 9659 } 9660 9661 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9662 /* ConstRHS */ ConstRHS, 9663 /* Diagnose */ true); 9664 } 9665 } 9666 9667 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9668 FunctionDecl *Callee = Cand->Function; 9669 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9670 9671 S.Diag(Callee->getLocation(), 9672 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9673 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9674 } 9675 9676 /// Generates a 'note' diagnostic for an overload candidate. We've 9677 /// already generated a primary error at the call site. 9678 /// 9679 /// It really does need to be a single diagnostic with its caret 9680 /// pointed at the candidate declaration. Yes, this creates some 9681 /// major challenges of technical writing. Yes, this makes pointing 9682 /// out problems with specific arguments quite awkward. It's still 9683 /// better than generating twenty screens of text for every failed 9684 /// overload. 9685 /// 9686 /// It would be great to be able to express per-candidate problems 9687 /// more richly for those diagnostic clients that cared, but we'd 9688 /// still have to be just as careful with the default diagnostics. 9689 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9690 unsigned NumArgs, 9691 bool TakingCandidateAddress) { 9692 FunctionDecl *Fn = Cand->Function; 9693 9694 // Note deleted candidates, but only if they're viable. 9695 if (Cand->Viable && (Fn->isDeleted() || 9696 S.isFunctionConsideredUnavailable(Fn))) { 9697 std::string FnDesc; 9698 OverloadCandidateKind FnKind = 9699 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9700 9701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9702 << FnKind << FnDesc 9703 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9704 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9705 return; 9706 } 9707 9708 // We don't really have anything else to say about viable candidates. 9709 if (Cand->Viable) { 9710 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9711 return; 9712 } 9713 9714 switch (Cand->FailureKind) { 9715 case ovl_fail_too_many_arguments: 9716 case ovl_fail_too_few_arguments: 9717 return DiagnoseArityMismatch(S, Cand, NumArgs); 9718 9719 case ovl_fail_bad_deduction: 9720 return DiagnoseBadDeduction(S, Cand, NumArgs, 9721 TakingCandidateAddress); 9722 9723 case ovl_fail_illegal_constructor: { 9724 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9725 << (Fn->getPrimaryTemplate() ? 1 : 0); 9726 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9727 return; 9728 } 9729 9730 case ovl_fail_trivial_conversion: 9731 case ovl_fail_bad_final_conversion: 9732 case ovl_fail_final_conversion_not_exact: 9733 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9734 9735 case ovl_fail_bad_conversion: { 9736 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9737 for (unsigned N = Cand->NumConversions; I != N; ++I) 9738 if (Cand->Conversions[I].isBad()) 9739 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9740 9741 // FIXME: this currently happens when we're called from SemaInit 9742 // when user-conversion overload fails. Figure out how to handle 9743 // those conditions and diagnose them well. 9744 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9745 } 9746 9747 case ovl_fail_bad_target: 9748 return DiagnoseBadTarget(S, Cand); 9749 9750 case ovl_fail_enable_if: 9751 return DiagnoseFailedEnableIfAttr(S, Cand); 9752 9753 case ovl_fail_addr_not_available: { 9754 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9755 (void)Available; 9756 assert(!Available); 9757 break; 9758 } 9759 } 9760 } 9761 9762 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9763 // Desugar the type of the surrogate down to a function type, 9764 // retaining as many typedefs as possible while still showing 9765 // the function type (and, therefore, its parameter types). 9766 QualType FnType = Cand->Surrogate->getConversionType(); 9767 bool isLValueReference = false; 9768 bool isRValueReference = false; 9769 bool isPointer = false; 9770 if (const LValueReferenceType *FnTypeRef = 9771 FnType->getAs<LValueReferenceType>()) { 9772 FnType = FnTypeRef->getPointeeType(); 9773 isLValueReference = true; 9774 } else if (const RValueReferenceType *FnTypeRef = 9775 FnType->getAs<RValueReferenceType>()) { 9776 FnType = FnTypeRef->getPointeeType(); 9777 isRValueReference = true; 9778 } 9779 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9780 FnType = FnTypePtr->getPointeeType(); 9781 isPointer = true; 9782 } 9783 // Desugar down to a function type. 9784 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9785 // Reconstruct the pointer/reference as appropriate. 9786 if (isPointer) FnType = S.Context.getPointerType(FnType); 9787 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9788 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9789 9790 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9791 << FnType; 9792 } 9793 9794 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9795 SourceLocation OpLoc, 9796 OverloadCandidate *Cand) { 9797 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9798 std::string TypeStr("operator"); 9799 TypeStr += Opc; 9800 TypeStr += "("; 9801 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9802 if (Cand->NumConversions == 1) { 9803 TypeStr += ")"; 9804 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9805 } else { 9806 TypeStr += ", "; 9807 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9808 TypeStr += ")"; 9809 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9810 } 9811 } 9812 9813 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9814 OverloadCandidate *Cand) { 9815 unsigned NoOperands = Cand->NumConversions; 9816 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9817 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9818 if (ICS.isBad()) break; // all meaningless after first invalid 9819 if (!ICS.isAmbiguous()) continue; 9820 9821 ICS.DiagnoseAmbiguousConversion( 9822 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 9823 } 9824 } 9825 9826 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9827 if (Cand->Function) 9828 return Cand->Function->getLocation(); 9829 if (Cand->IsSurrogate) 9830 return Cand->Surrogate->getLocation(); 9831 return SourceLocation(); 9832 } 9833 9834 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9835 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9836 case Sema::TDK_Success: 9837 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9838 9839 case Sema::TDK_Invalid: 9840 case Sema::TDK_Incomplete: 9841 return 1; 9842 9843 case Sema::TDK_Underqualified: 9844 case Sema::TDK_Inconsistent: 9845 return 2; 9846 9847 case Sema::TDK_SubstitutionFailure: 9848 case Sema::TDK_DeducedMismatch: 9849 case Sema::TDK_NonDeducedMismatch: 9850 case Sema::TDK_MiscellaneousDeductionFailure: 9851 return 3; 9852 9853 case Sema::TDK_InstantiationDepth: 9854 case Sema::TDK_FailedOverloadResolution: 9855 return 4; 9856 9857 case Sema::TDK_InvalidExplicitArguments: 9858 return 5; 9859 9860 case Sema::TDK_TooManyArguments: 9861 case Sema::TDK_TooFewArguments: 9862 return 6; 9863 } 9864 llvm_unreachable("Unhandled deduction result"); 9865 } 9866 9867 namespace { 9868 struct CompareOverloadCandidatesForDisplay { 9869 Sema &S; 9870 SourceLocation Loc; 9871 size_t NumArgs; 9872 9873 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9874 : S(S), NumArgs(nArgs) {} 9875 9876 bool operator()(const OverloadCandidate *L, 9877 const OverloadCandidate *R) { 9878 // Fast-path this check. 9879 if (L == R) return false; 9880 9881 // Order first by viability. 9882 if (L->Viable) { 9883 if (!R->Viable) return true; 9884 9885 // TODO: introduce a tri-valued comparison for overload 9886 // candidates. Would be more worthwhile if we had a sort 9887 // that could exploit it. 9888 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9889 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9890 } else if (R->Viable) 9891 return false; 9892 9893 assert(L->Viable == R->Viable); 9894 9895 // Criteria by which we can sort non-viable candidates: 9896 if (!L->Viable) { 9897 // 1. Arity mismatches come after other candidates. 9898 if (L->FailureKind == ovl_fail_too_many_arguments || 9899 L->FailureKind == ovl_fail_too_few_arguments) { 9900 if (R->FailureKind == ovl_fail_too_many_arguments || 9901 R->FailureKind == ovl_fail_too_few_arguments) { 9902 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9903 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9904 if (LDist == RDist) { 9905 if (L->FailureKind == R->FailureKind) 9906 // Sort non-surrogates before surrogates. 9907 return !L->IsSurrogate && R->IsSurrogate; 9908 // Sort candidates requiring fewer parameters than there were 9909 // arguments given after candidates requiring more parameters 9910 // than there were arguments given. 9911 return L->FailureKind == ovl_fail_too_many_arguments; 9912 } 9913 return LDist < RDist; 9914 } 9915 return false; 9916 } 9917 if (R->FailureKind == ovl_fail_too_many_arguments || 9918 R->FailureKind == ovl_fail_too_few_arguments) 9919 return true; 9920 9921 // 2. Bad conversions come first and are ordered by the number 9922 // of bad conversions and quality of good conversions. 9923 if (L->FailureKind == ovl_fail_bad_conversion) { 9924 if (R->FailureKind != ovl_fail_bad_conversion) 9925 return true; 9926 9927 // The conversion that can be fixed with a smaller number of changes, 9928 // comes first. 9929 unsigned numLFixes = L->Fix.NumConversionsFixed; 9930 unsigned numRFixes = R->Fix.NumConversionsFixed; 9931 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9932 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9933 if (numLFixes != numRFixes) { 9934 return numLFixes < numRFixes; 9935 } 9936 9937 // If there's any ordering between the defined conversions... 9938 // FIXME: this might not be transitive. 9939 assert(L->NumConversions == R->NumConversions); 9940 9941 int leftBetter = 0; 9942 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9943 for (unsigned E = L->NumConversions; I != E; ++I) { 9944 switch (CompareImplicitConversionSequences(S, Loc, 9945 L->Conversions[I], 9946 R->Conversions[I])) { 9947 case ImplicitConversionSequence::Better: 9948 leftBetter++; 9949 break; 9950 9951 case ImplicitConversionSequence::Worse: 9952 leftBetter--; 9953 break; 9954 9955 case ImplicitConversionSequence::Indistinguishable: 9956 break; 9957 } 9958 } 9959 if (leftBetter > 0) return true; 9960 if (leftBetter < 0) return false; 9961 9962 } else if (R->FailureKind == ovl_fail_bad_conversion) 9963 return false; 9964 9965 if (L->FailureKind == ovl_fail_bad_deduction) { 9966 if (R->FailureKind != ovl_fail_bad_deduction) 9967 return true; 9968 9969 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9970 return RankDeductionFailure(L->DeductionFailure) 9971 < RankDeductionFailure(R->DeductionFailure); 9972 } else if (R->FailureKind == ovl_fail_bad_deduction) 9973 return false; 9974 9975 // TODO: others? 9976 } 9977 9978 // Sort everything else by location. 9979 SourceLocation LLoc = GetLocationForCandidate(L); 9980 SourceLocation RLoc = GetLocationForCandidate(R); 9981 9982 // Put candidates without locations (e.g. builtins) at the end. 9983 if (LLoc.isInvalid()) return false; 9984 if (RLoc.isInvalid()) return true; 9985 9986 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9987 } 9988 }; 9989 } 9990 9991 /// CompleteNonViableCandidate - Normally, overload resolution only 9992 /// computes up to the first. Produces the FixIt set if possible. 9993 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9994 ArrayRef<Expr *> Args) { 9995 assert(!Cand->Viable); 9996 9997 // Don't do anything on failures other than bad conversion. 9998 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9999 10000 // We only want the FixIts if all the arguments can be corrected. 10001 bool Unfixable = false; 10002 // Use a implicit copy initialization to check conversion fixes. 10003 Cand->Fix.setConversionChecker(TryCopyInitialization); 10004 10005 // Skip forward to the first bad conversion. 10006 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10007 unsigned ConvCount = Cand->NumConversions; 10008 while (true) { 10009 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10010 ConvIdx++; 10011 if (Cand->Conversions[ConvIdx - 1].isBad()) { 10012 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 10013 break; 10014 } 10015 } 10016 10017 if (ConvIdx == ConvCount) 10018 return; 10019 10020 assert(!Cand->Conversions[ConvIdx].isInitialized() && 10021 "remaining conversion is initialized?"); 10022 10023 // FIXME: this should probably be preserved from the overload 10024 // operation somehow. 10025 bool SuppressUserConversions = false; 10026 10027 const FunctionProtoType* Proto; 10028 unsigned ArgIdx = ConvIdx; 10029 10030 if (Cand->IsSurrogate) { 10031 QualType ConvType 10032 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10033 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10034 ConvType = ConvPtrType->getPointeeType(); 10035 Proto = ConvType->getAs<FunctionProtoType>(); 10036 ArgIdx--; 10037 } else if (Cand->Function) { 10038 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10039 if (isa<CXXMethodDecl>(Cand->Function) && 10040 !isa<CXXConstructorDecl>(Cand->Function)) 10041 ArgIdx--; 10042 } else { 10043 // Builtin binary operator with a bad first conversion. 10044 assert(ConvCount <= 3); 10045 for (; ConvIdx != ConvCount; ++ConvIdx) 10046 Cand->Conversions[ConvIdx] 10047 = TryCopyInitialization(S, Args[ConvIdx], 10048 Cand->BuiltinTypes.ParamTypes[ConvIdx], 10049 SuppressUserConversions, 10050 /*InOverloadResolution*/ true, 10051 /*AllowObjCWritebackConversion=*/ 10052 S.getLangOpts().ObjCAutoRefCount); 10053 return; 10054 } 10055 10056 // Fill in the rest of the conversions. 10057 unsigned NumParams = Proto->getNumParams(); 10058 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10059 if (ArgIdx < NumParams) { 10060 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10061 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10062 /*InOverloadResolution=*/true, 10063 /*AllowObjCWritebackConversion=*/ 10064 S.getLangOpts().ObjCAutoRefCount); 10065 // Store the FixIt in the candidate if it exists. 10066 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10067 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10068 } 10069 else 10070 Cand->Conversions[ConvIdx].setEllipsis(); 10071 } 10072 } 10073 10074 /// PrintOverloadCandidates - When overload resolution fails, prints 10075 /// diagnostic messages containing the candidates in the candidate 10076 /// set. 10077 void OverloadCandidateSet::NoteCandidates(Sema &S, 10078 OverloadCandidateDisplayKind OCD, 10079 ArrayRef<Expr *> Args, 10080 StringRef Opc, 10081 SourceLocation OpLoc) { 10082 // Sort the candidates by viability and position. Sorting directly would 10083 // be prohibitive, so we make a set of pointers and sort those. 10084 SmallVector<OverloadCandidate*, 32> Cands; 10085 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10086 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10087 if (Cand->Viable) 10088 Cands.push_back(Cand); 10089 else if (OCD == OCD_AllCandidates) { 10090 CompleteNonViableCandidate(S, Cand, Args); 10091 if (Cand->Function || Cand->IsSurrogate) 10092 Cands.push_back(Cand); 10093 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10094 // want to list every possible builtin candidate. 10095 } 10096 } 10097 10098 std::sort(Cands.begin(), Cands.end(), 10099 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10100 10101 bool ReportedAmbiguousConversions = false; 10102 10103 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10104 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10105 unsigned CandsShown = 0; 10106 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10107 OverloadCandidate *Cand = *I; 10108 10109 // Set an arbitrary limit on the number of candidate functions we'll spam 10110 // the user with. FIXME: This limit should depend on details of the 10111 // candidate list. 10112 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10113 break; 10114 } 10115 ++CandsShown; 10116 10117 if (Cand->Function) 10118 NoteFunctionCandidate(S, Cand, Args.size(), 10119 /*TakingCandidateAddress=*/false); 10120 else if (Cand->IsSurrogate) 10121 NoteSurrogateCandidate(S, Cand); 10122 else { 10123 assert(Cand->Viable && 10124 "Non-viable built-in candidates are not added to Cands."); 10125 // Generally we only see ambiguities including viable builtin 10126 // operators if overload resolution got screwed up by an 10127 // ambiguous user-defined conversion. 10128 // 10129 // FIXME: It's quite possible for different conversions to see 10130 // different ambiguities, though. 10131 if (!ReportedAmbiguousConversions) { 10132 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10133 ReportedAmbiguousConversions = true; 10134 } 10135 10136 // If this is a viable builtin, print it. 10137 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10138 } 10139 } 10140 10141 if (I != E) 10142 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10143 } 10144 10145 static SourceLocation 10146 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10147 return Cand->Specialization ? Cand->Specialization->getLocation() 10148 : SourceLocation(); 10149 } 10150 10151 namespace { 10152 struct CompareTemplateSpecCandidatesForDisplay { 10153 Sema &S; 10154 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10155 10156 bool operator()(const TemplateSpecCandidate *L, 10157 const TemplateSpecCandidate *R) { 10158 // Fast-path this check. 10159 if (L == R) 10160 return false; 10161 10162 // Assuming that both candidates are not matches... 10163 10164 // Sort by the ranking of deduction failures. 10165 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10166 return RankDeductionFailure(L->DeductionFailure) < 10167 RankDeductionFailure(R->DeductionFailure); 10168 10169 // Sort everything else by location. 10170 SourceLocation LLoc = GetLocationForCandidate(L); 10171 SourceLocation RLoc = GetLocationForCandidate(R); 10172 10173 // Put candidates without locations (e.g. builtins) at the end. 10174 if (LLoc.isInvalid()) 10175 return false; 10176 if (RLoc.isInvalid()) 10177 return true; 10178 10179 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10180 } 10181 }; 10182 } 10183 10184 /// Diagnose a template argument deduction failure. 10185 /// We are treating these failures as overload failures due to bad 10186 /// deductions. 10187 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10188 bool ForTakingAddress) { 10189 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10190 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10191 } 10192 10193 void TemplateSpecCandidateSet::destroyCandidates() { 10194 for (iterator i = begin(), e = end(); i != e; ++i) { 10195 i->DeductionFailure.Destroy(); 10196 } 10197 } 10198 10199 void TemplateSpecCandidateSet::clear() { 10200 destroyCandidates(); 10201 Candidates.clear(); 10202 } 10203 10204 /// NoteCandidates - When no template specialization match is found, prints 10205 /// diagnostic messages containing the non-matching specializations that form 10206 /// the candidate set. 10207 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10208 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10209 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10210 // Sort the candidates by position (assuming no candidate is a match). 10211 // Sorting directly would be prohibitive, so we make a set of pointers 10212 // and sort those. 10213 SmallVector<TemplateSpecCandidate *, 32> Cands; 10214 Cands.reserve(size()); 10215 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10216 if (Cand->Specialization) 10217 Cands.push_back(Cand); 10218 // Otherwise, this is a non-matching builtin candidate. We do not, 10219 // in general, want to list every possible builtin candidate. 10220 } 10221 10222 std::sort(Cands.begin(), Cands.end(), 10223 CompareTemplateSpecCandidatesForDisplay(S)); 10224 10225 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10226 // for generalization purposes (?). 10227 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10228 10229 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10230 unsigned CandsShown = 0; 10231 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10232 TemplateSpecCandidate *Cand = *I; 10233 10234 // Set an arbitrary limit on the number of candidates we'll spam 10235 // the user with. FIXME: This limit should depend on details of the 10236 // candidate list. 10237 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10238 break; 10239 ++CandsShown; 10240 10241 assert(Cand->Specialization && 10242 "Non-matching built-in candidates are not added to Cands."); 10243 Cand->NoteDeductionFailure(S, ForTakingAddress); 10244 } 10245 10246 if (I != E) 10247 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10248 } 10249 10250 // [PossiblyAFunctionType] --> [Return] 10251 // NonFunctionType --> NonFunctionType 10252 // R (A) --> R(A) 10253 // R (*)(A) --> R (A) 10254 // R (&)(A) --> R (A) 10255 // R (S::*)(A) --> R (A) 10256 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10257 QualType Ret = PossiblyAFunctionType; 10258 if (const PointerType *ToTypePtr = 10259 PossiblyAFunctionType->getAs<PointerType>()) 10260 Ret = ToTypePtr->getPointeeType(); 10261 else if (const ReferenceType *ToTypeRef = 10262 PossiblyAFunctionType->getAs<ReferenceType>()) 10263 Ret = ToTypeRef->getPointeeType(); 10264 else if (const MemberPointerType *MemTypePtr = 10265 PossiblyAFunctionType->getAs<MemberPointerType>()) 10266 Ret = MemTypePtr->getPointeeType(); 10267 Ret = 10268 Context.getCanonicalType(Ret).getUnqualifiedType(); 10269 return Ret; 10270 } 10271 10272 namespace { 10273 // A helper class to help with address of function resolution 10274 // - allows us to avoid passing around all those ugly parameters 10275 class AddressOfFunctionResolver { 10276 Sema& S; 10277 Expr* SourceExpr; 10278 const QualType& TargetType; 10279 QualType TargetFunctionType; // Extracted function type from target type 10280 10281 bool Complain; 10282 //DeclAccessPair& ResultFunctionAccessPair; 10283 ASTContext& Context; 10284 10285 bool TargetTypeIsNonStaticMemberFunction; 10286 bool FoundNonTemplateFunction; 10287 bool StaticMemberFunctionFromBoundPointer; 10288 bool HasComplained; 10289 10290 OverloadExpr::FindResult OvlExprInfo; 10291 OverloadExpr *OvlExpr; 10292 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10293 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10294 TemplateSpecCandidateSet FailedCandidates; 10295 10296 public: 10297 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10298 const QualType &TargetType, bool Complain) 10299 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10300 Complain(Complain), Context(S.getASTContext()), 10301 TargetTypeIsNonStaticMemberFunction( 10302 !!TargetType->getAs<MemberPointerType>()), 10303 FoundNonTemplateFunction(false), 10304 StaticMemberFunctionFromBoundPointer(false), 10305 HasComplained(false), 10306 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10307 OvlExpr(OvlExprInfo.Expression), 10308 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10309 ExtractUnqualifiedFunctionTypeFromTargetType(); 10310 10311 if (TargetFunctionType->isFunctionType()) { 10312 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10313 if (!UME->isImplicitAccess() && 10314 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10315 StaticMemberFunctionFromBoundPointer = true; 10316 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10317 DeclAccessPair dap; 10318 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10319 OvlExpr, false, &dap)) { 10320 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10321 if (!Method->isStatic()) { 10322 // If the target type is a non-function type and the function found 10323 // is a non-static member function, pretend as if that was the 10324 // target, it's the only possible type to end up with. 10325 TargetTypeIsNonStaticMemberFunction = true; 10326 10327 // And skip adding the function if its not in the proper form. 10328 // We'll diagnose this due to an empty set of functions. 10329 if (!OvlExprInfo.HasFormOfMemberPointer) 10330 return; 10331 } 10332 10333 Matches.push_back(std::make_pair(dap, Fn)); 10334 } 10335 return; 10336 } 10337 10338 if (OvlExpr->hasExplicitTemplateArgs()) 10339 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10340 10341 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10342 // C++ [over.over]p4: 10343 // If more than one function is selected, [...] 10344 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10345 if (FoundNonTemplateFunction) 10346 EliminateAllTemplateMatches(); 10347 else 10348 EliminateAllExceptMostSpecializedTemplate(); 10349 } 10350 } 10351 10352 if (S.getLangOpts().CUDA && Matches.size() > 1) 10353 EliminateSuboptimalCudaMatches(); 10354 } 10355 10356 bool hasComplained() const { return HasComplained; } 10357 10358 private: 10359 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10360 QualType Discard; 10361 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10362 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard); 10363 } 10364 10365 /// \return true if A is considered a better overload candidate for the 10366 /// desired type than B. 10367 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10368 // If A doesn't have exactly the correct type, we don't want to classify it 10369 // as "better" than anything else. This way, the user is required to 10370 // disambiguate for us if there are multiple candidates and no exact match. 10371 return candidateHasExactlyCorrectType(A) && 10372 (!candidateHasExactlyCorrectType(B) || 10373 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10374 } 10375 10376 /// \return true if we were able to eliminate all but one overload candidate, 10377 /// false otherwise. 10378 bool eliminiateSuboptimalOverloadCandidates() { 10379 // Same algorithm as overload resolution -- one pass to pick the "best", 10380 // another pass to be sure that nothing is better than the best. 10381 auto Best = Matches.begin(); 10382 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10383 if (isBetterCandidate(I->second, Best->second)) 10384 Best = I; 10385 10386 const FunctionDecl *BestFn = Best->second; 10387 auto IsBestOrInferiorToBest = [this, BestFn]( 10388 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10389 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10390 }; 10391 10392 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10393 // option, so we can potentially give the user a better error 10394 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10395 return false; 10396 Matches[0] = *Best; 10397 Matches.resize(1); 10398 return true; 10399 } 10400 10401 bool isTargetTypeAFunction() const { 10402 return TargetFunctionType->isFunctionType(); 10403 } 10404 10405 // [ToType] [Return] 10406 10407 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10408 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10409 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10410 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10411 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10412 } 10413 10414 // return true if any matching specializations were found 10415 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10416 const DeclAccessPair& CurAccessFunPair) { 10417 if (CXXMethodDecl *Method 10418 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10419 // Skip non-static function templates when converting to pointer, and 10420 // static when converting to member pointer. 10421 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10422 return false; 10423 } 10424 else if (TargetTypeIsNonStaticMemberFunction) 10425 return false; 10426 10427 // C++ [over.over]p2: 10428 // If the name is a function template, template argument deduction is 10429 // done (14.8.2.2), and if the argument deduction succeeds, the 10430 // resulting template argument list is used to generate a single 10431 // function template specialization, which is added to the set of 10432 // overloaded functions considered. 10433 FunctionDecl *Specialization = nullptr; 10434 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10435 if (Sema::TemplateDeductionResult Result 10436 = S.DeduceTemplateArguments(FunctionTemplate, 10437 &OvlExplicitTemplateArgs, 10438 TargetFunctionType, Specialization, 10439 Info, /*InOverloadResolution=*/true)) { 10440 // Make a note of the failed deduction for diagnostics. 10441 FailedCandidates.addCandidate() 10442 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10443 MakeDeductionFailureInfo(Context, Result, Info)); 10444 return false; 10445 } 10446 10447 // Template argument deduction ensures that we have an exact match or 10448 // compatible pointer-to-function arguments that would be adjusted by ICS. 10449 // This function template specicalization works. 10450 assert(S.isSameOrCompatibleFunctionType( 10451 Context.getCanonicalType(Specialization->getType()), 10452 Context.getCanonicalType(TargetFunctionType))); 10453 10454 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10455 return false; 10456 10457 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10458 return true; 10459 } 10460 10461 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10462 const DeclAccessPair& CurAccessFunPair) { 10463 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10464 // Skip non-static functions when converting to pointer, and static 10465 // when converting to member pointer. 10466 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10467 return false; 10468 } 10469 else if (TargetTypeIsNonStaticMemberFunction) 10470 return false; 10471 10472 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10473 if (S.getLangOpts().CUDA) 10474 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10475 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10476 return false; 10477 10478 // If any candidate has a placeholder return type, trigger its deduction 10479 // now. 10480 if (S.getLangOpts().CPlusPlus14 && 10481 FunDecl->getReturnType()->isUndeducedType() && 10482 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10483 HasComplained |= Complain; 10484 return false; 10485 } 10486 10487 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10488 return false; 10489 10490 // If we're in C, we need to support types that aren't exactly identical. 10491 if (!S.getLangOpts().CPlusPlus || 10492 candidateHasExactlyCorrectType(FunDecl)) { 10493 Matches.push_back(std::make_pair( 10494 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10495 FoundNonTemplateFunction = true; 10496 return true; 10497 } 10498 } 10499 10500 return false; 10501 } 10502 10503 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10504 bool Ret = false; 10505 10506 // If the overload expression doesn't have the form of a pointer to 10507 // member, don't try to convert it to a pointer-to-member type. 10508 if (IsInvalidFormOfPointerToMemberFunction()) 10509 return false; 10510 10511 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10512 E = OvlExpr->decls_end(); 10513 I != E; ++I) { 10514 // Look through any using declarations to find the underlying function. 10515 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10516 10517 // C++ [over.over]p3: 10518 // Non-member functions and static member functions match 10519 // targets of type "pointer-to-function" or "reference-to-function." 10520 // Nonstatic member functions match targets of 10521 // type "pointer-to-member-function." 10522 // Note that according to DR 247, the containing class does not matter. 10523 if (FunctionTemplateDecl *FunctionTemplate 10524 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10525 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10526 Ret = true; 10527 } 10528 // If we have explicit template arguments supplied, skip non-templates. 10529 else if (!OvlExpr->hasExplicitTemplateArgs() && 10530 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10531 Ret = true; 10532 } 10533 assert(Ret || Matches.empty()); 10534 return Ret; 10535 } 10536 10537 void EliminateAllExceptMostSpecializedTemplate() { 10538 // [...] and any given function template specialization F1 is 10539 // eliminated if the set contains a second function template 10540 // specialization whose function template is more specialized 10541 // than the function template of F1 according to the partial 10542 // ordering rules of 14.5.5.2. 10543 10544 // The algorithm specified above is quadratic. We instead use a 10545 // two-pass algorithm (similar to the one used to identify the 10546 // best viable function in an overload set) that identifies the 10547 // best function template (if it exists). 10548 10549 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10550 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10551 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10552 10553 // TODO: It looks like FailedCandidates does not serve much purpose 10554 // here, since the no_viable diagnostic has index 0. 10555 UnresolvedSetIterator Result = S.getMostSpecialized( 10556 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10557 SourceExpr->getLocStart(), S.PDiag(), 10558 S.PDiag(diag::err_addr_ovl_ambiguous) 10559 << Matches[0].second->getDeclName(), 10560 S.PDiag(diag::note_ovl_candidate) 10561 << (unsigned)oc_function_template, 10562 Complain, TargetFunctionType); 10563 10564 if (Result != MatchesCopy.end()) { 10565 // Make it the first and only element 10566 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10567 Matches[0].second = cast<FunctionDecl>(*Result); 10568 Matches.resize(1); 10569 } else 10570 HasComplained |= Complain; 10571 } 10572 10573 void EliminateAllTemplateMatches() { 10574 // [...] any function template specializations in the set are 10575 // eliminated if the set also contains a non-template function, [...] 10576 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10577 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10578 ++I; 10579 else { 10580 Matches[I] = Matches[--N]; 10581 Matches.resize(N); 10582 } 10583 } 10584 } 10585 10586 void EliminateSuboptimalCudaMatches() { 10587 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10588 } 10589 10590 public: 10591 void ComplainNoMatchesFound() const { 10592 assert(Matches.empty()); 10593 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10594 << OvlExpr->getName() << TargetFunctionType 10595 << OvlExpr->getSourceRange(); 10596 if (FailedCandidates.empty()) 10597 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10598 /*TakingAddress=*/true); 10599 else { 10600 // We have some deduction failure messages. Use them to diagnose 10601 // the function templates, and diagnose the non-template candidates 10602 // normally. 10603 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10604 IEnd = OvlExpr->decls_end(); 10605 I != IEnd; ++I) 10606 if (FunctionDecl *Fun = 10607 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10608 if (!functionHasPassObjectSizeParams(Fun)) 10609 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 10610 /*TakingAddress=*/true); 10611 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10612 } 10613 } 10614 10615 bool IsInvalidFormOfPointerToMemberFunction() const { 10616 return TargetTypeIsNonStaticMemberFunction && 10617 !OvlExprInfo.HasFormOfMemberPointer; 10618 } 10619 10620 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10621 // TODO: Should we condition this on whether any functions might 10622 // have matched, or is it more appropriate to do that in callers? 10623 // TODO: a fixit wouldn't hurt. 10624 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10625 << TargetType << OvlExpr->getSourceRange(); 10626 } 10627 10628 bool IsStaticMemberFunctionFromBoundPointer() const { 10629 return StaticMemberFunctionFromBoundPointer; 10630 } 10631 10632 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10633 S.Diag(OvlExpr->getLocStart(), 10634 diag::err_invalid_form_pointer_member_function) 10635 << OvlExpr->getSourceRange(); 10636 } 10637 10638 void ComplainOfInvalidConversion() const { 10639 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10640 << OvlExpr->getName() << TargetType; 10641 } 10642 10643 void ComplainMultipleMatchesFound() const { 10644 assert(Matches.size() > 1); 10645 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10646 << OvlExpr->getName() 10647 << OvlExpr->getSourceRange(); 10648 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10649 /*TakingAddress=*/true); 10650 } 10651 10652 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10653 10654 int getNumMatches() const { return Matches.size(); } 10655 10656 FunctionDecl* getMatchingFunctionDecl() const { 10657 if (Matches.size() != 1) return nullptr; 10658 return Matches[0].second; 10659 } 10660 10661 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10662 if (Matches.size() != 1) return nullptr; 10663 return &Matches[0].first; 10664 } 10665 }; 10666 } 10667 10668 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10669 /// an overloaded function (C++ [over.over]), where @p From is an 10670 /// expression with overloaded function type and @p ToType is the type 10671 /// we're trying to resolve to. For example: 10672 /// 10673 /// @code 10674 /// int f(double); 10675 /// int f(int); 10676 /// 10677 /// int (*pfd)(double) = f; // selects f(double) 10678 /// @endcode 10679 /// 10680 /// This routine returns the resulting FunctionDecl if it could be 10681 /// resolved, and NULL otherwise. When @p Complain is true, this 10682 /// routine will emit diagnostics if there is an error. 10683 FunctionDecl * 10684 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10685 QualType TargetType, 10686 bool Complain, 10687 DeclAccessPair &FoundResult, 10688 bool *pHadMultipleCandidates) { 10689 assert(AddressOfExpr->getType() == Context.OverloadTy); 10690 10691 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10692 Complain); 10693 int NumMatches = Resolver.getNumMatches(); 10694 FunctionDecl *Fn = nullptr; 10695 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10696 if (NumMatches == 0 && ShouldComplain) { 10697 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10698 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10699 else 10700 Resolver.ComplainNoMatchesFound(); 10701 } 10702 else if (NumMatches > 1 && ShouldComplain) 10703 Resolver.ComplainMultipleMatchesFound(); 10704 else if (NumMatches == 1) { 10705 Fn = Resolver.getMatchingFunctionDecl(); 10706 assert(Fn); 10707 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10708 if (Complain) { 10709 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10710 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10711 else 10712 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10713 } 10714 } 10715 10716 if (pHadMultipleCandidates) 10717 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10718 return Fn; 10719 } 10720 10721 /// \brief Given an expression that refers to an overloaded function, try to 10722 /// resolve that function to a single function that can have its address taken. 10723 /// This will modify `Pair` iff it returns non-null. 10724 /// 10725 /// This routine can only realistically succeed if all but one candidates in the 10726 /// overload set for SrcExpr cannot have their addresses taken. 10727 FunctionDecl * 10728 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10729 DeclAccessPair &Pair) { 10730 OverloadExpr::FindResult R = OverloadExpr::find(E); 10731 OverloadExpr *Ovl = R.Expression; 10732 FunctionDecl *Result = nullptr; 10733 DeclAccessPair DAP; 10734 // Don't use the AddressOfResolver because we're specifically looking for 10735 // cases where we have one overload candidate that lacks 10736 // enable_if/pass_object_size/... 10737 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10738 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10739 if (!FD) 10740 return nullptr; 10741 10742 if (!checkAddressOfFunctionIsAvailable(FD)) 10743 continue; 10744 10745 // We have more than one result; quit. 10746 if (Result) 10747 return nullptr; 10748 DAP = I.getPair(); 10749 Result = FD; 10750 } 10751 10752 if (Result) 10753 Pair = DAP; 10754 return Result; 10755 } 10756 10757 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 10758 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 10759 /// will perform access checks, diagnose the use of the resultant decl, and, if 10760 /// necessary, perform a function-to-pointer decay. 10761 /// 10762 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 10763 /// Otherwise, returns true. This may emit diagnostics and return true. 10764 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 10765 ExprResult &SrcExpr) { 10766 Expr *E = SrcExpr.get(); 10767 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 10768 10769 DeclAccessPair DAP; 10770 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 10771 if (!Found) 10772 return false; 10773 10774 // Emitting multiple diagnostics for a function that is both inaccessible and 10775 // unavailable is consistent with our behavior elsewhere. So, always check 10776 // for both. 10777 DiagnoseUseOfDecl(Found, E->getExprLoc()); 10778 CheckAddressOfMemberAccess(E, DAP); 10779 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 10780 if (Fixed->getType()->isFunctionType()) 10781 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 10782 else 10783 SrcExpr = Fixed; 10784 return true; 10785 } 10786 10787 /// \brief Given an expression that refers to an overloaded function, try to 10788 /// resolve that overloaded function expression down to a single function. 10789 /// 10790 /// This routine can only resolve template-ids that refer to a single function 10791 /// template, where that template-id refers to a single template whose template 10792 /// arguments are either provided by the template-id or have defaults, 10793 /// as described in C++0x [temp.arg.explicit]p3. 10794 /// 10795 /// If no template-ids are found, no diagnostics are emitted and NULL is 10796 /// returned. 10797 FunctionDecl * 10798 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10799 bool Complain, 10800 DeclAccessPair *FoundResult) { 10801 // C++ [over.over]p1: 10802 // [...] [Note: any redundant set of parentheses surrounding the 10803 // overloaded function name is ignored (5.1). ] 10804 // C++ [over.over]p1: 10805 // [...] The overloaded function name can be preceded by the & 10806 // operator. 10807 10808 // If we didn't actually find any template-ids, we're done. 10809 if (!ovl->hasExplicitTemplateArgs()) 10810 return nullptr; 10811 10812 TemplateArgumentListInfo ExplicitTemplateArgs; 10813 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10814 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10815 10816 // Look through all of the overloaded functions, searching for one 10817 // whose type matches exactly. 10818 FunctionDecl *Matched = nullptr; 10819 for (UnresolvedSetIterator I = ovl->decls_begin(), 10820 E = ovl->decls_end(); I != E; ++I) { 10821 // C++0x [temp.arg.explicit]p3: 10822 // [...] In contexts where deduction is done and fails, or in contexts 10823 // where deduction is not done, if a template argument list is 10824 // specified and it, along with any default template arguments, 10825 // identifies a single function template specialization, then the 10826 // template-id is an lvalue for the function template specialization. 10827 FunctionTemplateDecl *FunctionTemplate 10828 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10829 10830 // C++ [over.over]p2: 10831 // If the name is a function template, template argument deduction is 10832 // done (14.8.2.2), and if the argument deduction succeeds, the 10833 // resulting template argument list is used to generate a single 10834 // function template specialization, which is added to the set of 10835 // overloaded functions considered. 10836 FunctionDecl *Specialization = nullptr; 10837 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10838 if (TemplateDeductionResult Result 10839 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10840 Specialization, Info, 10841 /*InOverloadResolution=*/true)) { 10842 // Make a note of the failed deduction for diagnostics. 10843 // TODO: Actually use the failed-deduction info? 10844 FailedCandidates.addCandidate() 10845 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 10846 MakeDeductionFailureInfo(Context, Result, Info)); 10847 continue; 10848 } 10849 10850 assert(Specialization && "no specialization and no error?"); 10851 10852 // Multiple matches; we can't resolve to a single declaration. 10853 if (Matched) { 10854 if (Complain) { 10855 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10856 << ovl->getName(); 10857 NoteAllOverloadCandidates(ovl); 10858 } 10859 return nullptr; 10860 } 10861 10862 Matched = Specialization; 10863 if (FoundResult) *FoundResult = I.getPair(); 10864 } 10865 10866 if (Matched && getLangOpts().CPlusPlus14 && 10867 Matched->getReturnType()->isUndeducedType() && 10868 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10869 return nullptr; 10870 10871 return Matched; 10872 } 10873 10874 10875 10876 10877 // Resolve and fix an overloaded expression that can be resolved 10878 // because it identifies a single function template specialization. 10879 // 10880 // Last three arguments should only be supplied if Complain = true 10881 // 10882 // Return true if it was logically possible to so resolve the 10883 // expression, regardless of whether or not it succeeded. Always 10884 // returns true if 'complain' is set. 10885 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10886 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10887 bool complain, SourceRange OpRangeForComplaining, 10888 QualType DestTypeForComplaining, 10889 unsigned DiagIDForComplaining) { 10890 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10891 10892 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10893 10894 DeclAccessPair found; 10895 ExprResult SingleFunctionExpression; 10896 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10897 ovl.Expression, /*complain*/ false, &found)) { 10898 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10899 SrcExpr = ExprError(); 10900 return true; 10901 } 10902 10903 // It is only correct to resolve to an instance method if we're 10904 // resolving a form that's permitted to be a pointer to member. 10905 // Otherwise we'll end up making a bound member expression, which 10906 // is illegal in all the contexts we resolve like this. 10907 if (!ovl.HasFormOfMemberPointer && 10908 isa<CXXMethodDecl>(fn) && 10909 cast<CXXMethodDecl>(fn)->isInstance()) { 10910 if (!complain) return false; 10911 10912 Diag(ovl.Expression->getExprLoc(), 10913 diag::err_bound_member_function) 10914 << 0 << ovl.Expression->getSourceRange(); 10915 10916 // TODO: I believe we only end up here if there's a mix of 10917 // static and non-static candidates (otherwise the expression 10918 // would have 'bound member' type, not 'overload' type). 10919 // Ideally we would note which candidate was chosen and why 10920 // the static candidates were rejected. 10921 SrcExpr = ExprError(); 10922 return true; 10923 } 10924 10925 // Fix the expression to refer to 'fn'. 10926 SingleFunctionExpression = 10927 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10928 10929 // If desired, do function-to-pointer decay. 10930 if (doFunctionPointerConverion) { 10931 SingleFunctionExpression = 10932 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10933 if (SingleFunctionExpression.isInvalid()) { 10934 SrcExpr = ExprError(); 10935 return true; 10936 } 10937 } 10938 } 10939 10940 if (!SingleFunctionExpression.isUsable()) { 10941 if (complain) { 10942 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10943 << ovl.Expression->getName() 10944 << DestTypeForComplaining 10945 << OpRangeForComplaining 10946 << ovl.Expression->getQualifierLoc().getSourceRange(); 10947 NoteAllOverloadCandidates(SrcExpr.get()); 10948 10949 SrcExpr = ExprError(); 10950 return true; 10951 } 10952 10953 return false; 10954 } 10955 10956 SrcExpr = SingleFunctionExpression; 10957 return true; 10958 } 10959 10960 /// \brief Add a single candidate to the overload set. 10961 static void AddOverloadedCallCandidate(Sema &S, 10962 DeclAccessPair FoundDecl, 10963 TemplateArgumentListInfo *ExplicitTemplateArgs, 10964 ArrayRef<Expr *> Args, 10965 OverloadCandidateSet &CandidateSet, 10966 bool PartialOverloading, 10967 bool KnownValid) { 10968 NamedDecl *Callee = FoundDecl.getDecl(); 10969 if (isa<UsingShadowDecl>(Callee)) 10970 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10971 10972 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10973 if (ExplicitTemplateArgs) { 10974 assert(!KnownValid && "Explicit template arguments?"); 10975 return; 10976 } 10977 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10978 /*SuppressUsedConversions=*/false, 10979 PartialOverloading); 10980 return; 10981 } 10982 10983 if (FunctionTemplateDecl *FuncTemplate 10984 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10985 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10986 ExplicitTemplateArgs, Args, CandidateSet, 10987 /*SuppressUsedConversions=*/false, 10988 PartialOverloading); 10989 return; 10990 } 10991 10992 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10993 } 10994 10995 /// \brief Add the overload candidates named by callee and/or found by argument 10996 /// dependent lookup to the given overload set. 10997 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10998 ArrayRef<Expr *> Args, 10999 OverloadCandidateSet &CandidateSet, 11000 bool PartialOverloading) { 11001 11002 #ifndef NDEBUG 11003 // Verify that ArgumentDependentLookup is consistent with the rules 11004 // in C++0x [basic.lookup.argdep]p3: 11005 // 11006 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11007 // and let Y be the lookup set produced by argument dependent 11008 // lookup (defined as follows). If X contains 11009 // 11010 // -- a declaration of a class member, or 11011 // 11012 // -- a block-scope function declaration that is not a 11013 // using-declaration, or 11014 // 11015 // -- a declaration that is neither a function or a function 11016 // template 11017 // 11018 // then Y is empty. 11019 11020 if (ULE->requiresADL()) { 11021 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11022 E = ULE->decls_end(); I != E; ++I) { 11023 assert(!(*I)->getDeclContext()->isRecord()); 11024 assert(isa<UsingShadowDecl>(*I) || 11025 !(*I)->getDeclContext()->isFunctionOrMethod()); 11026 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11027 } 11028 } 11029 #endif 11030 11031 // It would be nice to avoid this copy. 11032 TemplateArgumentListInfo TABuffer; 11033 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11034 if (ULE->hasExplicitTemplateArgs()) { 11035 ULE->copyTemplateArgumentsInto(TABuffer); 11036 ExplicitTemplateArgs = &TABuffer; 11037 } 11038 11039 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11040 E = ULE->decls_end(); I != E; ++I) 11041 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11042 CandidateSet, PartialOverloading, 11043 /*KnownValid*/ true); 11044 11045 if (ULE->requiresADL()) 11046 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11047 Args, ExplicitTemplateArgs, 11048 CandidateSet, PartialOverloading); 11049 } 11050 11051 /// Determine whether a declaration with the specified name could be moved into 11052 /// a different namespace. 11053 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11054 switch (Name.getCXXOverloadedOperator()) { 11055 case OO_New: case OO_Array_New: 11056 case OO_Delete: case OO_Array_Delete: 11057 return false; 11058 11059 default: 11060 return true; 11061 } 11062 } 11063 11064 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11065 /// template, where the non-dependent name was declared after the template 11066 /// was defined. This is common in code written for a compilers which do not 11067 /// correctly implement two-stage name lookup. 11068 /// 11069 /// Returns true if a viable candidate was found and a diagnostic was issued. 11070 static bool 11071 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11072 const CXXScopeSpec &SS, LookupResult &R, 11073 OverloadCandidateSet::CandidateSetKind CSK, 11074 TemplateArgumentListInfo *ExplicitTemplateArgs, 11075 ArrayRef<Expr *> Args, 11076 bool *DoDiagnoseEmptyLookup = nullptr) { 11077 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11078 return false; 11079 11080 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11081 if (DC->isTransparentContext()) 11082 continue; 11083 11084 SemaRef.LookupQualifiedName(R, DC); 11085 11086 if (!R.empty()) { 11087 R.suppressDiagnostics(); 11088 11089 if (isa<CXXRecordDecl>(DC)) { 11090 // Don't diagnose names we find in classes; we get much better 11091 // diagnostics for these from DiagnoseEmptyLookup. 11092 R.clear(); 11093 if (DoDiagnoseEmptyLookup) 11094 *DoDiagnoseEmptyLookup = true; 11095 return false; 11096 } 11097 11098 OverloadCandidateSet Candidates(FnLoc, CSK); 11099 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11100 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11101 ExplicitTemplateArgs, Args, 11102 Candidates, false, /*KnownValid*/ false); 11103 11104 OverloadCandidateSet::iterator Best; 11105 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11106 // No viable functions. Don't bother the user with notes for functions 11107 // which don't work and shouldn't be found anyway. 11108 R.clear(); 11109 return false; 11110 } 11111 11112 // Find the namespaces where ADL would have looked, and suggest 11113 // declaring the function there instead. 11114 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11115 Sema::AssociatedClassSet AssociatedClasses; 11116 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11117 AssociatedNamespaces, 11118 AssociatedClasses); 11119 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11120 if (canBeDeclaredInNamespace(R.getLookupName())) { 11121 DeclContext *Std = SemaRef.getStdNamespace(); 11122 for (Sema::AssociatedNamespaceSet::iterator 11123 it = AssociatedNamespaces.begin(), 11124 end = AssociatedNamespaces.end(); it != end; ++it) { 11125 // Never suggest declaring a function within namespace 'std'. 11126 if (Std && Std->Encloses(*it)) 11127 continue; 11128 11129 // Never suggest declaring a function within a namespace with a 11130 // reserved name, like __gnu_cxx. 11131 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11132 if (NS && 11133 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11134 continue; 11135 11136 SuggestedNamespaces.insert(*it); 11137 } 11138 } 11139 11140 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11141 << R.getLookupName(); 11142 if (SuggestedNamespaces.empty()) { 11143 SemaRef.Diag(Best->Function->getLocation(), 11144 diag::note_not_found_by_two_phase_lookup) 11145 << R.getLookupName() << 0; 11146 } else if (SuggestedNamespaces.size() == 1) { 11147 SemaRef.Diag(Best->Function->getLocation(), 11148 diag::note_not_found_by_two_phase_lookup) 11149 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11150 } else { 11151 // FIXME: It would be useful to list the associated namespaces here, 11152 // but the diagnostics infrastructure doesn't provide a way to produce 11153 // a localized representation of a list of items. 11154 SemaRef.Diag(Best->Function->getLocation(), 11155 diag::note_not_found_by_two_phase_lookup) 11156 << R.getLookupName() << 2; 11157 } 11158 11159 // Try to recover by calling this function. 11160 return true; 11161 } 11162 11163 R.clear(); 11164 } 11165 11166 return false; 11167 } 11168 11169 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11170 /// template, where the non-dependent operator was declared after the template 11171 /// was defined. 11172 /// 11173 /// Returns true if a viable candidate was found and a diagnostic was issued. 11174 static bool 11175 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11176 SourceLocation OpLoc, 11177 ArrayRef<Expr *> Args) { 11178 DeclarationName OpName = 11179 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11180 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11181 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11182 OverloadCandidateSet::CSK_Operator, 11183 /*ExplicitTemplateArgs=*/nullptr, Args); 11184 } 11185 11186 namespace { 11187 class BuildRecoveryCallExprRAII { 11188 Sema &SemaRef; 11189 public: 11190 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11191 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11192 SemaRef.IsBuildingRecoveryCallExpr = true; 11193 } 11194 11195 ~BuildRecoveryCallExprRAII() { 11196 SemaRef.IsBuildingRecoveryCallExpr = false; 11197 } 11198 }; 11199 11200 } 11201 11202 static std::unique_ptr<CorrectionCandidateCallback> 11203 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11204 bool HasTemplateArgs, bool AllowTypoCorrection) { 11205 if (!AllowTypoCorrection) 11206 return llvm::make_unique<NoTypoCorrectionCCC>(); 11207 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11208 HasTemplateArgs, ME); 11209 } 11210 11211 /// Attempts to recover from a call where no functions were found. 11212 /// 11213 /// Returns true if new candidates were found. 11214 static ExprResult 11215 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11216 UnresolvedLookupExpr *ULE, 11217 SourceLocation LParenLoc, 11218 MutableArrayRef<Expr *> Args, 11219 SourceLocation RParenLoc, 11220 bool EmptyLookup, bool AllowTypoCorrection) { 11221 // Do not try to recover if it is already building a recovery call. 11222 // This stops infinite loops for template instantiations like 11223 // 11224 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11225 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11226 // 11227 if (SemaRef.IsBuildingRecoveryCallExpr) 11228 return ExprError(); 11229 BuildRecoveryCallExprRAII RCE(SemaRef); 11230 11231 CXXScopeSpec SS; 11232 SS.Adopt(ULE->getQualifierLoc()); 11233 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11234 11235 TemplateArgumentListInfo TABuffer; 11236 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11237 if (ULE->hasExplicitTemplateArgs()) { 11238 ULE->copyTemplateArgumentsInto(TABuffer); 11239 ExplicitTemplateArgs = &TABuffer; 11240 } 11241 11242 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11243 Sema::LookupOrdinaryName); 11244 bool DoDiagnoseEmptyLookup = EmptyLookup; 11245 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11246 OverloadCandidateSet::CSK_Normal, 11247 ExplicitTemplateArgs, Args, 11248 &DoDiagnoseEmptyLookup) && 11249 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11250 S, SS, R, 11251 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11252 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11253 ExplicitTemplateArgs, Args))) 11254 return ExprError(); 11255 11256 assert(!R.empty() && "lookup results empty despite recovery"); 11257 11258 // Build an implicit member call if appropriate. Just drop the 11259 // casts and such from the call, we don't really care. 11260 ExprResult NewFn = ExprError(); 11261 if ((*R.begin())->isCXXClassMember()) 11262 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11263 ExplicitTemplateArgs, S); 11264 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11265 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11266 ExplicitTemplateArgs); 11267 else 11268 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11269 11270 if (NewFn.isInvalid()) 11271 return ExprError(); 11272 11273 // This shouldn't cause an infinite loop because we're giving it 11274 // an expression with viable lookup results, which should never 11275 // end up here. 11276 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11277 MultiExprArg(Args.data(), Args.size()), 11278 RParenLoc); 11279 } 11280 11281 /// \brief Constructs and populates an OverloadedCandidateSet from 11282 /// the given function. 11283 /// \returns true when an the ExprResult output parameter has been set. 11284 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11285 UnresolvedLookupExpr *ULE, 11286 MultiExprArg Args, 11287 SourceLocation RParenLoc, 11288 OverloadCandidateSet *CandidateSet, 11289 ExprResult *Result) { 11290 #ifndef NDEBUG 11291 if (ULE->requiresADL()) { 11292 // To do ADL, we must have found an unqualified name. 11293 assert(!ULE->getQualifier() && "qualified name with ADL"); 11294 11295 // We don't perform ADL for implicit declarations of builtins. 11296 // Verify that this was correctly set up. 11297 FunctionDecl *F; 11298 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11299 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11300 F->getBuiltinID() && F->isImplicit()) 11301 llvm_unreachable("performing ADL for builtin"); 11302 11303 // We don't perform ADL in C. 11304 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11305 } 11306 #endif 11307 11308 UnbridgedCastsSet UnbridgedCasts; 11309 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11310 *Result = ExprError(); 11311 return true; 11312 } 11313 11314 // Add the functions denoted by the callee to the set of candidate 11315 // functions, including those from argument-dependent lookup. 11316 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11317 11318 if (getLangOpts().MSVCCompat && 11319 CurContext->isDependentContext() && !isSFINAEContext() && 11320 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11321 11322 OverloadCandidateSet::iterator Best; 11323 if (CandidateSet->empty() || 11324 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11325 OR_No_Viable_Function) { 11326 // In Microsoft mode, if we are inside a template class member function then 11327 // create a type dependent CallExpr. The goal is to postpone name lookup 11328 // to instantiation time to be able to search into type dependent base 11329 // classes. 11330 CallExpr *CE = new (Context) CallExpr( 11331 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11332 CE->setTypeDependent(true); 11333 CE->setValueDependent(true); 11334 CE->setInstantiationDependent(true); 11335 *Result = CE; 11336 return true; 11337 } 11338 } 11339 11340 if (CandidateSet->empty()) 11341 return false; 11342 11343 UnbridgedCasts.restore(); 11344 return false; 11345 } 11346 11347 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11348 /// the completed call expression. If overload resolution fails, emits 11349 /// diagnostics and returns ExprError() 11350 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11351 UnresolvedLookupExpr *ULE, 11352 SourceLocation LParenLoc, 11353 MultiExprArg Args, 11354 SourceLocation RParenLoc, 11355 Expr *ExecConfig, 11356 OverloadCandidateSet *CandidateSet, 11357 OverloadCandidateSet::iterator *Best, 11358 OverloadingResult OverloadResult, 11359 bool AllowTypoCorrection) { 11360 if (CandidateSet->empty()) 11361 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11362 RParenLoc, /*EmptyLookup=*/true, 11363 AllowTypoCorrection); 11364 11365 switch (OverloadResult) { 11366 case OR_Success: { 11367 FunctionDecl *FDecl = (*Best)->Function; 11368 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11369 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11370 return ExprError(); 11371 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11372 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11373 ExecConfig); 11374 } 11375 11376 case OR_No_Viable_Function: { 11377 // Try to recover by looking for viable functions which the user might 11378 // have meant to call. 11379 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11380 Args, RParenLoc, 11381 /*EmptyLookup=*/false, 11382 AllowTypoCorrection); 11383 if (!Recovery.isInvalid()) 11384 return Recovery; 11385 11386 // If the user passes in a function that we can't take the address of, we 11387 // generally end up emitting really bad error messages. Here, we attempt to 11388 // emit better ones. 11389 for (const Expr *Arg : Args) { 11390 if (!Arg->getType()->isFunctionType()) 11391 continue; 11392 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11393 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11394 if (FD && 11395 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11396 Arg->getExprLoc())) 11397 return ExprError(); 11398 } 11399 } 11400 11401 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11402 << ULE->getName() << Fn->getSourceRange(); 11403 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11404 break; 11405 } 11406 11407 case OR_Ambiguous: 11408 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11409 << ULE->getName() << Fn->getSourceRange(); 11410 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11411 break; 11412 11413 case OR_Deleted: { 11414 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11415 << (*Best)->Function->isDeleted() 11416 << ULE->getName() 11417 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11418 << Fn->getSourceRange(); 11419 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11420 11421 // We emitted an error for the unvailable/deleted function call but keep 11422 // the call in the AST. 11423 FunctionDecl *FDecl = (*Best)->Function; 11424 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11425 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11426 ExecConfig); 11427 } 11428 } 11429 11430 // Overload resolution failed. 11431 return ExprError(); 11432 } 11433 11434 static void markUnaddressableCandidatesUnviable(Sema &S, 11435 OverloadCandidateSet &CS) { 11436 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11437 if (I->Viable && 11438 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11439 I->Viable = false; 11440 I->FailureKind = ovl_fail_addr_not_available; 11441 } 11442 } 11443 } 11444 11445 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11446 /// (which eventually refers to the declaration Func) and the call 11447 /// arguments Args/NumArgs, attempt to resolve the function call down 11448 /// to a specific function. If overload resolution succeeds, returns 11449 /// the call expression produced by overload resolution. 11450 /// Otherwise, emits diagnostics and returns ExprError. 11451 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11452 UnresolvedLookupExpr *ULE, 11453 SourceLocation LParenLoc, 11454 MultiExprArg Args, 11455 SourceLocation RParenLoc, 11456 Expr *ExecConfig, 11457 bool AllowTypoCorrection, 11458 bool CalleesAddressIsTaken) { 11459 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11460 OverloadCandidateSet::CSK_Normal); 11461 ExprResult result; 11462 11463 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11464 &result)) 11465 return result; 11466 11467 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11468 // functions that aren't addressible are considered unviable. 11469 if (CalleesAddressIsTaken) 11470 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11471 11472 OverloadCandidateSet::iterator Best; 11473 OverloadingResult OverloadResult = 11474 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11475 11476 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11477 RParenLoc, ExecConfig, &CandidateSet, 11478 &Best, OverloadResult, 11479 AllowTypoCorrection); 11480 } 11481 11482 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11483 return Functions.size() > 1 || 11484 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11485 } 11486 11487 /// \brief Create a unary operation that may resolve to an overloaded 11488 /// operator. 11489 /// 11490 /// \param OpLoc The location of the operator itself (e.g., '*'). 11491 /// 11492 /// \param Opc The UnaryOperatorKind that describes this operator. 11493 /// 11494 /// \param Fns The set of non-member functions that will be 11495 /// considered by overload resolution. The caller needs to build this 11496 /// set based on the context using, e.g., 11497 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11498 /// set should not contain any member functions; those will be added 11499 /// by CreateOverloadedUnaryOp(). 11500 /// 11501 /// \param Input The input argument. 11502 ExprResult 11503 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11504 const UnresolvedSetImpl &Fns, 11505 Expr *Input) { 11506 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11507 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11508 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11509 // TODO: provide better source location info. 11510 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11511 11512 if (checkPlaceholderForOverload(*this, Input)) 11513 return ExprError(); 11514 11515 Expr *Args[2] = { Input, nullptr }; 11516 unsigned NumArgs = 1; 11517 11518 // For post-increment and post-decrement, add the implicit '0' as 11519 // the second argument, so that we know this is a post-increment or 11520 // post-decrement. 11521 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11522 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11523 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11524 SourceLocation()); 11525 NumArgs = 2; 11526 } 11527 11528 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11529 11530 if (Input->isTypeDependent()) { 11531 if (Fns.empty()) 11532 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11533 VK_RValue, OK_Ordinary, OpLoc); 11534 11535 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11536 UnresolvedLookupExpr *Fn 11537 = UnresolvedLookupExpr::Create(Context, NamingClass, 11538 NestedNameSpecifierLoc(), OpNameInfo, 11539 /*ADL*/ true, IsOverloaded(Fns), 11540 Fns.begin(), Fns.end()); 11541 return new (Context) 11542 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11543 VK_RValue, OpLoc, false); 11544 } 11545 11546 // Build an empty overload set. 11547 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11548 11549 // Add the candidates from the given function set. 11550 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11551 11552 // Add operator candidates that are member functions. 11553 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11554 11555 // Add candidates from ADL. 11556 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11557 /*ExplicitTemplateArgs*/nullptr, 11558 CandidateSet); 11559 11560 // Add builtin operator candidates. 11561 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11562 11563 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11564 11565 // Perform overload resolution. 11566 OverloadCandidateSet::iterator Best; 11567 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11568 case OR_Success: { 11569 // We found a built-in operator or an overloaded operator. 11570 FunctionDecl *FnDecl = Best->Function; 11571 11572 if (FnDecl) { 11573 // We matched an overloaded operator. Build a call to that 11574 // operator. 11575 11576 // Convert the arguments. 11577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11578 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11579 11580 ExprResult InputRes = 11581 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11582 Best->FoundDecl, Method); 11583 if (InputRes.isInvalid()) 11584 return ExprError(); 11585 Input = InputRes.get(); 11586 } else { 11587 // Convert the arguments. 11588 ExprResult InputInit 11589 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11590 Context, 11591 FnDecl->getParamDecl(0)), 11592 SourceLocation(), 11593 Input); 11594 if (InputInit.isInvalid()) 11595 return ExprError(); 11596 Input = InputInit.get(); 11597 } 11598 11599 // Build the actual expression node. 11600 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11601 HadMultipleCandidates, OpLoc); 11602 if (FnExpr.isInvalid()) 11603 return ExprError(); 11604 11605 // Determine the result type. 11606 QualType ResultTy = FnDecl->getReturnType(); 11607 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11608 ResultTy = ResultTy.getNonLValueExprType(Context); 11609 11610 Args[0] = Input; 11611 CallExpr *TheCall = 11612 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11613 ResultTy, VK, OpLoc, false); 11614 11615 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11616 return ExprError(); 11617 11618 return MaybeBindToTemporary(TheCall); 11619 } else { 11620 // We matched a built-in operator. Convert the arguments, then 11621 // break out so that we will build the appropriate built-in 11622 // operator node. 11623 ExprResult InputRes = 11624 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11625 Best->Conversions[0], AA_Passing); 11626 if (InputRes.isInvalid()) 11627 return ExprError(); 11628 Input = InputRes.get(); 11629 break; 11630 } 11631 } 11632 11633 case OR_No_Viable_Function: 11634 // This is an erroneous use of an operator which can be overloaded by 11635 // a non-member function. Check for non-member operators which were 11636 // defined too late to be candidates. 11637 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11638 // FIXME: Recover by calling the found function. 11639 return ExprError(); 11640 11641 // No viable function; fall through to handling this as a 11642 // built-in operator, which will produce an error message for us. 11643 break; 11644 11645 case OR_Ambiguous: 11646 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11647 << UnaryOperator::getOpcodeStr(Opc) 11648 << Input->getType() 11649 << Input->getSourceRange(); 11650 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11651 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11652 return ExprError(); 11653 11654 case OR_Deleted: 11655 Diag(OpLoc, diag::err_ovl_deleted_oper) 11656 << Best->Function->isDeleted() 11657 << UnaryOperator::getOpcodeStr(Opc) 11658 << getDeletedOrUnavailableSuffix(Best->Function) 11659 << Input->getSourceRange(); 11660 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11661 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11662 return ExprError(); 11663 } 11664 11665 // Either we found no viable overloaded operator or we matched a 11666 // built-in operator. In either case, fall through to trying to 11667 // build a built-in operation. 11668 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11669 } 11670 11671 /// \brief Create a binary operation that may resolve to an overloaded 11672 /// operator. 11673 /// 11674 /// \param OpLoc The location of the operator itself (e.g., '+'). 11675 /// 11676 /// \param Opc The BinaryOperatorKind that describes this operator. 11677 /// 11678 /// \param Fns The set of non-member functions that will be 11679 /// considered by overload resolution. The caller needs to build this 11680 /// set based on the context using, e.g., 11681 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11682 /// set should not contain any member functions; those will be added 11683 /// by CreateOverloadedBinOp(). 11684 /// 11685 /// \param LHS Left-hand argument. 11686 /// \param RHS Right-hand argument. 11687 ExprResult 11688 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11689 BinaryOperatorKind Opc, 11690 const UnresolvedSetImpl &Fns, 11691 Expr *LHS, Expr *RHS) { 11692 Expr *Args[2] = { LHS, RHS }; 11693 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11694 11695 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11696 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11697 11698 // If either side is type-dependent, create an appropriate dependent 11699 // expression. 11700 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11701 if (Fns.empty()) { 11702 // If there are no functions to store, just build a dependent 11703 // BinaryOperator or CompoundAssignment. 11704 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11705 return new (Context) BinaryOperator( 11706 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11707 OpLoc, FPFeatures.fp_contract); 11708 11709 return new (Context) CompoundAssignOperator( 11710 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11711 Context.DependentTy, Context.DependentTy, OpLoc, 11712 FPFeatures.fp_contract); 11713 } 11714 11715 // FIXME: save results of ADL from here? 11716 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11717 // TODO: provide better source location info in DNLoc component. 11718 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11719 UnresolvedLookupExpr *Fn 11720 = UnresolvedLookupExpr::Create(Context, NamingClass, 11721 NestedNameSpecifierLoc(), OpNameInfo, 11722 /*ADL*/ true, IsOverloaded(Fns), 11723 Fns.begin(), Fns.end()); 11724 return new (Context) 11725 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11726 VK_RValue, OpLoc, FPFeatures.fp_contract); 11727 } 11728 11729 // Always do placeholder-like conversions on the RHS. 11730 if (checkPlaceholderForOverload(*this, Args[1])) 11731 return ExprError(); 11732 11733 // Do placeholder-like conversion on the LHS; note that we should 11734 // not get here with a PseudoObject LHS. 11735 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11736 if (checkPlaceholderForOverload(*this, Args[0])) 11737 return ExprError(); 11738 11739 // If this is the assignment operator, we only perform overload resolution 11740 // if the left-hand side is a class or enumeration type. This is actually 11741 // a hack. The standard requires that we do overload resolution between the 11742 // various built-in candidates, but as DR507 points out, this can lead to 11743 // problems. So we do it this way, which pretty much follows what GCC does. 11744 // Note that we go the traditional code path for compound assignment forms. 11745 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11746 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11747 11748 // If this is the .* operator, which is not overloadable, just 11749 // create a built-in binary operator. 11750 if (Opc == BO_PtrMemD) 11751 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11752 11753 // Build an empty overload set. 11754 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11755 11756 // Add the candidates from the given function set. 11757 AddFunctionCandidates(Fns, Args, CandidateSet); 11758 11759 // Add operator candidates that are member functions. 11760 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11761 11762 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11763 // performed for an assignment operator (nor for operator[] nor operator->, 11764 // which don't get here). 11765 if (Opc != BO_Assign) 11766 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11767 /*ExplicitTemplateArgs*/ nullptr, 11768 CandidateSet); 11769 11770 // Add builtin operator candidates. 11771 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11772 11773 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11774 11775 // Perform overload resolution. 11776 OverloadCandidateSet::iterator Best; 11777 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11778 case OR_Success: { 11779 // We found a built-in operator or an overloaded operator. 11780 FunctionDecl *FnDecl = Best->Function; 11781 11782 if (FnDecl) { 11783 // We matched an overloaded operator. Build a call to that 11784 // operator. 11785 11786 // Convert the arguments. 11787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11788 // Best->Access is only meaningful for class members. 11789 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11790 11791 ExprResult Arg1 = 11792 PerformCopyInitialization( 11793 InitializedEntity::InitializeParameter(Context, 11794 FnDecl->getParamDecl(0)), 11795 SourceLocation(), Args[1]); 11796 if (Arg1.isInvalid()) 11797 return ExprError(); 11798 11799 ExprResult Arg0 = 11800 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11801 Best->FoundDecl, Method); 11802 if (Arg0.isInvalid()) 11803 return ExprError(); 11804 Args[0] = Arg0.getAs<Expr>(); 11805 Args[1] = RHS = Arg1.getAs<Expr>(); 11806 } else { 11807 // Convert the arguments. 11808 ExprResult Arg0 = PerformCopyInitialization( 11809 InitializedEntity::InitializeParameter(Context, 11810 FnDecl->getParamDecl(0)), 11811 SourceLocation(), Args[0]); 11812 if (Arg0.isInvalid()) 11813 return ExprError(); 11814 11815 ExprResult Arg1 = 11816 PerformCopyInitialization( 11817 InitializedEntity::InitializeParameter(Context, 11818 FnDecl->getParamDecl(1)), 11819 SourceLocation(), Args[1]); 11820 if (Arg1.isInvalid()) 11821 return ExprError(); 11822 Args[0] = LHS = Arg0.getAs<Expr>(); 11823 Args[1] = RHS = Arg1.getAs<Expr>(); 11824 } 11825 11826 // Build the actual expression node. 11827 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11828 Best->FoundDecl, 11829 HadMultipleCandidates, OpLoc); 11830 if (FnExpr.isInvalid()) 11831 return ExprError(); 11832 11833 // Determine the result type. 11834 QualType ResultTy = FnDecl->getReturnType(); 11835 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11836 ResultTy = ResultTy.getNonLValueExprType(Context); 11837 11838 CXXOperatorCallExpr *TheCall = 11839 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11840 Args, ResultTy, VK, OpLoc, 11841 FPFeatures.fp_contract); 11842 11843 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11844 FnDecl)) 11845 return ExprError(); 11846 11847 ArrayRef<const Expr *> ArgsArray(Args, 2); 11848 // Cut off the implicit 'this'. 11849 if (isa<CXXMethodDecl>(FnDecl)) 11850 ArgsArray = ArgsArray.slice(1); 11851 11852 // Check for a self move. 11853 if (Op == OO_Equal) 11854 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11855 11856 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11857 TheCall->getSourceRange(), VariadicDoesNotApply); 11858 11859 return MaybeBindToTemporary(TheCall); 11860 } else { 11861 // We matched a built-in operator. Convert the arguments, then 11862 // break out so that we will build the appropriate built-in 11863 // operator node. 11864 ExprResult ArgsRes0 = 11865 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11866 Best->Conversions[0], AA_Passing); 11867 if (ArgsRes0.isInvalid()) 11868 return ExprError(); 11869 Args[0] = ArgsRes0.get(); 11870 11871 ExprResult ArgsRes1 = 11872 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11873 Best->Conversions[1], AA_Passing); 11874 if (ArgsRes1.isInvalid()) 11875 return ExprError(); 11876 Args[1] = ArgsRes1.get(); 11877 break; 11878 } 11879 } 11880 11881 case OR_No_Viable_Function: { 11882 // C++ [over.match.oper]p9: 11883 // If the operator is the operator , [...] and there are no 11884 // viable functions, then the operator is assumed to be the 11885 // built-in operator and interpreted according to clause 5. 11886 if (Opc == BO_Comma) 11887 break; 11888 11889 // For class as left operand for assignment or compound assigment 11890 // operator do not fall through to handling in built-in, but report that 11891 // no overloaded assignment operator found 11892 ExprResult Result = ExprError(); 11893 if (Args[0]->getType()->isRecordType() && 11894 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11895 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11896 << BinaryOperator::getOpcodeStr(Opc) 11897 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11898 if (Args[0]->getType()->isIncompleteType()) { 11899 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11900 << Args[0]->getType() 11901 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11902 } 11903 } else { 11904 // This is an erroneous use of an operator which can be overloaded by 11905 // a non-member function. Check for non-member operators which were 11906 // defined too late to be candidates. 11907 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11908 // FIXME: Recover by calling the found function. 11909 return ExprError(); 11910 11911 // No viable function; try to create a built-in operation, which will 11912 // produce an error. Then, show the non-viable candidates. 11913 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11914 } 11915 assert(Result.isInvalid() && 11916 "C++ binary operator overloading is missing candidates!"); 11917 if (Result.isInvalid()) 11918 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11919 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11920 return Result; 11921 } 11922 11923 case OR_Ambiguous: 11924 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11925 << BinaryOperator::getOpcodeStr(Opc) 11926 << Args[0]->getType() << Args[1]->getType() 11927 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11928 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11929 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11930 return ExprError(); 11931 11932 case OR_Deleted: 11933 if (isImplicitlyDeleted(Best->Function)) { 11934 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11935 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11936 << Context.getRecordType(Method->getParent()) 11937 << getSpecialMember(Method); 11938 11939 // The user probably meant to call this special member. Just 11940 // explain why it's deleted. 11941 NoteDeletedFunction(Method); 11942 return ExprError(); 11943 } else { 11944 Diag(OpLoc, diag::err_ovl_deleted_oper) 11945 << Best->Function->isDeleted() 11946 << BinaryOperator::getOpcodeStr(Opc) 11947 << getDeletedOrUnavailableSuffix(Best->Function) 11948 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11949 } 11950 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11951 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11952 return ExprError(); 11953 } 11954 11955 // We matched a built-in operator; build it. 11956 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11957 } 11958 11959 ExprResult 11960 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11961 SourceLocation RLoc, 11962 Expr *Base, Expr *Idx) { 11963 Expr *Args[2] = { Base, Idx }; 11964 DeclarationName OpName = 11965 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11966 11967 // If either side is type-dependent, create an appropriate dependent 11968 // expression. 11969 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11970 11971 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11972 // CHECKME: no 'operator' keyword? 11973 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11974 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11975 UnresolvedLookupExpr *Fn 11976 = UnresolvedLookupExpr::Create(Context, NamingClass, 11977 NestedNameSpecifierLoc(), OpNameInfo, 11978 /*ADL*/ true, /*Overloaded*/ false, 11979 UnresolvedSetIterator(), 11980 UnresolvedSetIterator()); 11981 // Can't add any actual overloads yet 11982 11983 return new (Context) 11984 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11985 Context.DependentTy, VK_RValue, RLoc, false); 11986 } 11987 11988 // Handle placeholders on both operands. 11989 if (checkPlaceholderForOverload(*this, Args[0])) 11990 return ExprError(); 11991 if (checkPlaceholderForOverload(*this, Args[1])) 11992 return ExprError(); 11993 11994 // Build an empty overload set. 11995 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11996 11997 // Subscript can only be overloaded as a member function. 11998 11999 // Add operator candidates that are member functions. 12000 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12001 12002 // Add builtin operator candidates. 12003 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12004 12005 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12006 12007 // Perform overload resolution. 12008 OverloadCandidateSet::iterator Best; 12009 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12010 case OR_Success: { 12011 // We found a built-in operator or an overloaded operator. 12012 FunctionDecl *FnDecl = Best->Function; 12013 12014 if (FnDecl) { 12015 // We matched an overloaded operator. Build a call to that 12016 // operator. 12017 12018 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12019 12020 // Convert the arguments. 12021 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12022 ExprResult Arg0 = 12023 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12024 Best->FoundDecl, Method); 12025 if (Arg0.isInvalid()) 12026 return ExprError(); 12027 Args[0] = Arg0.get(); 12028 12029 // Convert the arguments. 12030 ExprResult InputInit 12031 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12032 Context, 12033 FnDecl->getParamDecl(0)), 12034 SourceLocation(), 12035 Args[1]); 12036 if (InputInit.isInvalid()) 12037 return ExprError(); 12038 12039 Args[1] = InputInit.getAs<Expr>(); 12040 12041 // Build the actual expression node. 12042 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12043 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12044 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12045 Best->FoundDecl, 12046 HadMultipleCandidates, 12047 OpLocInfo.getLoc(), 12048 OpLocInfo.getInfo()); 12049 if (FnExpr.isInvalid()) 12050 return ExprError(); 12051 12052 // Determine the result type 12053 QualType ResultTy = FnDecl->getReturnType(); 12054 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12055 ResultTy = ResultTy.getNonLValueExprType(Context); 12056 12057 CXXOperatorCallExpr *TheCall = 12058 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12059 FnExpr.get(), Args, 12060 ResultTy, VK, RLoc, 12061 false); 12062 12063 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12064 return ExprError(); 12065 12066 return MaybeBindToTemporary(TheCall); 12067 } else { 12068 // We matched a built-in operator. Convert the arguments, then 12069 // break out so that we will build the appropriate built-in 12070 // operator node. 12071 ExprResult ArgsRes0 = 12072 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12073 Best->Conversions[0], AA_Passing); 12074 if (ArgsRes0.isInvalid()) 12075 return ExprError(); 12076 Args[0] = ArgsRes0.get(); 12077 12078 ExprResult ArgsRes1 = 12079 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12080 Best->Conversions[1], AA_Passing); 12081 if (ArgsRes1.isInvalid()) 12082 return ExprError(); 12083 Args[1] = ArgsRes1.get(); 12084 12085 break; 12086 } 12087 } 12088 12089 case OR_No_Viable_Function: { 12090 if (CandidateSet.empty()) 12091 Diag(LLoc, diag::err_ovl_no_oper) 12092 << Args[0]->getType() << /*subscript*/ 0 12093 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12094 else 12095 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12096 << Args[0]->getType() 12097 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12098 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12099 "[]", LLoc); 12100 return ExprError(); 12101 } 12102 12103 case OR_Ambiguous: 12104 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12105 << "[]" 12106 << Args[0]->getType() << Args[1]->getType() 12107 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12108 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12109 "[]", LLoc); 12110 return ExprError(); 12111 12112 case OR_Deleted: 12113 Diag(LLoc, diag::err_ovl_deleted_oper) 12114 << Best->Function->isDeleted() << "[]" 12115 << getDeletedOrUnavailableSuffix(Best->Function) 12116 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12117 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12118 "[]", LLoc); 12119 return ExprError(); 12120 } 12121 12122 // We matched a built-in operator; build it. 12123 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12124 } 12125 12126 /// BuildCallToMemberFunction - Build a call to a member 12127 /// function. MemExpr is the expression that refers to the member 12128 /// function (and includes the object parameter), Args/NumArgs are the 12129 /// arguments to the function call (not including the object 12130 /// parameter). The caller needs to validate that the member 12131 /// expression refers to a non-static member function or an overloaded 12132 /// member function. 12133 ExprResult 12134 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12135 SourceLocation LParenLoc, 12136 MultiExprArg Args, 12137 SourceLocation RParenLoc) { 12138 assert(MemExprE->getType() == Context.BoundMemberTy || 12139 MemExprE->getType() == Context.OverloadTy); 12140 12141 // Dig out the member expression. This holds both the object 12142 // argument and the member function we're referring to. 12143 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12144 12145 // Determine whether this is a call to a pointer-to-member function. 12146 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12147 assert(op->getType() == Context.BoundMemberTy); 12148 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12149 12150 QualType fnType = 12151 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12152 12153 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12154 QualType resultType = proto->getCallResultType(Context); 12155 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12156 12157 // Check that the object type isn't more qualified than the 12158 // member function we're calling. 12159 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12160 12161 QualType objectType = op->getLHS()->getType(); 12162 if (op->getOpcode() == BO_PtrMemI) 12163 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12164 Qualifiers objectQuals = objectType.getQualifiers(); 12165 12166 Qualifiers difference = objectQuals - funcQuals; 12167 difference.removeObjCGCAttr(); 12168 difference.removeAddressSpace(); 12169 if (difference) { 12170 std::string qualsString = difference.getAsString(); 12171 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12172 << fnType.getUnqualifiedType() 12173 << qualsString 12174 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12175 } 12176 12177 CXXMemberCallExpr *call 12178 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12179 resultType, valueKind, RParenLoc); 12180 12181 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12182 call, nullptr)) 12183 return ExprError(); 12184 12185 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12186 return ExprError(); 12187 12188 if (CheckOtherCall(call, proto)) 12189 return ExprError(); 12190 12191 return MaybeBindToTemporary(call); 12192 } 12193 12194 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12195 return new (Context) 12196 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12197 12198 UnbridgedCastsSet UnbridgedCasts; 12199 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12200 return ExprError(); 12201 12202 MemberExpr *MemExpr; 12203 CXXMethodDecl *Method = nullptr; 12204 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12205 NestedNameSpecifier *Qualifier = nullptr; 12206 if (isa<MemberExpr>(NakedMemExpr)) { 12207 MemExpr = cast<MemberExpr>(NakedMemExpr); 12208 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12209 FoundDecl = MemExpr->getFoundDecl(); 12210 Qualifier = MemExpr->getQualifier(); 12211 UnbridgedCasts.restore(); 12212 } else { 12213 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12214 Qualifier = UnresExpr->getQualifier(); 12215 12216 QualType ObjectType = UnresExpr->getBaseType(); 12217 Expr::Classification ObjectClassification 12218 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12219 : UnresExpr->getBase()->Classify(Context); 12220 12221 // Add overload candidates 12222 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12223 OverloadCandidateSet::CSK_Normal); 12224 12225 // FIXME: avoid copy. 12226 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12227 if (UnresExpr->hasExplicitTemplateArgs()) { 12228 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12229 TemplateArgs = &TemplateArgsBuffer; 12230 } 12231 12232 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12233 E = UnresExpr->decls_end(); I != E; ++I) { 12234 12235 NamedDecl *Func = *I; 12236 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12237 if (isa<UsingShadowDecl>(Func)) 12238 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12239 12240 12241 // Microsoft supports direct constructor calls. 12242 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12243 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12244 Args, CandidateSet); 12245 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12246 // If explicit template arguments were provided, we can't call a 12247 // non-template member function. 12248 if (TemplateArgs) 12249 continue; 12250 12251 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12252 ObjectClassification, Args, CandidateSet, 12253 /*SuppressUserConversions=*/false); 12254 } else { 12255 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12256 I.getPair(), ActingDC, TemplateArgs, 12257 ObjectType, ObjectClassification, 12258 Args, CandidateSet, 12259 /*SuppressUsedConversions=*/false); 12260 } 12261 } 12262 12263 DeclarationName DeclName = UnresExpr->getMemberName(); 12264 12265 UnbridgedCasts.restore(); 12266 12267 OverloadCandidateSet::iterator Best; 12268 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12269 Best)) { 12270 case OR_Success: 12271 Method = cast<CXXMethodDecl>(Best->Function); 12272 FoundDecl = Best->FoundDecl; 12273 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12274 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12275 return ExprError(); 12276 // If FoundDecl is different from Method (such as if one is a template 12277 // and the other a specialization), make sure DiagnoseUseOfDecl is 12278 // called on both. 12279 // FIXME: This would be more comprehensively addressed by modifying 12280 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12281 // being used. 12282 if (Method != FoundDecl.getDecl() && 12283 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12284 return ExprError(); 12285 break; 12286 12287 case OR_No_Viable_Function: 12288 Diag(UnresExpr->getMemberLoc(), 12289 diag::err_ovl_no_viable_member_function_in_call) 12290 << DeclName << MemExprE->getSourceRange(); 12291 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12292 // FIXME: Leaking incoming expressions! 12293 return ExprError(); 12294 12295 case OR_Ambiguous: 12296 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12297 << DeclName << MemExprE->getSourceRange(); 12298 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12299 // FIXME: Leaking incoming expressions! 12300 return ExprError(); 12301 12302 case OR_Deleted: 12303 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12304 << Best->Function->isDeleted() 12305 << DeclName 12306 << getDeletedOrUnavailableSuffix(Best->Function) 12307 << MemExprE->getSourceRange(); 12308 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12309 // FIXME: Leaking incoming expressions! 12310 return ExprError(); 12311 } 12312 12313 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12314 12315 // If overload resolution picked a static member, build a 12316 // non-member call based on that function. 12317 if (Method->isStatic()) { 12318 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12319 RParenLoc); 12320 } 12321 12322 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12323 } 12324 12325 QualType ResultType = Method->getReturnType(); 12326 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12327 ResultType = ResultType.getNonLValueExprType(Context); 12328 12329 assert(Method && "Member call to something that isn't a method?"); 12330 CXXMemberCallExpr *TheCall = 12331 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12332 ResultType, VK, RParenLoc); 12333 12334 // Check for a valid return type. 12335 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12336 TheCall, Method)) 12337 return ExprError(); 12338 12339 // Convert the object argument (for a non-static member function call). 12340 // We only need to do this if there was actually an overload; otherwise 12341 // it was done at lookup. 12342 if (!Method->isStatic()) { 12343 ExprResult ObjectArg = 12344 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12345 FoundDecl, Method); 12346 if (ObjectArg.isInvalid()) 12347 return ExprError(); 12348 MemExpr->setBase(ObjectArg.get()); 12349 } 12350 12351 // Convert the rest of the arguments 12352 const FunctionProtoType *Proto = 12353 Method->getType()->getAs<FunctionProtoType>(); 12354 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12355 RParenLoc)) 12356 return ExprError(); 12357 12358 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12359 12360 if (CheckFunctionCall(Method, TheCall, Proto)) 12361 return ExprError(); 12362 12363 // In the case the method to call was not selected by the overloading 12364 // resolution process, we still need to handle the enable_if attribute. Do 12365 // that here, so it will not hide previous -- and more relevant -- errors 12366 if (isa<MemberExpr>(NakedMemExpr)) { 12367 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12368 Diag(MemExprE->getLocStart(), 12369 diag::err_ovl_no_viable_member_function_in_call) 12370 << Method << Method->getSourceRange(); 12371 Diag(Method->getLocation(), 12372 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12373 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12374 return ExprError(); 12375 } 12376 } 12377 12378 if ((isa<CXXConstructorDecl>(CurContext) || 12379 isa<CXXDestructorDecl>(CurContext)) && 12380 TheCall->getMethodDecl()->isPure()) { 12381 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12382 12383 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12384 MemExpr->performsVirtualDispatch(getLangOpts())) { 12385 Diag(MemExpr->getLocStart(), 12386 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12387 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12388 << MD->getParent()->getDeclName(); 12389 12390 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12391 if (getLangOpts().AppleKext) 12392 Diag(MemExpr->getLocStart(), 12393 diag::note_pure_qualified_call_kext) 12394 << MD->getParent()->getDeclName() 12395 << MD->getDeclName(); 12396 } 12397 } 12398 12399 if (CXXDestructorDecl *DD = 12400 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12401 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12402 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12403 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12404 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12405 MemExpr->getMemberLoc()); 12406 } 12407 12408 return MaybeBindToTemporary(TheCall); 12409 } 12410 12411 /// BuildCallToObjectOfClassType - Build a call to an object of class 12412 /// type (C++ [over.call.object]), which can end up invoking an 12413 /// overloaded function call operator (@c operator()) or performing a 12414 /// user-defined conversion on the object argument. 12415 ExprResult 12416 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12417 SourceLocation LParenLoc, 12418 MultiExprArg Args, 12419 SourceLocation RParenLoc) { 12420 if (checkPlaceholderForOverload(*this, Obj)) 12421 return ExprError(); 12422 ExprResult Object = Obj; 12423 12424 UnbridgedCastsSet UnbridgedCasts; 12425 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12426 return ExprError(); 12427 12428 assert(Object.get()->getType()->isRecordType() && 12429 "Requires object type argument"); 12430 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12431 12432 // C++ [over.call.object]p1: 12433 // If the primary-expression E in the function call syntax 12434 // evaluates to a class object of type "cv T", then the set of 12435 // candidate functions includes at least the function call 12436 // operators of T. The function call operators of T are obtained by 12437 // ordinary lookup of the name operator() in the context of 12438 // (E).operator(). 12439 OverloadCandidateSet CandidateSet(LParenLoc, 12440 OverloadCandidateSet::CSK_Operator); 12441 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12442 12443 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12444 diag::err_incomplete_object_call, Object.get())) 12445 return true; 12446 12447 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12448 LookupQualifiedName(R, Record->getDecl()); 12449 R.suppressDiagnostics(); 12450 12451 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12452 Oper != OperEnd; ++Oper) { 12453 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12454 Object.get()->Classify(Context), 12455 Args, CandidateSet, 12456 /*SuppressUserConversions=*/ false); 12457 } 12458 12459 // C++ [over.call.object]p2: 12460 // In addition, for each (non-explicit in C++0x) conversion function 12461 // declared in T of the form 12462 // 12463 // operator conversion-type-id () cv-qualifier; 12464 // 12465 // where cv-qualifier is the same cv-qualification as, or a 12466 // greater cv-qualification than, cv, and where conversion-type-id 12467 // denotes the type "pointer to function of (P1,...,Pn) returning 12468 // R", or the type "reference to pointer to function of 12469 // (P1,...,Pn) returning R", or the type "reference to function 12470 // of (P1,...,Pn) returning R", a surrogate call function [...] 12471 // is also considered as a candidate function. Similarly, 12472 // surrogate call functions are added to the set of candidate 12473 // functions for each conversion function declared in an 12474 // accessible base class provided the function is not hidden 12475 // within T by another intervening declaration. 12476 const auto &Conversions = 12477 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12478 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12479 NamedDecl *D = *I; 12480 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12481 if (isa<UsingShadowDecl>(D)) 12482 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12483 12484 // Skip over templated conversion functions; they aren't 12485 // surrogates. 12486 if (isa<FunctionTemplateDecl>(D)) 12487 continue; 12488 12489 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12490 if (!Conv->isExplicit()) { 12491 // Strip the reference type (if any) and then the pointer type (if 12492 // any) to get down to what might be a function type. 12493 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12494 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12495 ConvType = ConvPtrType->getPointeeType(); 12496 12497 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12498 { 12499 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12500 Object.get(), Args, CandidateSet); 12501 } 12502 } 12503 } 12504 12505 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12506 12507 // Perform overload resolution. 12508 OverloadCandidateSet::iterator Best; 12509 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12510 Best)) { 12511 case OR_Success: 12512 // Overload resolution succeeded; we'll build the appropriate call 12513 // below. 12514 break; 12515 12516 case OR_No_Viable_Function: 12517 if (CandidateSet.empty()) 12518 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12519 << Object.get()->getType() << /*call*/ 1 12520 << Object.get()->getSourceRange(); 12521 else 12522 Diag(Object.get()->getLocStart(), 12523 diag::err_ovl_no_viable_object_call) 12524 << Object.get()->getType() << Object.get()->getSourceRange(); 12525 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12526 break; 12527 12528 case OR_Ambiguous: 12529 Diag(Object.get()->getLocStart(), 12530 diag::err_ovl_ambiguous_object_call) 12531 << Object.get()->getType() << Object.get()->getSourceRange(); 12532 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12533 break; 12534 12535 case OR_Deleted: 12536 Diag(Object.get()->getLocStart(), 12537 diag::err_ovl_deleted_object_call) 12538 << Best->Function->isDeleted() 12539 << Object.get()->getType() 12540 << getDeletedOrUnavailableSuffix(Best->Function) 12541 << Object.get()->getSourceRange(); 12542 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12543 break; 12544 } 12545 12546 if (Best == CandidateSet.end()) 12547 return true; 12548 12549 UnbridgedCasts.restore(); 12550 12551 if (Best->Function == nullptr) { 12552 // Since there is no function declaration, this is one of the 12553 // surrogate candidates. Dig out the conversion function. 12554 CXXConversionDecl *Conv 12555 = cast<CXXConversionDecl>( 12556 Best->Conversions[0].UserDefined.ConversionFunction); 12557 12558 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12559 Best->FoundDecl); 12560 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12561 return ExprError(); 12562 assert(Conv == Best->FoundDecl.getDecl() && 12563 "Found Decl & conversion-to-functionptr should be same, right?!"); 12564 // We selected one of the surrogate functions that converts the 12565 // object parameter to a function pointer. Perform the conversion 12566 // on the object argument, then let ActOnCallExpr finish the job. 12567 12568 // Create an implicit member expr to refer to the conversion operator. 12569 // and then call it. 12570 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12571 Conv, HadMultipleCandidates); 12572 if (Call.isInvalid()) 12573 return ExprError(); 12574 // Record usage of conversion in an implicit cast. 12575 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12576 CK_UserDefinedConversion, Call.get(), 12577 nullptr, VK_RValue); 12578 12579 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12580 } 12581 12582 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12583 12584 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12585 // that calls this method, using Object for the implicit object 12586 // parameter and passing along the remaining arguments. 12587 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12588 12589 // An error diagnostic has already been printed when parsing the declaration. 12590 if (Method->isInvalidDecl()) 12591 return ExprError(); 12592 12593 const FunctionProtoType *Proto = 12594 Method->getType()->getAs<FunctionProtoType>(); 12595 12596 unsigned NumParams = Proto->getNumParams(); 12597 12598 DeclarationNameInfo OpLocInfo( 12599 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12600 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12601 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12602 HadMultipleCandidates, 12603 OpLocInfo.getLoc(), 12604 OpLocInfo.getInfo()); 12605 if (NewFn.isInvalid()) 12606 return true; 12607 12608 // Build the full argument list for the method call (the implicit object 12609 // parameter is placed at the beginning of the list). 12610 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12611 MethodArgs[0] = Object.get(); 12612 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12613 12614 // Once we've built TheCall, all of the expressions are properly 12615 // owned. 12616 QualType ResultTy = Method->getReturnType(); 12617 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12618 ResultTy = ResultTy.getNonLValueExprType(Context); 12619 12620 CXXOperatorCallExpr *TheCall = new (Context) 12621 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12622 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12623 ResultTy, VK, RParenLoc, false); 12624 MethodArgs.reset(); 12625 12626 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12627 return true; 12628 12629 // We may have default arguments. If so, we need to allocate more 12630 // slots in the call for them. 12631 if (Args.size() < NumParams) 12632 TheCall->setNumArgs(Context, NumParams + 1); 12633 12634 bool IsError = false; 12635 12636 // Initialize the implicit object parameter. 12637 ExprResult ObjRes = 12638 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12639 Best->FoundDecl, Method); 12640 if (ObjRes.isInvalid()) 12641 IsError = true; 12642 else 12643 Object = ObjRes; 12644 TheCall->setArg(0, Object.get()); 12645 12646 // Check the argument types. 12647 for (unsigned i = 0; i != NumParams; i++) { 12648 Expr *Arg; 12649 if (i < Args.size()) { 12650 Arg = Args[i]; 12651 12652 // Pass the argument. 12653 12654 ExprResult InputInit 12655 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12656 Context, 12657 Method->getParamDecl(i)), 12658 SourceLocation(), Arg); 12659 12660 IsError |= InputInit.isInvalid(); 12661 Arg = InputInit.getAs<Expr>(); 12662 } else { 12663 ExprResult DefArg 12664 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12665 if (DefArg.isInvalid()) { 12666 IsError = true; 12667 break; 12668 } 12669 12670 Arg = DefArg.getAs<Expr>(); 12671 } 12672 12673 TheCall->setArg(i + 1, Arg); 12674 } 12675 12676 // If this is a variadic call, handle args passed through "...". 12677 if (Proto->isVariadic()) { 12678 // Promote the arguments (C99 6.5.2.2p7). 12679 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12680 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12681 nullptr); 12682 IsError |= Arg.isInvalid(); 12683 TheCall->setArg(i + 1, Arg.get()); 12684 } 12685 } 12686 12687 if (IsError) return true; 12688 12689 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12690 12691 if (CheckFunctionCall(Method, TheCall, Proto)) 12692 return true; 12693 12694 return MaybeBindToTemporary(TheCall); 12695 } 12696 12697 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12698 /// (if one exists), where @c Base is an expression of class type and 12699 /// @c Member is the name of the member we're trying to find. 12700 ExprResult 12701 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12702 bool *NoArrowOperatorFound) { 12703 assert(Base->getType()->isRecordType() && 12704 "left-hand side must have class type"); 12705 12706 if (checkPlaceholderForOverload(*this, Base)) 12707 return ExprError(); 12708 12709 SourceLocation Loc = Base->getExprLoc(); 12710 12711 // C++ [over.ref]p1: 12712 // 12713 // [...] An expression x->m is interpreted as (x.operator->())->m 12714 // for a class object x of type T if T::operator->() exists and if 12715 // the operator is selected as the best match function by the 12716 // overload resolution mechanism (13.3). 12717 DeclarationName OpName = 12718 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12719 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12720 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12721 12722 if (RequireCompleteType(Loc, Base->getType(), 12723 diag::err_typecheck_incomplete_tag, Base)) 12724 return ExprError(); 12725 12726 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12727 LookupQualifiedName(R, BaseRecord->getDecl()); 12728 R.suppressDiagnostics(); 12729 12730 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12731 Oper != OperEnd; ++Oper) { 12732 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12733 None, CandidateSet, /*SuppressUserConversions=*/false); 12734 } 12735 12736 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12737 12738 // Perform overload resolution. 12739 OverloadCandidateSet::iterator Best; 12740 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12741 case OR_Success: 12742 // Overload resolution succeeded; we'll build the call below. 12743 break; 12744 12745 case OR_No_Viable_Function: 12746 if (CandidateSet.empty()) { 12747 QualType BaseType = Base->getType(); 12748 if (NoArrowOperatorFound) { 12749 // Report this specific error to the caller instead of emitting a 12750 // diagnostic, as requested. 12751 *NoArrowOperatorFound = true; 12752 return ExprError(); 12753 } 12754 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12755 << BaseType << Base->getSourceRange(); 12756 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12757 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12758 << FixItHint::CreateReplacement(OpLoc, "."); 12759 } 12760 } else 12761 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12762 << "operator->" << Base->getSourceRange(); 12763 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12764 return ExprError(); 12765 12766 case OR_Ambiguous: 12767 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12768 << "->" << Base->getType() << Base->getSourceRange(); 12769 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12770 return ExprError(); 12771 12772 case OR_Deleted: 12773 Diag(OpLoc, diag::err_ovl_deleted_oper) 12774 << Best->Function->isDeleted() 12775 << "->" 12776 << getDeletedOrUnavailableSuffix(Best->Function) 12777 << Base->getSourceRange(); 12778 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12779 return ExprError(); 12780 } 12781 12782 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12783 12784 // Convert the object parameter. 12785 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12786 ExprResult BaseResult = 12787 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12788 Best->FoundDecl, Method); 12789 if (BaseResult.isInvalid()) 12790 return ExprError(); 12791 Base = BaseResult.get(); 12792 12793 // Build the operator call. 12794 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12795 HadMultipleCandidates, OpLoc); 12796 if (FnExpr.isInvalid()) 12797 return ExprError(); 12798 12799 QualType ResultTy = Method->getReturnType(); 12800 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12801 ResultTy = ResultTy.getNonLValueExprType(Context); 12802 CXXOperatorCallExpr *TheCall = 12803 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12804 Base, ResultTy, VK, OpLoc, false); 12805 12806 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12807 return ExprError(); 12808 12809 return MaybeBindToTemporary(TheCall); 12810 } 12811 12812 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12813 /// a literal operator described by the provided lookup results. 12814 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12815 DeclarationNameInfo &SuffixInfo, 12816 ArrayRef<Expr*> Args, 12817 SourceLocation LitEndLoc, 12818 TemplateArgumentListInfo *TemplateArgs) { 12819 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12820 12821 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12822 OverloadCandidateSet::CSK_Normal); 12823 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12824 /*SuppressUserConversions=*/true); 12825 12826 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12827 12828 // Perform overload resolution. This will usually be trivial, but might need 12829 // to perform substitutions for a literal operator template. 12830 OverloadCandidateSet::iterator Best; 12831 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12832 case OR_Success: 12833 case OR_Deleted: 12834 break; 12835 12836 case OR_No_Viable_Function: 12837 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12838 << R.getLookupName(); 12839 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12840 return ExprError(); 12841 12842 case OR_Ambiguous: 12843 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12844 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12845 return ExprError(); 12846 } 12847 12848 FunctionDecl *FD = Best->Function; 12849 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12850 HadMultipleCandidates, 12851 SuffixInfo.getLoc(), 12852 SuffixInfo.getInfo()); 12853 if (Fn.isInvalid()) 12854 return true; 12855 12856 // Check the argument types. This should almost always be a no-op, except 12857 // that array-to-pointer decay is applied to string literals. 12858 Expr *ConvArgs[2]; 12859 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12860 ExprResult InputInit = PerformCopyInitialization( 12861 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12862 SourceLocation(), Args[ArgIdx]); 12863 if (InputInit.isInvalid()) 12864 return true; 12865 ConvArgs[ArgIdx] = InputInit.get(); 12866 } 12867 12868 QualType ResultTy = FD->getReturnType(); 12869 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12870 ResultTy = ResultTy.getNonLValueExprType(Context); 12871 12872 UserDefinedLiteral *UDL = 12873 new (Context) UserDefinedLiteral(Context, Fn.get(), 12874 llvm::makeArrayRef(ConvArgs, Args.size()), 12875 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12876 12877 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12878 return ExprError(); 12879 12880 if (CheckFunctionCall(FD, UDL, nullptr)) 12881 return ExprError(); 12882 12883 return MaybeBindToTemporary(UDL); 12884 } 12885 12886 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12887 /// given LookupResult is non-empty, it is assumed to describe a member which 12888 /// will be invoked. Otherwise, the function will be found via argument 12889 /// dependent lookup. 12890 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12891 /// otherwise CallExpr is set to ExprError() and some non-success value 12892 /// is returned. 12893 Sema::ForRangeStatus 12894 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12895 SourceLocation RangeLoc, 12896 const DeclarationNameInfo &NameInfo, 12897 LookupResult &MemberLookup, 12898 OverloadCandidateSet *CandidateSet, 12899 Expr *Range, ExprResult *CallExpr) { 12900 Scope *S = nullptr; 12901 12902 CandidateSet->clear(); 12903 if (!MemberLookup.empty()) { 12904 ExprResult MemberRef = 12905 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12906 /*IsPtr=*/false, CXXScopeSpec(), 12907 /*TemplateKWLoc=*/SourceLocation(), 12908 /*FirstQualifierInScope=*/nullptr, 12909 MemberLookup, 12910 /*TemplateArgs=*/nullptr, S); 12911 if (MemberRef.isInvalid()) { 12912 *CallExpr = ExprError(); 12913 return FRS_DiagnosticIssued; 12914 } 12915 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12916 if (CallExpr->isInvalid()) { 12917 *CallExpr = ExprError(); 12918 return FRS_DiagnosticIssued; 12919 } 12920 } else { 12921 UnresolvedSet<0> FoundNames; 12922 UnresolvedLookupExpr *Fn = 12923 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12924 NestedNameSpecifierLoc(), NameInfo, 12925 /*NeedsADL=*/true, /*Overloaded=*/false, 12926 FoundNames.begin(), FoundNames.end()); 12927 12928 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12929 CandidateSet, CallExpr); 12930 if (CandidateSet->empty() || CandidateSetError) { 12931 *CallExpr = ExprError(); 12932 return FRS_NoViableFunction; 12933 } 12934 OverloadCandidateSet::iterator Best; 12935 OverloadingResult OverloadResult = 12936 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12937 12938 if (OverloadResult == OR_No_Viable_Function) { 12939 *CallExpr = ExprError(); 12940 return FRS_NoViableFunction; 12941 } 12942 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12943 Loc, nullptr, CandidateSet, &Best, 12944 OverloadResult, 12945 /*AllowTypoCorrection=*/false); 12946 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12947 *CallExpr = ExprError(); 12948 return FRS_DiagnosticIssued; 12949 } 12950 } 12951 return FRS_Success; 12952 } 12953 12954 12955 /// FixOverloadedFunctionReference - E is an expression that refers to 12956 /// a C++ overloaded function (possibly with some parentheses and 12957 /// perhaps a '&' around it). We have resolved the overloaded function 12958 /// to the function declaration Fn, so patch up the expression E to 12959 /// refer (possibly indirectly) to Fn. Returns the new expr. 12960 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12961 FunctionDecl *Fn) { 12962 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12963 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12964 Found, Fn); 12965 if (SubExpr == PE->getSubExpr()) 12966 return PE; 12967 12968 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12969 } 12970 12971 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12972 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12973 Found, Fn); 12974 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12975 SubExpr->getType()) && 12976 "Implicit cast type cannot be determined from overload"); 12977 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12978 if (SubExpr == ICE->getSubExpr()) 12979 return ICE; 12980 12981 return ImplicitCastExpr::Create(Context, ICE->getType(), 12982 ICE->getCastKind(), 12983 SubExpr, nullptr, 12984 ICE->getValueKind()); 12985 } 12986 12987 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12988 assert(UnOp->getOpcode() == UO_AddrOf && 12989 "Can only take the address of an overloaded function"); 12990 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12991 if (Method->isStatic()) { 12992 // Do nothing: static member functions aren't any different 12993 // from non-member functions. 12994 } else { 12995 // Fix the subexpression, which really has to be an 12996 // UnresolvedLookupExpr holding an overloaded member function 12997 // or template. 12998 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12999 Found, Fn); 13000 if (SubExpr == UnOp->getSubExpr()) 13001 return UnOp; 13002 13003 assert(isa<DeclRefExpr>(SubExpr) 13004 && "fixed to something other than a decl ref"); 13005 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13006 && "fixed to a member ref with no nested name qualifier"); 13007 13008 // We have taken the address of a pointer to member 13009 // function. Perform the computation here so that we get the 13010 // appropriate pointer to member type. 13011 QualType ClassType 13012 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13013 QualType MemPtrType 13014 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13015 // Under the MS ABI, lock down the inheritance model now. 13016 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13017 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13018 13019 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13020 VK_RValue, OK_Ordinary, 13021 UnOp->getOperatorLoc()); 13022 } 13023 } 13024 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13025 Found, Fn); 13026 if (SubExpr == UnOp->getSubExpr()) 13027 return UnOp; 13028 13029 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13030 Context.getPointerType(SubExpr->getType()), 13031 VK_RValue, OK_Ordinary, 13032 UnOp->getOperatorLoc()); 13033 } 13034 13035 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13036 // FIXME: avoid copy. 13037 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13038 if (ULE->hasExplicitTemplateArgs()) { 13039 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13040 TemplateArgs = &TemplateArgsBuffer; 13041 } 13042 13043 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13044 ULE->getQualifierLoc(), 13045 ULE->getTemplateKeywordLoc(), 13046 Fn, 13047 /*enclosing*/ false, // FIXME? 13048 ULE->getNameLoc(), 13049 Fn->getType(), 13050 VK_LValue, 13051 Found.getDecl(), 13052 TemplateArgs); 13053 MarkDeclRefReferenced(DRE); 13054 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13055 return DRE; 13056 } 13057 13058 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13059 // FIXME: avoid copy. 13060 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13061 if (MemExpr->hasExplicitTemplateArgs()) { 13062 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13063 TemplateArgs = &TemplateArgsBuffer; 13064 } 13065 13066 Expr *Base; 13067 13068 // If we're filling in a static method where we used to have an 13069 // implicit member access, rewrite to a simple decl ref. 13070 if (MemExpr->isImplicitAccess()) { 13071 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13072 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13073 MemExpr->getQualifierLoc(), 13074 MemExpr->getTemplateKeywordLoc(), 13075 Fn, 13076 /*enclosing*/ false, 13077 MemExpr->getMemberLoc(), 13078 Fn->getType(), 13079 VK_LValue, 13080 Found.getDecl(), 13081 TemplateArgs); 13082 MarkDeclRefReferenced(DRE); 13083 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13084 return DRE; 13085 } else { 13086 SourceLocation Loc = MemExpr->getMemberLoc(); 13087 if (MemExpr->getQualifier()) 13088 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13089 CheckCXXThisCapture(Loc); 13090 Base = new (Context) CXXThisExpr(Loc, 13091 MemExpr->getBaseType(), 13092 /*isImplicit=*/true); 13093 } 13094 } else 13095 Base = MemExpr->getBase(); 13096 13097 ExprValueKind valueKind; 13098 QualType type; 13099 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13100 valueKind = VK_LValue; 13101 type = Fn->getType(); 13102 } else { 13103 valueKind = VK_RValue; 13104 type = Context.BoundMemberTy; 13105 } 13106 13107 MemberExpr *ME = MemberExpr::Create( 13108 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13109 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13110 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13111 OK_Ordinary); 13112 ME->setHadMultipleCandidates(true); 13113 MarkMemberReferenced(ME); 13114 return ME; 13115 } 13116 13117 llvm_unreachable("Invalid reference to overloaded function"); 13118 } 13119 13120 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13121 DeclAccessPair Found, 13122 FunctionDecl *Fn) { 13123 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13124 } 13125