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 /// A convenience routine for creating a decayed reference to a function. 42 static ExprResult 43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 44 bool HadMultipleCandidates, 45 SourceLocation Loc = SourceLocation(), 46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 47 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 48 return ExprError(); 49 // If FoundDecl is different from Fn (such as if one is a template 50 // and the other a specialization), make sure DiagnoseUseOfDecl is 51 // called on both. 52 // FIXME: This would be more comprehensively addressed by modifying 53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 54 // being used. 55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 56 return ExprError(); 57 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 58 VK_LValue, Loc, LocInfo); 59 if (HadMultipleCandidates) 60 DRE->setHadMultipleCandidates(true); 61 62 S.MarkDeclRefReferenced(DRE); 63 64 ExprResult E = DRE; 65 E = S.DefaultFunctionArrayConversion(E.get()); 66 if (E.isInvalid()) 67 return ExprError(); 68 return E; 69 } 70 71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 72 bool InOverloadResolution, 73 StandardConversionSequence &SCS, 74 bool CStyle, 75 bool AllowObjCWritebackConversion); 76 77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 78 QualType &ToType, 79 bool InOverloadResolution, 80 StandardConversionSequence &SCS, 81 bool CStyle); 82 static OverloadingResult 83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 84 UserDefinedConversionSequence& User, 85 OverloadCandidateSet& Conversions, 86 bool AllowExplicit, 87 bool AllowObjCConversionOnExplicit); 88 89 90 static ImplicitConversionSequence::CompareKind 91 CompareStandardConversionSequences(Sema &S, 92 const StandardConversionSequence& SCS1, 93 const StandardConversionSequence& SCS2); 94 95 static ImplicitConversionSequence::CompareKind 96 CompareQualificationConversions(Sema &S, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareDerivedToBaseConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 /// GetConversionRank - Retrieve the implicit conversion rank 106 /// corresponding to the given implicit conversion kind. 107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 108 static const ImplicitConversionRank 109 Rank[(int)ICK_Num_Conversion_Kinds] = { 110 ICR_Exact_Match, 111 ICR_Exact_Match, 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Promotion, 117 ICR_Promotion, 118 ICR_Promotion, 119 ICR_Conversion, 120 ICR_Conversion, 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_Complex_Real_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Writeback_Conversion, 134 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 135 // it was omitted by the patch that added 136 // ICK_Zero_Event_Conversion 137 ICR_C_Conversion 138 }; 139 return Rank[(int)Kind]; 140 } 141 142 /// GetImplicitConversionName - Return the name of this kind of 143 /// implicit conversion. 144 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 145 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 146 "No conversion", 147 "Lvalue-to-rvalue", 148 "Array-to-pointer", 149 "Function-to-pointer", 150 "Noreturn adjustment", 151 "Qualification", 152 "Integral promotion", 153 "Floating point promotion", 154 "Complex promotion", 155 "Integral conversion", 156 "Floating conversion", 157 "Complex conversion", 158 "Floating-integral conversion", 159 "Pointer conversion", 160 "Pointer-to-member conversion", 161 "Boolean conversion", 162 "Compatible-types conversion", 163 "Derived-to-base conversion", 164 "Vector conversion", 165 "Vector splat", 166 "Complex-real conversion", 167 "Block Pointer conversion", 168 "Transparent Union Conversion", 169 "Writeback conversion", 170 "OpenCL Zero Event Conversion", 171 "C specific type conversion" 172 }; 173 return Name[Kind]; 174 } 175 176 /// StandardConversionSequence - Set the standard conversion 177 /// sequence to the identity conversion. 178 void StandardConversionSequence::setAsIdentityConversion() { 179 First = ICK_Identity; 180 Second = ICK_Identity; 181 Third = ICK_Identity; 182 DeprecatedStringLiteralToCharPtr = false; 183 QualificationIncludesObjCLifetime = false; 184 ReferenceBinding = false; 185 DirectBinding = false; 186 IsLvalueReference = true; 187 BindsToFunctionLvalue = false; 188 BindsToRvalue = false; 189 BindsImplicitObjectArgumentWithoutRefQualifier = false; 190 ObjCLifetimeConversionBinding = false; 191 CopyConstructor = nullptr; 192 } 193 194 /// getRank - Retrieve the rank of this standard conversion sequence 195 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 196 /// implicit conversions. 197 ImplicitConversionRank StandardConversionSequence::getRank() const { 198 ImplicitConversionRank Rank = ICR_Exact_Match; 199 if (GetConversionRank(First) > Rank) 200 Rank = GetConversionRank(First); 201 if (GetConversionRank(Second) > Rank) 202 Rank = GetConversionRank(Second); 203 if (GetConversionRank(Third) > Rank) 204 Rank = GetConversionRank(Third); 205 return Rank; 206 } 207 208 /// isPointerConversionToBool - Determines whether this conversion is 209 /// a conversion of a pointer or pointer-to-member to bool. This is 210 /// used as part of the ranking of standard conversion sequences 211 /// (C++ 13.3.3.2p4). 212 bool StandardConversionSequence::isPointerConversionToBool() const { 213 // Note that FromType has not necessarily been transformed by the 214 // array-to-pointer or function-to-pointer implicit conversions, so 215 // check for their presence as well as checking whether FromType is 216 // a pointer. 217 if (getToType(1)->isBooleanType() && 218 (getFromType()->isPointerType() || 219 getFromType()->isObjCObjectPointerType() || 220 getFromType()->isBlockPointerType() || 221 getFromType()->isNullPtrType() || 222 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 223 return true; 224 225 return false; 226 } 227 228 /// isPointerConversionToVoidPointer - Determines whether this 229 /// conversion is a conversion of a pointer to a void pointer. This is 230 /// used as part of the ranking of standard conversion sequences (C++ 231 /// 13.3.3.2p4). 232 bool 233 StandardConversionSequence:: 234 isPointerConversionToVoidPointer(ASTContext& Context) const { 235 QualType FromType = getFromType(); 236 QualType ToType = getToType(1); 237 238 // Note that FromType has not necessarily been transformed by the 239 // array-to-pointer implicit conversion, so check for its presence 240 // and redo the conversion to get a pointer. 241 if (First == ICK_Array_To_Pointer) 242 FromType = Context.getArrayDecayedType(FromType); 243 244 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 245 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 246 return ToPtrType->getPointeeType()->isVoidType(); 247 248 return false; 249 } 250 251 /// Skip any implicit casts which could be either part of a narrowing conversion 252 /// or after one in an implicit conversion. 253 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 254 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 255 switch (ICE->getCastKind()) { 256 case CK_NoOp: 257 case CK_IntegralCast: 258 case CK_IntegralToBoolean: 259 case CK_IntegralToFloating: 260 case CK_FloatingToIntegral: 261 case CK_FloatingToBoolean: 262 case CK_FloatingCast: 263 Converted = ICE->getSubExpr(); 264 continue; 265 266 default: 267 return Converted; 268 } 269 } 270 271 return Converted; 272 } 273 274 /// Check if this standard conversion sequence represents a narrowing 275 /// conversion, according to C++11 [dcl.init.list]p7. 276 /// 277 /// \param Ctx The AST context. 278 /// \param Converted The result of applying this standard conversion sequence. 279 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 280 /// value of the expression prior to the narrowing conversion. 281 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 282 /// type of the expression prior to the narrowing conversion. 283 NarrowingKind 284 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 285 const Expr *Converted, 286 APValue &ConstantValue, 287 QualType &ConstantType) const { 288 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 289 290 // C++11 [dcl.init.list]p7: 291 // A narrowing conversion is an implicit conversion ... 292 QualType FromType = getToType(0); 293 QualType ToType = getToType(1); 294 switch (Second) { 295 // 'bool' is an integral type; dispatch to the right place to handle it. 296 case ICK_Boolean_Conversion: 297 if (FromType->isRealFloatingType()) 298 goto FloatingIntegralConversion; 299 if (FromType->isIntegralOrUnscopedEnumerationType()) 300 goto IntegralConversion; 301 // Boolean conversions can be from pointers and pointers to members 302 // [conv.bool], and those aren't considered narrowing conversions. 303 return NK_Not_Narrowing; 304 305 // -- from a floating-point type to an integer type, or 306 // 307 // -- from an integer type or unscoped enumeration type to a floating-point 308 // type, except where the source is a constant expression and the actual 309 // value after conversion will fit into the target type and will produce 310 // the original value when converted back to the original type, or 311 case ICK_Floating_Integral: 312 FloatingIntegralConversion: 313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 314 return NK_Type_Narrowing; 315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 316 llvm::APSInt IntConstantValue; 317 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 318 if (Initializer && 319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 320 // Convert the integer to the floating type. 321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 323 llvm::APFloat::rmNearestTiesToEven); 324 // And back. 325 llvm::APSInt ConvertedValue = IntConstantValue; 326 bool ignored; 327 Result.convertToInteger(ConvertedValue, 328 llvm::APFloat::rmTowardZero, &ignored); 329 // If the resulting value is different, this was a narrowing conversion. 330 if (IntConstantValue != ConvertedValue) { 331 ConstantValue = APValue(IntConstantValue); 332 ConstantType = Initializer->getType(); 333 return NK_Constant_Narrowing; 334 } 335 } else { 336 // Variables are always narrowings. 337 return NK_Variable_Narrowing; 338 } 339 } 340 return NK_Not_Narrowing; 341 342 // -- from long double to double or float, or from double to float, except 343 // where the source is a constant expression and the actual value after 344 // conversion is within the range of values that can be represented (even 345 // if it cannot be represented exactly), or 346 case ICK_Floating_Conversion: 347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 349 // FromType is larger than ToType. 350 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 352 // Constant! 353 assert(ConstantValue.isFloat()); 354 llvm::APFloat FloatVal = ConstantValue.getFloat(); 355 // Convert the source value into the target type. 356 bool ignored; 357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 358 Ctx.getFloatTypeSemantics(ToType), 359 llvm::APFloat::rmNearestTiesToEven, &ignored); 360 // If there was no overflow, the source value is within the range of 361 // values that can be represented. 362 if (ConvertStatus & llvm::APFloat::opOverflow) { 363 ConstantType = Initializer->getType(); 364 return NK_Constant_Narrowing; 365 } 366 } else { 367 return NK_Variable_Narrowing; 368 } 369 } 370 return NK_Not_Narrowing; 371 372 // -- from an integer type or unscoped enumeration type to an integer type 373 // that cannot represent all the values of the original type, except where 374 // the source is a constant expression and the actual value after 375 // conversion will fit into the target type and will produce the original 376 // value when converted back to the original type. 377 case ICK_Integral_Conversion: 378 IntegralConversion: { 379 assert(FromType->isIntegralOrUnscopedEnumerationType()); 380 assert(ToType->isIntegralOrUnscopedEnumerationType()); 381 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 382 const unsigned FromWidth = Ctx.getIntWidth(FromType); 383 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 384 const unsigned ToWidth = Ctx.getIntWidth(ToType); 385 386 if (FromWidth > ToWidth || 387 (FromWidth == ToWidth && FromSigned != ToSigned) || 388 (FromSigned && !ToSigned)) { 389 // Not all values of FromType can be represented in ToType. 390 llvm::APSInt InitializerValue; 391 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 392 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 393 // Such conversions on variables are always narrowing. 394 return NK_Variable_Narrowing; 395 } 396 bool Narrowing = false; 397 if (FromWidth < ToWidth) { 398 // Negative -> unsigned is narrowing. Otherwise, more bits is never 399 // narrowing. 400 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 401 Narrowing = true; 402 } else { 403 // Add a bit to the InitializerValue so we don't have to worry about 404 // signed vs. unsigned comparisons. 405 InitializerValue = InitializerValue.extend( 406 InitializerValue.getBitWidth() + 1); 407 // Convert the initializer to and from the target width and signed-ness. 408 llvm::APSInt ConvertedValue = InitializerValue; 409 ConvertedValue = ConvertedValue.trunc(ToWidth); 410 ConvertedValue.setIsSigned(ToSigned); 411 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 412 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 413 // If the result is different, this was a narrowing conversion. 414 if (ConvertedValue != InitializerValue) 415 Narrowing = true; 416 } 417 if (Narrowing) { 418 ConstantType = Initializer->getType(); 419 ConstantValue = APValue(InitializerValue); 420 return NK_Constant_Narrowing; 421 } 422 } 423 return NK_Not_Narrowing; 424 } 425 426 default: 427 // Other kinds of conversions are not narrowings. 428 return NK_Not_Narrowing; 429 } 430 } 431 432 /// dump - Print this standard conversion sequence to standard 433 /// error. Useful for debugging overloading issues. 434 void StandardConversionSequence::dump() const { 435 raw_ostream &OS = llvm::errs(); 436 bool PrintedSomething = false; 437 if (First != ICK_Identity) { 438 OS << GetImplicitConversionName(First); 439 PrintedSomething = true; 440 } 441 442 if (Second != ICK_Identity) { 443 if (PrintedSomething) { 444 OS << " -> "; 445 } 446 OS << GetImplicitConversionName(Second); 447 448 if (CopyConstructor) { 449 OS << " (by copy constructor)"; 450 } else if (DirectBinding) { 451 OS << " (direct reference binding)"; 452 } else if (ReferenceBinding) { 453 OS << " (reference binding)"; 454 } 455 PrintedSomething = true; 456 } 457 458 if (Third != ICK_Identity) { 459 if (PrintedSomething) { 460 OS << " -> "; 461 } 462 OS << GetImplicitConversionName(Third); 463 PrintedSomething = true; 464 } 465 466 if (!PrintedSomething) { 467 OS << "No conversions required"; 468 } 469 } 470 471 /// dump - Print this user-defined conversion sequence to standard 472 /// error. Useful for debugging overloading issues. 473 void UserDefinedConversionSequence::dump() const { 474 raw_ostream &OS = llvm::errs(); 475 if (Before.First || Before.Second || Before.Third) { 476 Before.dump(); 477 OS << " -> "; 478 } 479 if (ConversionFunction) 480 OS << '\'' << *ConversionFunction << '\''; 481 else 482 OS << "aggregate initialization"; 483 if (After.First || After.Second || After.Third) { 484 OS << " -> "; 485 After.dump(); 486 } 487 } 488 489 /// dump - Print this implicit conversion sequence to standard 490 /// error. Useful for debugging overloading issues. 491 void ImplicitConversionSequence::dump() const { 492 raw_ostream &OS = llvm::errs(); 493 if (isStdInitializerListElement()) 494 OS << "Worst std::initializer_list element conversion: "; 495 switch (ConversionKind) { 496 case StandardConversion: 497 OS << "Standard conversion: "; 498 Standard.dump(); 499 break; 500 case UserDefinedConversion: 501 OS << "User-defined conversion: "; 502 UserDefined.dump(); 503 break; 504 case EllipsisConversion: 505 OS << "Ellipsis conversion"; 506 break; 507 case AmbiguousConversion: 508 OS << "Ambiguous conversion"; 509 break; 510 case BadConversion: 511 OS << "Bad conversion"; 512 break; 513 } 514 515 OS << "\n"; 516 } 517 518 void AmbiguousConversionSequence::construct() { 519 new (&conversions()) ConversionSet(); 520 } 521 522 void AmbiguousConversionSequence::destruct() { 523 conversions().~ConversionSet(); 524 } 525 526 void 527 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 528 FromTypePtr = O.FromTypePtr; 529 ToTypePtr = O.ToTypePtr; 530 new (&conversions()) ConversionSet(O.conversions()); 531 } 532 533 namespace { 534 // Structure used by DeductionFailureInfo to store 535 // template argument information. 536 struct DFIArguments { 537 TemplateArgument FirstArg; 538 TemplateArgument SecondArg; 539 }; 540 // Structure used by DeductionFailureInfo to store 541 // template parameter and template argument information. 542 struct DFIParamWithArguments : DFIArguments { 543 TemplateParameter Param; 544 }; 545 } 546 547 /// \brief Convert from Sema's representation of template deduction information 548 /// to the form used in overload-candidate information. 549 DeductionFailureInfo 550 clang::MakeDeductionFailureInfo(ASTContext &Context, 551 Sema::TemplateDeductionResult TDK, 552 TemplateDeductionInfo &Info) { 553 DeductionFailureInfo Result; 554 Result.Result = static_cast<unsigned>(TDK); 555 Result.HasDiagnostic = false; 556 Result.Data = nullptr; 557 switch (TDK) { 558 case Sema::TDK_Success: 559 case Sema::TDK_Invalid: 560 case Sema::TDK_InstantiationDepth: 561 case Sema::TDK_TooManyArguments: 562 case Sema::TDK_TooFewArguments: 563 break; 564 565 case Sema::TDK_Incomplete: 566 case Sema::TDK_InvalidExplicitArguments: 567 Result.Data = Info.Param.getOpaqueValue(); 568 break; 569 570 case Sema::TDK_NonDeducedMismatch: { 571 // FIXME: Should allocate from normal heap so that we can free this later. 572 DFIArguments *Saved = new (Context) DFIArguments; 573 Saved->FirstArg = Info.FirstArg; 574 Saved->SecondArg = Info.SecondArg; 575 Result.Data = Saved; 576 break; 577 } 578 579 case Sema::TDK_Inconsistent: 580 case Sema::TDK_Underqualified: { 581 // FIXME: Should allocate from normal heap so that we can free this later. 582 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 583 Saved->Param = Info.Param; 584 Saved->FirstArg = Info.FirstArg; 585 Saved->SecondArg = Info.SecondArg; 586 Result.Data = Saved; 587 break; 588 } 589 590 case Sema::TDK_SubstitutionFailure: 591 Result.Data = Info.take(); 592 if (Info.hasSFINAEDiagnostic()) { 593 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 594 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 595 Info.takeSFINAEDiagnostic(*Diag); 596 Result.HasDiagnostic = true; 597 } 598 break; 599 600 case Sema::TDK_FailedOverloadResolution: 601 Result.Data = Info.Expression; 602 break; 603 604 case Sema::TDK_MiscellaneousDeductionFailure: 605 break; 606 } 607 608 return Result; 609 } 610 611 void DeductionFailureInfo::Destroy() { 612 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 613 case Sema::TDK_Success: 614 case Sema::TDK_Invalid: 615 case Sema::TDK_InstantiationDepth: 616 case Sema::TDK_Incomplete: 617 case Sema::TDK_TooManyArguments: 618 case Sema::TDK_TooFewArguments: 619 case Sema::TDK_InvalidExplicitArguments: 620 case Sema::TDK_FailedOverloadResolution: 621 break; 622 623 case Sema::TDK_Inconsistent: 624 case Sema::TDK_Underqualified: 625 case Sema::TDK_NonDeducedMismatch: 626 // FIXME: Destroy the data? 627 Data = nullptr; 628 break; 629 630 case Sema::TDK_SubstitutionFailure: 631 // FIXME: Destroy the template argument list? 632 Data = nullptr; 633 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 634 Diag->~PartialDiagnosticAt(); 635 HasDiagnostic = false; 636 } 637 break; 638 639 // Unhandled 640 case Sema::TDK_MiscellaneousDeductionFailure: 641 break; 642 } 643 } 644 645 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 646 if (HasDiagnostic) 647 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 648 return nullptr; 649 } 650 651 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 652 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 653 case Sema::TDK_Success: 654 case Sema::TDK_Invalid: 655 case Sema::TDK_InstantiationDepth: 656 case Sema::TDK_TooManyArguments: 657 case Sema::TDK_TooFewArguments: 658 case Sema::TDK_SubstitutionFailure: 659 case Sema::TDK_NonDeducedMismatch: 660 case Sema::TDK_FailedOverloadResolution: 661 return TemplateParameter(); 662 663 case Sema::TDK_Incomplete: 664 case Sema::TDK_InvalidExplicitArguments: 665 return TemplateParameter::getFromOpaqueValue(Data); 666 667 case Sema::TDK_Inconsistent: 668 case Sema::TDK_Underqualified: 669 return static_cast<DFIParamWithArguments*>(Data)->Param; 670 671 // Unhandled 672 case Sema::TDK_MiscellaneousDeductionFailure: 673 break; 674 } 675 676 return TemplateParameter(); 677 } 678 679 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 681 case Sema::TDK_Success: 682 case Sema::TDK_Invalid: 683 case Sema::TDK_InstantiationDepth: 684 case Sema::TDK_TooManyArguments: 685 case Sema::TDK_TooFewArguments: 686 case Sema::TDK_Incomplete: 687 case Sema::TDK_InvalidExplicitArguments: 688 case Sema::TDK_Inconsistent: 689 case Sema::TDK_Underqualified: 690 case Sema::TDK_NonDeducedMismatch: 691 case Sema::TDK_FailedOverloadResolution: 692 return nullptr; 693 694 case Sema::TDK_SubstitutionFailure: 695 return static_cast<TemplateArgumentList*>(Data); 696 697 // Unhandled 698 case Sema::TDK_MiscellaneousDeductionFailure: 699 break; 700 } 701 702 return nullptr; 703 } 704 705 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 707 case Sema::TDK_Success: 708 case Sema::TDK_Invalid: 709 case Sema::TDK_InstantiationDepth: 710 case Sema::TDK_Incomplete: 711 case Sema::TDK_TooManyArguments: 712 case Sema::TDK_TooFewArguments: 713 case Sema::TDK_InvalidExplicitArguments: 714 case Sema::TDK_SubstitutionFailure: 715 case Sema::TDK_FailedOverloadResolution: 716 return nullptr; 717 718 case Sema::TDK_Inconsistent: 719 case Sema::TDK_Underqualified: 720 case Sema::TDK_NonDeducedMismatch: 721 return &static_cast<DFIArguments*>(Data)->FirstArg; 722 723 // Unhandled 724 case Sema::TDK_MiscellaneousDeductionFailure: 725 break; 726 } 727 728 return nullptr; 729 } 730 731 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 733 case Sema::TDK_Success: 734 case Sema::TDK_Invalid: 735 case Sema::TDK_InstantiationDepth: 736 case Sema::TDK_Incomplete: 737 case Sema::TDK_TooManyArguments: 738 case Sema::TDK_TooFewArguments: 739 case Sema::TDK_InvalidExplicitArguments: 740 case Sema::TDK_SubstitutionFailure: 741 case Sema::TDK_FailedOverloadResolution: 742 return nullptr; 743 744 case Sema::TDK_Inconsistent: 745 case Sema::TDK_Underqualified: 746 case Sema::TDK_NonDeducedMismatch: 747 return &static_cast<DFIArguments*>(Data)->SecondArg; 748 749 // Unhandled 750 case Sema::TDK_MiscellaneousDeductionFailure: 751 break; 752 } 753 754 return nullptr; 755 } 756 757 Expr *DeductionFailureInfo::getExpr() { 758 if (static_cast<Sema::TemplateDeductionResult>(Result) == 759 Sema::TDK_FailedOverloadResolution) 760 return static_cast<Expr*>(Data); 761 762 return nullptr; 763 } 764 765 void OverloadCandidateSet::destroyCandidates() { 766 for (iterator i = begin(), e = end(); i != e; ++i) { 767 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 768 i->Conversions[ii].~ImplicitConversionSequence(); 769 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 770 i->DeductionFailure.Destroy(); 771 } 772 } 773 774 void OverloadCandidateSet::clear() { 775 destroyCandidates(); 776 NumInlineSequences = 0; 777 Candidates.clear(); 778 Functions.clear(); 779 } 780 781 namespace { 782 class UnbridgedCastsSet { 783 struct Entry { 784 Expr **Addr; 785 Expr *Saved; 786 }; 787 SmallVector<Entry, 2> Entries; 788 789 public: 790 void save(Sema &S, Expr *&E) { 791 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 792 Entry entry = { &E, E }; 793 Entries.push_back(entry); 794 E = S.stripARCUnbridgedCast(E); 795 } 796 797 void restore() { 798 for (SmallVectorImpl<Entry>::iterator 799 i = Entries.begin(), e = Entries.end(); i != e; ++i) 800 *i->Addr = i->Saved; 801 } 802 }; 803 } 804 805 /// checkPlaceholderForOverload - Do any interesting placeholder-like 806 /// preprocessing on the given expression. 807 /// 808 /// \param unbridgedCasts a collection to which to add unbridged casts; 809 /// without this, they will be immediately diagnosed as errors 810 /// 811 /// Return true on unrecoverable error. 812 static bool 813 checkPlaceholderForOverload(Sema &S, Expr *&E, 814 UnbridgedCastsSet *unbridgedCasts = nullptr) { 815 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 816 // We can't handle overloaded expressions here because overload 817 // resolution might reasonably tweak them. 818 if (placeholder->getKind() == BuiltinType::Overload) return false; 819 820 // If the context potentially accepts unbridged ARC casts, strip 821 // the unbridged cast and add it to the collection for later restoration. 822 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 823 unbridgedCasts) { 824 unbridgedCasts->save(S, E); 825 return false; 826 } 827 828 // Go ahead and check everything else. 829 ExprResult result = S.CheckPlaceholderExpr(E); 830 if (result.isInvalid()) 831 return true; 832 833 E = result.get(); 834 return false; 835 } 836 837 // Nothing to do. 838 return false; 839 } 840 841 /// checkArgPlaceholdersForOverload - Check a set of call operands for 842 /// placeholders. 843 static bool checkArgPlaceholdersForOverload(Sema &S, 844 MultiExprArg Args, 845 UnbridgedCastsSet &unbridged) { 846 for (unsigned i = 0, e = Args.size(); i != e; ++i) 847 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 848 return true; 849 850 return false; 851 } 852 853 // IsOverload - Determine whether the given New declaration is an 854 // overload of the declarations in Old. This routine returns false if 855 // New and Old cannot be overloaded, e.g., if New has the same 856 // signature as some function in Old (C++ 1.3.10) or if the Old 857 // declarations aren't functions (or function templates) at all. When 858 // it does return false, MatchedDecl will point to the decl that New 859 // cannot be overloaded with. This decl may be a UsingShadowDecl on 860 // top of the underlying declaration. 861 // 862 // Example: Given the following input: 863 // 864 // void f(int, float); // #1 865 // void f(int, int); // #2 866 // int f(int, int); // #3 867 // 868 // When we process #1, there is no previous declaration of "f", 869 // so IsOverload will not be used. 870 // 871 // When we process #2, Old contains only the FunctionDecl for #1. By 872 // comparing the parameter types, we see that #1 and #2 are overloaded 873 // (since they have different signatures), so this routine returns 874 // false; MatchedDecl is unchanged. 875 // 876 // When we process #3, Old is an overload set containing #1 and #2. We 877 // compare the signatures of #3 to #1 (they're overloaded, so we do 878 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 879 // identical (return types of functions are not part of the 880 // signature), IsOverload returns false and MatchedDecl will be set to 881 // point to the FunctionDecl for #2. 882 // 883 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 884 // into a class by a using declaration. The rules for whether to hide 885 // shadow declarations ignore some properties which otherwise figure 886 // into a function template's signature. 887 Sema::OverloadKind 888 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 889 NamedDecl *&Match, bool NewIsUsingDecl) { 890 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 891 I != E; ++I) { 892 NamedDecl *OldD = *I; 893 894 bool OldIsUsingDecl = false; 895 if (isa<UsingShadowDecl>(OldD)) { 896 OldIsUsingDecl = true; 897 898 // We can always introduce two using declarations into the same 899 // context, even if they have identical signatures. 900 if (NewIsUsingDecl) continue; 901 902 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 903 } 904 905 // A using-declaration does not conflict with another declaration 906 // if one of them is hidden. 907 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 908 continue; 909 910 // If either declaration was introduced by a using declaration, 911 // we'll need to use slightly different rules for matching. 912 // Essentially, these rules are the normal rules, except that 913 // function templates hide function templates with different 914 // return types or template parameter lists. 915 bool UseMemberUsingDeclRules = 916 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 917 !New->getFriendObjectKind(); 918 919 if (FunctionDecl *OldF = OldD->getAsFunction()) { 920 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 921 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 922 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 923 continue; 924 } 925 926 if (!isa<FunctionTemplateDecl>(OldD) && 927 !shouldLinkPossiblyHiddenDecl(*I, New)) 928 continue; 929 930 Match = *I; 931 return Ovl_Match; 932 } 933 } else if (isa<UsingDecl>(OldD)) { 934 // We can overload with these, which can show up when doing 935 // redeclaration checks for UsingDecls. 936 assert(Old.getLookupKind() == LookupUsingDeclName); 937 } else if (isa<TagDecl>(OldD)) { 938 // We can always overload with tags by hiding them. 939 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 940 // Optimistically assume that an unresolved using decl will 941 // overload; if it doesn't, we'll have to diagnose during 942 // template instantiation. 943 } else { 944 // (C++ 13p1): 945 // Only function declarations can be overloaded; object and type 946 // declarations cannot be overloaded. 947 Match = *I; 948 return Ovl_NonFunction; 949 } 950 } 951 952 return Ovl_Overload; 953 } 954 955 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 956 bool UseUsingDeclRules) { 957 // C++ [basic.start.main]p2: This function shall not be overloaded. 958 if (New->isMain()) 959 return false; 960 961 // MSVCRT user defined entry points cannot be overloaded. 962 if (New->isMSVCRTEntryPoint()) 963 return false; 964 965 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 966 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 967 968 // C++ [temp.fct]p2: 969 // A function template can be overloaded with other function templates 970 // and with normal (non-template) functions. 971 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 972 return true; 973 974 // Is the function New an overload of the function Old? 975 QualType OldQType = Context.getCanonicalType(Old->getType()); 976 QualType NewQType = Context.getCanonicalType(New->getType()); 977 978 // Compare the signatures (C++ 1.3.10) of the two functions to 979 // determine whether they are overloads. If we find any mismatch 980 // in the signature, they are overloads. 981 982 // If either of these functions is a K&R-style function (no 983 // prototype), then we consider them to have matching signatures. 984 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 985 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 986 return false; 987 988 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 989 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 990 991 // The signature of a function includes the types of its 992 // parameters (C++ 1.3.10), which includes the presence or absence 993 // of the ellipsis; see C++ DR 357). 994 if (OldQType != NewQType && 995 (OldType->getNumParams() != NewType->getNumParams() || 996 OldType->isVariadic() != NewType->isVariadic() || 997 !FunctionParamTypesAreEqual(OldType, NewType))) 998 return true; 999 1000 // C++ [temp.over.link]p4: 1001 // The signature of a function template consists of its function 1002 // signature, its return type and its template parameter list. The names 1003 // of the template parameters are significant only for establishing the 1004 // relationship between the template parameters and the rest of the 1005 // signature. 1006 // 1007 // We check the return type and template parameter lists for function 1008 // templates first; the remaining checks follow. 1009 // 1010 // However, we don't consider either of these when deciding whether 1011 // a member introduced by a shadow declaration is hidden. 1012 if (!UseUsingDeclRules && NewTemplate && 1013 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1014 OldTemplate->getTemplateParameters(), 1015 false, TPL_TemplateMatch) || 1016 OldType->getReturnType() != NewType->getReturnType())) 1017 return true; 1018 1019 // If the function is a class member, its signature includes the 1020 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1021 // 1022 // As part of this, also check whether one of the member functions 1023 // is static, in which case they are not overloads (C++ 1024 // 13.1p2). While not part of the definition of the signature, 1025 // this check is important to determine whether these functions 1026 // can be overloaded. 1027 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1028 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1029 if (OldMethod && NewMethod && 1030 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1031 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1032 if (!UseUsingDeclRules && 1033 (OldMethod->getRefQualifier() == RQ_None || 1034 NewMethod->getRefQualifier() == RQ_None)) { 1035 // C++0x [over.load]p2: 1036 // - Member function declarations with the same name and the same 1037 // parameter-type-list as well as member function template 1038 // declarations with the same name, the same parameter-type-list, and 1039 // the same template parameter lists cannot be overloaded if any of 1040 // them, but not all, have a ref-qualifier (8.3.5). 1041 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1042 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1043 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1044 } 1045 return true; 1046 } 1047 1048 // We may not have applied the implicit const for a constexpr member 1049 // function yet (because we haven't yet resolved whether this is a static 1050 // or non-static member function). Add it now, on the assumption that this 1051 // is a redeclaration of OldMethod. 1052 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1053 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1054 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1055 !isa<CXXConstructorDecl>(NewMethod)) 1056 NewQuals |= Qualifiers::Const; 1057 1058 // We do not allow overloading based off of '__restrict'. 1059 OldQuals &= ~Qualifiers::Restrict; 1060 NewQuals &= ~Qualifiers::Restrict; 1061 if (OldQuals != NewQuals) 1062 return true; 1063 } 1064 1065 // enable_if attributes are an order-sensitive part of the signature. 1066 for (specific_attr_iterator<EnableIfAttr> 1067 NewI = New->specific_attr_begin<EnableIfAttr>(), 1068 NewE = New->specific_attr_end<EnableIfAttr>(), 1069 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1070 OldE = Old->specific_attr_end<EnableIfAttr>(); 1071 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1072 if (NewI == NewE || OldI == OldE) 1073 return true; 1074 llvm::FoldingSetNodeID NewID, OldID; 1075 NewI->getCond()->Profile(NewID, Context, true); 1076 OldI->getCond()->Profile(OldID, Context, true); 1077 if (NewID != OldID) 1078 return true; 1079 } 1080 1081 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) { 1082 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1083 OldTarget = IdentifyCUDATarget(Old); 1084 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1085 return false; 1086 1087 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1088 1089 // Don't allow mixing of HD with other kinds. This guarantees that 1090 // we have only one viable function with this signature on any 1091 // side of CUDA compilation . 1092 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice)) 1093 return false; 1094 1095 // Allow overloading of functions with same signature, but 1096 // different CUDA target attributes. 1097 return NewTarget != OldTarget; 1098 } 1099 1100 // The signatures match; this is not an overload. 1101 return false; 1102 } 1103 1104 /// \brief Checks availability of the function depending on the current 1105 /// function context. Inside an unavailable function, unavailability is ignored. 1106 /// 1107 /// \returns true if \arg FD is unavailable and current context is inside 1108 /// an available function, false otherwise. 1109 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1110 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1111 } 1112 1113 /// \brief Tries a user-defined conversion from From to ToType. 1114 /// 1115 /// Produces an implicit conversion sequence for when a standard conversion 1116 /// is not an option. See TryImplicitConversion for more information. 1117 static ImplicitConversionSequence 1118 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1119 bool SuppressUserConversions, 1120 bool AllowExplicit, 1121 bool InOverloadResolution, 1122 bool CStyle, 1123 bool AllowObjCWritebackConversion, 1124 bool AllowObjCConversionOnExplicit) { 1125 ImplicitConversionSequence ICS; 1126 1127 if (SuppressUserConversions) { 1128 // We're not in the case above, so there is no conversion that 1129 // we can perform. 1130 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1131 return ICS; 1132 } 1133 1134 // Attempt user-defined conversion. 1135 OverloadCandidateSet Conversions(From->getExprLoc(), 1136 OverloadCandidateSet::CSK_Normal); 1137 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1138 Conversions, AllowExplicit, 1139 AllowObjCConversionOnExplicit)) { 1140 case OR_Success: 1141 case OR_Deleted: 1142 ICS.setUserDefined(); 1143 ICS.UserDefined.Before.setAsIdentityConversion(); 1144 // C++ [over.ics.user]p4: 1145 // A conversion of an expression of class type to the same class 1146 // type is given Exact Match rank, and a conversion of an 1147 // expression of class type to a base class of that type is 1148 // given Conversion rank, in spite of the fact that a copy 1149 // constructor (i.e., a user-defined conversion function) is 1150 // called for those cases. 1151 if (CXXConstructorDecl *Constructor 1152 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1153 QualType FromCanon 1154 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1155 QualType ToCanon 1156 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1157 if (Constructor->isCopyConstructor() && 1158 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1159 // Turn this into a "standard" conversion sequence, so that it 1160 // gets ranked with standard conversion sequences. 1161 ICS.setStandard(); 1162 ICS.Standard.setAsIdentityConversion(); 1163 ICS.Standard.setFromType(From->getType()); 1164 ICS.Standard.setAllToTypes(ToType); 1165 ICS.Standard.CopyConstructor = Constructor; 1166 if (ToCanon != FromCanon) 1167 ICS.Standard.Second = ICK_Derived_To_Base; 1168 } 1169 } 1170 break; 1171 1172 case OR_Ambiguous: 1173 ICS.setAmbiguous(); 1174 ICS.Ambiguous.setFromType(From->getType()); 1175 ICS.Ambiguous.setToType(ToType); 1176 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1177 Cand != Conversions.end(); ++Cand) 1178 if (Cand->Viable) 1179 ICS.Ambiguous.addConversion(Cand->Function); 1180 break; 1181 1182 // Fall through. 1183 case OR_No_Viable_Function: 1184 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1185 break; 1186 } 1187 1188 return ICS; 1189 } 1190 1191 /// TryImplicitConversion - Attempt to perform an implicit conversion 1192 /// from the given expression (Expr) to the given type (ToType). This 1193 /// function returns an implicit conversion sequence that can be used 1194 /// to perform the initialization. Given 1195 /// 1196 /// void f(float f); 1197 /// void g(int i) { f(i); } 1198 /// 1199 /// this routine would produce an implicit conversion sequence to 1200 /// describe the initialization of f from i, which will be a standard 1201 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1202 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1203 // 1204 /// Note that this routine only determines how the conversion can be 1205 /// performed; it does not actually perform the conversion. As such, 1206 /// it will not produce any diagnostics if no conversion is available, 1207 /// but will instead return an implicit conversion sequence of kind 1208 /// "BadConversion". 1209 /// 1210 /// If @p SuppressUserConversions, then user-defined conversions are 1211 /// not permitted. 1212 /// If @p AllowExplicit, then explicit user-defined conversions are 1213 /// permitted. 1214 /// 1215 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1216 /// writeback conversion, which allows __autoreleasing id* parameters to 1217 /// be initialized with __strong id* or __weak id* arguments. 1218 static ImplicitConversionSequence 1219 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1220 bool SuppressUserConversions, 1221 bool AllowExplicit, 1222 bool InOverloadResolution, 1223 bool CStyle, 1224 bool AllowObjCWritebackConversion, 1225 bool AllowObjCConversionOnExplicit) { 1226 ImplicitConversionSequence ICS; 1227 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1228 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1229 ICS.setStandard(); 1230 return ICS; 1231 } 1232 1233 if (!S.getLangOpts().CPlusPlus) { 1234 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1235 return ICS; 1236 } 1237 1238 // C++ [over.ics.user]p4: 1239 // A conversion of an expression of class type to the same class 1240 // type is given Exact Match rank, and a conversion of an 1241 // expression of class type to a base class of that type is 1242 // given Conversion rank, in spite of the fact that a copy/move 1243 // constructor (i.e., a user-defined conversion function) is 1244 // called for those cases. 1245 QualType FromType = From->getType(); 1246 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1247 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1248 S.IsDerivedFrom(FromType, ToType))) { 1249 ICS.setStandard(); 1250 ICS.Standard.setAsIdentityConversion(); 1251 ICS.Standard.setFromType(FromType); 1252 ICS.Standard.setAllToTypes(ToType); 1253 1254 // We don't actually check at this point whether there is a valid 1255 // copy/move constructor, since overloading just assumes that it 1256 // exists. When we actually perform initialization, we'll find the 1257 // appropriate constructor to copy the returned object, if needed. 1258 ICS.Standard.CopyConstructor = nullptr; 1259 1260 // Determine whether this is considered a derived-to-base conversion. 1261 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1262 ICS.Standard.Second = ICK_Derived_To_Base; 1263 1264 return ICS; 1265 } 1266 1267 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1268 AllowExplicit, InOverloadResolution, CStyle, 1269 AllowObjCWritebackConversion, 1270 AllowObjCConversionOnExplicit); 1271 } 1272 1273 ImplicitConversionSequence 1274 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1275 bool SuppressUserConversions, 1276 bool AllowExplicit, 1277 bool InOverloadResolution, 1278 bool CStyle, 1279 bool AllowObjCWritebackConversion) { 1280 return ::TryImplicitConversion(*this, From, ToType, 1281 SuppressUserConversions, AllowExplicit, 1282 InOverloadResolution, CStyle, 1283 AllowObjCWritebackConversion, 1284 /*AllowObjCConversionOnExplicit=*/false); 1285 } 1286 1287 /// PerformImplicitConversion - Perform an implicit conversion of the 1288 /// expression From to the type ToType. Returns the 1289 /// converted expression. Flavor is the kind of conversion we're 1290 /// performing, used in the error message. If @p AllowExplicit, 1291 /// explicit user-defined conversions are permitted. 1292 ExprResult 1293 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1294 AssignmentAction Action, bool AllowExplicit) { 1295 ImplicitConversionSequence ICS; 1296 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1297 } 1298 1299 ExprResult 1300 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1301 AssignmentAction Action, bool AllowExplicit, 1302 ImplicitConversionSequence& ICS) { 1303 if (checkPlaceholderForOverload(*this, From)) 1304 return ExprError(); 1305 1306 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1307 bool AllowObjCWritebackConversion 1308 = getLangOpts().ObjCAutoRefCount && 1309 (Action == AA_Passing || Action == AA_Sending); 1310 if (getLangOpts().ObjC1) 1311 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1312 ToType, From->getType(), From); 1313 ICS = ::TryImplicitConversion(*this, From, ToType, 1314 /*SuppressUserConversions=*/false, 1315 AllowExplicit, 1316 /*InOverloadResolution=*/false, 1317 /*CStyle=*/false, 1318 AllowObjCWritebackConversion, 1319 /*AllowObjCConversionOnExplicit=*/false); 1320 return PerformImplicitConversion(From, ToType, ICS, Action); 1321 } 1322 1323 /// \brief Determine whether the conversion from FromType to ToType is a valid 1324 /// conversion that strips "noreturn" off the nested function type. 1325 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1326 QualType &ResultTy) { 1327 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1328 return false; 1329 1330 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1331 // where F adds one of the following at most once: 1332 // - a pointer 1333 // - a member pointer 1334 // - a block pointer 1335 CanQualType CanTo = Context.getCanonicalType(ToType); 1336 CanQualType CanFrom = Context.getCanonicalType(FromType); 1337 Type::TypeClass TyClass = CanTo->getTypeClass(); 1338 if (TyClass != CanFrom->getTypeClass()) return false; 1339 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1340 if (TyClass == Type::Pointer) { 1341 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1342 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1343 } else if (TyClass == Type::BlockPointer) { 1344 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1345 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1346 } else if (TyClass == Type::MemberPointer) { 1347 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1348 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1349 } else { 1350 return false; 1351 } 1352 1353 TyClass = CanTo->getTypeClass(); 1354 if (TyClass != CanFrom->getTypeClass()) return false; 1355 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1356 return false; 1357 } 1358 1359 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1360 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1361 if (!EInfo.getNoReturn()) return false; 1362 1363 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1364 assert(QualType(FromFn, 0).isCanonical()); 1365 if (QualType(FromFn, 0) != CanTo) return false; 1366 1367 ResultTy = ToType; 1368 return true; 1369 } 1370 1371 /// \brief Determine whether the conversion from FromType to ToType is a valid 1372 /// vector conversion. 1373 /// 1374 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1375 /// conversion. 1376 static bool IsVectorConversion(Sema &S, QualType FromType, 1377 QualType ToType, ImplicitConversionKind &ICK) { 1378 // We need at least one of these types to be a vector type to have a vector 1379 // conversion. 1380 if (!ToType->isVectorType() && !FromType->isVectorType()) 1381 return false; 1382 1383 // Identical types require no conversions. 1384 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1385 return false; 1386 1387 // There are no conversions between extended vector types, only identity. 1388 if (ToType->isExtVectorType()) { 1389 // There are no conversions between extended vector types other than the 1390 // identity conversion. 1391 if (FromType->isExtVectorType()) 1392 return false; 1393 1394 // Vector splat from any arithmetic type to a vector. 1395 if (FromType->isArithmeticType()) { 1396 ICK = ICK_Vector_Splat; 1397 return true; 1398 } 1399 } 1400 1401 // We can perform the conversion between vector types in the following cases: 1402 // 1)vector types are equivalent AltiVec and GCC vector types 1403 // 2)lax vector conversions are permitted and the vector types are of the 1404 // same size 1405 if (ToType->isVectorType() && FromType->isVectorType()) { 1406 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1407 S.isLaxVectorConversion(FromType, ToType)) { 1408 ICK = ICK_Vector_Conversion; 1409 return true; 1410 } 1411 } 1412 1413 return false; 1414 } 1415 1416 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1417 bool InOverloadResolution, 1418 StandardConversionSequence &SCS, 1419 bool CStyle); 1420 1421 /// IsStandardConversion - Determines whether there is a standard 1422 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1423 /// expression From to the type ToType. Standard conversion sequences 1424 /// only consider non-class types; for conversions that involve class 1425 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1426 /// contain the standard conversion sequence required to perform this 1427 /// conversion and this routine will return true. Otherwise, this 1428 /// routine will return false and the value of SCS is unspecified. 1429 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1430 bool InOverloadResolution, 1431 StandardConversionSequence &SCS, 1432 bool CStyle, 1433 bool AllowObjCWritebackConversion) { 1434 QualType FromType = From->getType(); 1435 1436 // Standard conversions (C++ [conv]) 1437 SCS.setAsIdentityConversion(); 1438 SCS.IncompatibleObjC = false; 1439 SCS.setFromType(FromType); 1440 SCS.CopyConstructor = nullptr; 1441 1442 // There are no standard conversions for class types in C++, so 1443 // abort early. When overloading in C, however, we do permit them. 1444 if (S.getLangOpts().CPlusPlus && 1445 (FromType->isRecordType() || ToType->isRecordType())) 1446 return false; 1447 1448 // The first conversion can be an lvalue-to-rvalue conversion, 1449 // array-to-pointer conversion, or function-to-pointer conversion 1450 // (C++ 4p1). 1451 1452 if (FromType == S.Context.OverloadTy) { 1453 DeclAccessPair AccessPair; 1454 if (FunctionDecl *Fn 1455 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1456 AccessPair)) { 1457 // We were able to resolve the address of the overloaded function, 1458 // so we can convert to the type of that function. 1459 FromType = Fn->getType(); 1460 SCS.setFromType(FromType); 1461 1462 // we can sometimes resolve &foo<int> regardless of ToType, so check 1463 // if the type matches (identity) or we are converting to bool 1464 if (!S.Context.hasSameUnqualifiedType( 1465 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1466 QualType resultTy; 1467 // if the function type matches except for [[noreturn]], it's ok 1468 if (!S.IsNoReturnConversion(FromType, 1469 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1470 // otherwise, only a boolean conversion is standard 1471 if (!ToType->isBooleanType()) 1472 return false; 1473 } 1474 1475 // Check if the "from" expression is taking the address of an overloaded 1476 // function and recompute the FromType accordingly. Take advantage of the 1477 // fact that non-static member functions *must* have such an address-of 1478 // expression. 1479 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1480 if (Method && !Method->isStatic()) { 1481 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1482 "Non-unary operator on non-static member address"); 1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1484 == UO_AddrOf && 1485 "Non-address-of operator on non-static member address"); 1486 const Type *ClassType 1487 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1488 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1489 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1490 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1491 UO_AddrOf && 1492 "Non-address-of operator for overloaded function expression"); 1493 FromType = S.Context.getPointerType(FromType); 1494 } 1495 1496 // Check that we've computed the proper type after overload resolution. 1497 assert(S.Context.hasSameType( 1498 FromType, 1499 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1500 } else { 1501 return false; 1502 } 1503 } 1504 // Lvalue-to-rvalue conversion (C++11 4.1): 1505 // A glvalue (3.10) of a non-function, non-array type T can 1506 // be converted to a prvalue. 1507 bool argIsLValue = From->isGLValue(); 1508 if (argIsLValue && 1509 !FromType->isFunctionType() && !FromType->isArrayType() && 1510 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1511 SCS.First = ICK_Lvalue_To_Rvalue; 1512 1513 // C11 6.3.2.1p2: 1514 // ... if the lvalue has atomic type, the value has the non-atomic version 1515 // of the type of the lvalue ... 1516 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1517 FromType = Atomic->getValueType(); 1518 1519 // If T is a non-class type, the type of the rvalue is the 1520 // cv-unqualified version of T. Otherwise, the type of the rvalue 1521 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1522 // just strip the qualifiers because they don't matter. 1523 FromType = FromType.getUnqualifiedType(); 1524 } else if (FromType->isArrayType()) { 1525 // Array-to-pointer conversion (C++ 4.2) 1526 SCS.First = ICK_Array_To_Pointer; 1527 1528 // An lvalue or rvalue of type "array of N T" or "array of unknown 1529 // bound of T" can be converted to an rvalue of type "pointer to 1530 // T" (C++ 4.2p1). 1531 FromType = S.Context.getArrayDecayedType(FromType); 1532 1533 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1534 // This conversion is deprecated in C++03 (D.4) 1535 SCS.DeprecatedStringLiteralToCharPtr = true; 1536 1537 // For the purpose of ranking in overload resolution 1538 // (13.3.3.1.1), this conversion is considered an 1539 // array-to-pointer conversion followed by a qualification 1540 // conversion (4.4). (C++ 4.2p2) 1541 SCS.Second = ICK_Identity; 1542 SCS.Third = ICK_Qualification; 1543 SCS.QualificationIncludesObjCLifetime = false; 1544 SCS.setAllToTypes(FromType); 1545 return true; 1546 } 1547 } else if (FromType->isFunctionType() && argIsLValue) { 1548 // Function-to-pointer conversion (C++ 4.3). 1549 SCS.First = ICK_Function_To_Pointer; 1550 1551 // An lvalue of function type T can be converted to an rvalue of 1552 // type "pointer to T." The result is a pointer to the 1553 // function. (C++ 4.3p1). 1554 FromType = S.Context.getPointerType(FromType); 1555 } else { 1556 // We don't require any conversions for the first step. 1557 SCS.First = ICK_Identity; 1558 } 1559 SCS.setToType(0, FromType); 1560 1561 // The second conversion can be an integral promotion, floating 1562 // point promotion, integral conversion, floating point conversion, 1563 // floating-integral conversion, pointer conversion, 1564 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1565 // For overloading in C, this can also be a "compatible-type" 1566 // conversion. 1567 bool IncompatibleObjC = false; 1568 ImplicitConversionKind SecondICK = ICK_Identity; 1569 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1570 // The unqualified versions of the types are the same: there's no 1571 // conversion to do. 1572 SCS.Second = ICK_Identity; 1573 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1574 // Integral promotion (C++ 4.5). 1575 SCS.Second = ICK_Integral_Promotion; 1576 FromType = ToType.getUnqualifiedType(); 1577 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1578 // Floating point promotion (C++ 4.6). 1579 SCS.Second = ICK_Floating_Promotion; 1580 FromType = ToType.getUnqualifiedType(); 1581 } else if (S.IsComplexPromotion(FromType, ToType)) { 1582 // Complex promotion (Clang extension) 1583 SCS.Second = ICK_Complex_Promotion; 1584 FromType = ToType.getUnqualifiedType(); 1585 } else if (ToType->isBooleanType() && 1586 (FromType->isArithmeticType() || 1587 FromType->isAnyPointerType() || 1588 FromType->isBlockPointerType() || 1589 FromType->isMemberPointerType() || 1590 FromType->isNullPtrType())) { 1591 // Boolean conversions (C++ 4.12). 1592 SCS.Second = ICK_Boolean_Conversion; 1593 FromType = S.Context.BoolTy; 1594 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1595 ToType->isIntegralType(S.Context)) { 1596 // Integral conversions (C++ 4.7). 1597 SCS.Second = ICK_Integral_Conversion; 1598 FromType = ToType.getUnqualifiedType(); 1599 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1600 // Complex conversions (C99 6.3.1.6) 1601 SCS.Second = ICK_Complex_Conversion; 1602 FromType = ToType.getUnqualifiedType(); 1603 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1604 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1605 // Complex-real conversions (C99 6.3.1.7) 1606 SCS.Second = ICK_Complex_Real; 1607 FromType = ToType.getUnqualifiedType(); 1608 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1609 // Floating point conversions (C++ 4.8). 1610 SCS.Second = ICK_Floating_Conversion; 1611 FromType = ToType.getUnqualifiedType(); 1612 } else if ((FromType->isRealFloatingType() && 1613 ToType->isIntegralType(S.Context)) || 1614 (FromType->isIntegralOrUnscopedEnumerationType() && 1615 ToType->isRealFloatingType())) { 1616 // Floating-integral conversions (C++ 4.9). 1617 SCS.Second = ICK_Floating_Integral; 1618 FromType = ToType.getUnqualifiedType(); 1619 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1620 SCS.Second = ICK_Block_Pointer_Conversion; 1621 } else if (AllowObjCWritebackConversion && 1622 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1623 SCS.Second = ICK_Writeback_Conversion; 1624 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1625 FromType, IncompatibleObjC)) { 1626 // Pointer conversions (C++ 4.10). 1627 SCS.Second = ICK_Pointer_Conversion; 1628 SCS.IncompatibleObjC = IncompatibleObjC; 1629 FromType = FromType.getUnqualifiedType(); 1630 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1631 InOverloadResolution, FromType)) { 1632 // Pointer to member conversions (4.11). 1633 SCS.Second = ICK_Pointer_Member; 1634 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1635 SCS.Second = SecondICK; 1636 FromType = ToType.getUnqualifiedType(); 1637 } else if (!S.getLangOpts().CPlusPlus && 1638 S.Context.typesAreCompatible(ToType, FromType)) { 1639 // Compatible conversions (Clang extension for C function overloading) 1640 SCS.Second = ICK_Compatible_Conversion; 1641 FromType = ToType.getUnqualifiedType(); 1642 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1643 // Treat a conversion that strips "noreturn" as an identity conversion. 1644 SCS.Second = ICK_NoReturn_Adjustment; 1645 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1646 InOverloadResolution, 1647 SCS, CStyle)) { 1648 SCS.Second = ICK_TransparentUnionConversion; 1649 FromType = ToType; 1650 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1651 CStyle)) { 1652 // tryAtomicConversion has updated the standard conversion sequence 1653 // appropriately. 1654 return true; 1655 } else if (ToType->isEventT() && 1656 From->isIntegerConstantExpr(S.getASTContext()) && 1657 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1658 SCS.Second = ICK_Zero_Event_Conversion; 1659 FromType = ToType; 1660 } else { 1661 // No second conversion required. 1662 SCS.Second = ICK_Identity; 1663 } 1664 SCS.setToType(1, FromType); 1665 1666 QualType CanonFrom; 1667 QualType CanonTo; 1668 // The third conversion can be a qualification conversion (C++ 4p1). 1669 bool ObjCLifetimeConversion; 1670 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1671 ObjCLifetimeConversion)) { 1672 SCS.Third = ICK_Qualification; 1673 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1674 FromType = ToType; 1675 CanonFrom = S.Context.getCanonicalType(FromType); 1676 CanonTo = S.Context.getCanonicalType(ToType); 1677 } else { 1678 // No conversion required 1679 SCS.Third = ICK_Identity; 1680 1681 // C++ [over.best.ics]p6: 1682 // [...] Any difference in top-level cv-qualification is 1683 // subsumed by the initialization itself and does not constitute 1684 // a conversion. [...] 1685 CanonFrom = S.Context.getCanonicalType(FromType); 1686 CanonTo = S.Context.getCanonicalType(ToType); 1687 if (CanonFrom.getLocalUnqualifiedType() 1688 == CanonTo.getLocalUnqualifiedType() && 1689 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1690 FromType = ToType; 1691 CanonFrom = CanonTo; 1692 } 1693 } 1694 SCS.setToType(2, FromType); 1695 1696 if (CanonFrom == CanonTo) 1697 return true; 1698 1699 // If we have not converted the argument type to the parameter type, 1700 // this is a bad conversion sequence, unless we're resolving an overload in C. 1701 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1702 return false; 1703 1704 ExprResult ER = ExprResult{From}; 1705 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1706 /*Diagnose=*/false, 1707 /*DiagnoseCFAudited=*/false, 1708 /*ConvertRHS=*/false); 1709 if (Conv != Sema::Compatible) 1710 return false; 1711 1712 SCS.setAllToTypes(ToType); 1713 // We need to set all three because we want this conversion to rank terribly, 1714 // and we don't know what conversions it may overlap with. 1715 SCS.First = ICK_C_Only_Conversion; 1716 SCS.Second = ICK_C_Only_Conversion; 1717 SCS.Third = ICK_C_Only_Conversion; 1718 return true; 1719 } 1720 1721 static bool 1722 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1723 QualType &ToType, 1724 bool InOverloadResolution, 1725 StandardConversionSequence &SCS, 1726 bool CStyle) { 1727 1728 const RecordType *UT = ToType->getAsUnionType(); 1729 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1730 return false; 1731 // The field to initialize within the transparent union. 1732 RecordDecl *UD = UT->getDecl(); 1733 // It's compatible if the expression matches any of the fields. 1734 for (const auto *it : UD->fields()) { 1735 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1736 CStyle, /*ObjCWritebackConversion=*/false)) { 1737 ToType = it->getType(); 1738 return true; 1739 } 1740 } 1741 return false; 1742 } 1743 1744 /// IsIntegralPromotion - Determines whether the conversion from the 1745 /// expression From (whose potentially-adjusted type is FromType) to 1746 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1747 /// sets PromotedType to the promoted type. 1748 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1749 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1750 // All integers are built-in. 1751 if (!To) { 1752 return false; 1753 } 1754 1755 // An rvalue of type char, signed char, unsigned char, short int, or 1756 // unsigned short int can be converted to an rvalue of type int if 1757 // int can represent all the values of the source type; otherwise, 1758 // the source rvalue can be converted to an rvalue of type unsigned 1759 // int (C++ 4.5p1). 1760 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1761 !FromType->isEnumeralType()) { 1762 if (// We can promote any signed, promotable integer type to an int 1763 (FromType->isSignedIntegerType() || 1764 // We can promote any unsigned integer type whose size is 1765 // less than int to an int. 1766 (!FromType->isSignedIntegerType() && 1767 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1768 return To->getKind() == BuiltinType::Int; 1769 } 1770 1771 return To->getKind() == BuiltinType::UInt; 1772 } 1773 1774 // C++11 [conv.prom]p3: 1775 // A prvalue of an unscoped enumeration type whose underlying type is not 1776 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1777 // following types that can represent all the values of the enumeration 1778 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1779 // unsigned int, long int, unsigned long int, long long int, or unsigned 1780 // long long int. If none of the types in that list can represent all the 1781 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1782 // type can be converted to an rvalue a prvalue of the extended integer type 1783 // with lowest integer conversion rank (4.13) greater than the rank of long 1784 // long in which all the values of the enumeration can be represented. If 1785 // there are two such extended types, the signed one is chosen. 1786 // C++11 [conv.prom]p4: 1787 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1788 // can be converted to a prvalue of its underlying type. Moreover, if 1789 // integral promotion can be applied to its underlying type, a prvalue of an 1790 // unscoped enumeration type whose underlying type is fixed can also be 1791 // converted to a prvalue of the promoted underlying type. 1792 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1793 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1794 // provided for a scoped enumeration. 1795 if (FromEnumType->getDecl()->isScoped()) 1796 return false; 1797 1798 // We can perform an integral promotion to the underlying type of the enum, 1799 // even if that's not the promoted type. Note that the check for promoting 1800 // the underlying type is based on the type alone, and does not consider 1801 // the bitfield-ness of the actual source expression. 1802 if (FromEnumType->getDecl()->isFixed()) { 1803 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1804 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1805 IsIntegralPromotion(nullptr, Underlying, ToType); 1806 } 1807 1808 // We have already pre-calculated the promotion type, so this is trivial. 1809 if (ToType->isIntegerType() && 1810 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1811 return Context.hasSameUnqualifiedType( 1812 ToType, FromEnumType->getDecl()->getPromotionType()); 1813 } 1814 1815 // C++0x [conv.prom]p2: 1816 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1817 // to an rvalue a prvalue of the first of the following types that can 1818 // represent all the values of its underlying type: int, unsigned int, 1819 // long int, unsigned long int, long long int, or unsigned long long int. 1820 // If none of the types in that list can represent all the values of its 1821 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1822 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1823 // type. 1824 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1825 ToType->isIntegerType()) { 1826 // Determine whether the type we're converting from is signed or 1827 // unsigned. 1828 bool FromIsSigned = FromType->isSignedIntegerType(); 1829 uint64_t FromSize = Context.getTypeSize(FromType); 1830 1831 // The types we'll try to promote to, in the appropriate 1832 // order. Try each of these types. 1833 QualType PromoteTypes[6] = { 1834 Context.IntTy, Context.UnsignedIntTy, 1835 Context.LongTy, Context.UnsignedLongTy , 1836 Context.LongLongTy, Context.UnsignedLongLongTy 1837 }; 1838 for (int Idx = 0; Idx < 6; ++Idx) { 1839 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1840 if (FromSize < ToSize || 1841 (FromSize == ToSize && 1842 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1843 // We found the type that we can promote to. If this is the 1844 // type we wanted, we have a promotion. Otherwise, no 1845 // promotion. 1846 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1847 } 1848 } 1849 } 1850 1851 // An rvalue for an integral bit-field (9.6) can be converted to an 1852 // rvalue of type int if int can represent all the values of the 1853 // bit-field; otherwise, it can be converted to unsigned int if 1854 // unsigned int can represent all the values of the bit-field. If 1855 // the bit-field is larger yet, no integral promotion applies to 1856 // it. If the bit-field has an enumerated type, it is treated as any 1857 // other value of that type for promotion purposes (C++ 4.5p3). 1858 // FIXME: We should delay checking of bit-fields until we actually perform the 1859 // conversion. 1860 if (From) { 1861 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1862 llvm::APSInt BitWidth; 1863 if (FromType->isIntegralType(Context) && 1864 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1865 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1866 ToSize = Context.getTypeSize(ToType); 1867 1868 // Are we promoting to an int from a bitfield that fits in an int? 1869 if (BitWidth < ToSize || 1870 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1871 return To->getKind() == BuiltinType::Int; 1872 } 1873 1874 // Are we promoting to an unsigned int from an unsigned bitfield 1875 // that fits into an unsigned int? 1876 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1877 return To->getKind() == BuiltinType::UInt; 1878 } 1879 1880 return false; 1881 } 1882 } 1883 } 1884 1885 // An rvalue of type bool can be converted to an rvalue of type int, 1886 // with false becoming zero and true becoming one (C++ 4.5p4). 1887 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1888 return true; 1889 } 1890 1891 return false; 1892 } 1893 1894 /// IsFloatingPointPromotion - Determines whether the conversion from 1895 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1896 /// returns true and sets PromotedType to the promoted type. 1897 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1898 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1899 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1900 /// An rvalue of type float can be converted to an rvalue of type 1901 /// double. (C++ 4.6p1). 1902 if (FromBuiltin->getKind() == BuiltinType::Float && 1903 ToBuiltin->getKind() == BuiltinType::Double) 1904 return true; 1905 1906 // C99 6.3.1.5p1: 1907 // When a float is promoted to double or long double, or a 1908 // double is promoted to long double [...]. 1909 if (!getLangOpts().CPlusPlus && 1910 (FromBuiltin->getKind() == BuiltinType::Float || 1911 FromBuiltin->getKind() == BuiltinType::Double) && 1912 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1913 return true; 1914 1915 // Half can be promoted to float. 1916 if (!getLangOpts().NativeHalfType && 1917 FromBuiltin->getKind() == BuiltinType::Half && 1918 ToBuiltin->getKind() == BuiltinType::Float) 1919 return true; 1920 } 1921 1922 return false; 1923 } 1924 1925 /// \brief Determine if a conversion is a complex promotion. 1926 /// 1927 /// A complex promotion is defined as a complex -> complex conversion 1928 /// where the conversion between the underlying real types is a 1929 /// floating-point or integral promotion. 1930 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1931 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1932 if (!FromComplex) 1933 return false; 1934 1935 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1936 if (!ToComplex) 1937 return false; 1938 1939 return IsFloatingPointPromotion(FromComplex->getElementType(), 1940 ToComplex->getElementType()) || 1941 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1942 ToComplex->getElementType()); 1943 } 1944 1945 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1946 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1947 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1948 /// if non-empty, will be a pointer to ToType that may or may not have 1949 /// the right set of qualifiers on its pointee. 1950 /// 1951 static QualType 1952 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1953 QualType ToPointee, QualType ToType, 1954 ASTContext &Context, 1955 bool StripObjCLifetime = false) { 1956 assert((FromPtr->getTypeClass() == Type::Pointer || 1957 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1958 "Invalid similarly-qualified pointer type"); 1959 1960 /// Conversions to 'id' subsume cv-qualifier conversions. 1961 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1962 return ToType.getUnqualifiedType(); 1963 1964 QualType CanonFromPointee 1965 = Context.getCanonicalType(FromPtr->getPointeeType()); 1966 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1967 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1968 1969 if (StripObjCLifetime) 1970 Quals.removeObjCLifetime(); 1971 1972 // Exact qualifier match -> return the pointer type we're converting to. 1973 if (CanonToPointee.getLocalQualifiers() == Quals) { 1974 // ToType is exactly what we need. Return it. 1975 if (!ToType.isNull()) 1976 return ToType.getUnqualifiedType(); 1977 1978 // Build a pointer to ToPointee. It has the right qualifiers 1979 // already. 1980 if (isa<ObjCObjectPointerType>(ToType)) 1981 return Context.getObjCObjectPointerType(ToPointee); 1982 return Context.getPointerType(ToPointee); 1983 } 1984 1985 // Just build a canonical type that has the right qualifiers. 1986 QualType QualifiedCanonToPointee 1987 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1988 1989 if (isa<ObjCObjectPointerType>(ToType)) 1990 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1991 return Context.getPointerType(QualifiedCanonToPointee); 1992 } 1993 1994 static bool isNullPointerConstantForConversion(Expr *Expr, 1995 bool InOverloadResolution, 1996 ASTContext &Context) { 1997 // Handle value-dependent integral null pointer constants correctly. 1998 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1999 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2000 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2001 return !InOverloadResolution; 2002 2003 return Expr->isNullPointerConstant(Context, 2004 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2005 : Expr::NPC_ValueDependentIsNull); 2006 } 2007 2008 /// IsPointerConversion - Determines whether the conversion of the 2009 /// expression From, which has the (possibly adjusted) type FromType, 2010 /// can be converted to the type ToType via a pointer conversion (C++ 2011 /// 4.10). If so, returns true and places the converted type (that 2012 /// might differ from ToType in its cv-qualifiers at some level) into 2013 /// ConvertedType. 2014 /// 2015 /// This routine also supports conversions to and from block pointers 2016 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2017 /// pointers to interfaces. FIXME: Once we've determined the 2018 /// appropriate overloading rules for Objective-C, we may want to 2019 /// split the Objective-C checks into a different routine; however, 2020 /// GCC seems to consider all of these conversions to be pointer 2021 /// conversions, so for now they live here. IncompatibleObjC will be 2022 /// set if the conversion is an allowed Objective-C conversion that 2023 /// should result in a warning. 2024 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2025 bool InOverloadResolution, 2026 QualType& ConvertedType, 2027 bool &IncompatibleObjC) { 2028 IncompatibleObjC = false; 2029 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2030 IncompatibleObjC)) 2031 return true; 2032 2033 // Conversion from a null pointer constant to any Objective-C pointer type. 2034 if (ToType->isObjCObjectPointerType() && 2035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2036 ConvertedType = ToType; 2037 return true; 2038 } 2039 2040 // Blocks: Block pointers can be converted to void*. 2041 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2042 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2043 ConvertedType = ToType; 2044 return true; 2045 } 2046 // Blocks: A null pointer constant can be converted to a block 2047 // pointer type. 2048 if (ToType->isBlockPointerType() && 2049 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2050 ConvertedType = ToType; 2051 return true; 2052 } 2053 2054 // If the left-hand-side is nullptr_t, the right side can be a null 2055 // pointer constant. 2056 if (ToType->isNullPtrType() && 2057 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2058 ConvertedType = ToType; 2059 return true; 2060 } 2061 2062 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2063 if (!ToTypePtr) 2064 return false; 2065 2066 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2067 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2068 ConvertedType = ToType; 2069 return true; 2070 } 2071 2072 // Beyond this point, both types need to be pointers 2073 // , including objective-c pointers. 2074 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2075 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2076 !getLangOpts().ObjCAutoRefCount) { 2077 ConvertedType = BuildSimilarlyQualifiedPointerType( 2078 FromType->getAs<ObjCObjectPointerType>(), 2079 ToPointeeType, 2080 ToType, Context); 2081 return true; 2082 } 2083 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2084 if (!FromTypePtr) 2085 return false; 2086 2087 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2088 2089 // If the unqualified pointee types are the same, this can't be a 2090 // pointer conversion, so don't do all of the work below. 2091 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2092 return false; 2093 2094 // An rvalue of type "pointer to cv T," where T is an object type, 2095 // can be converted to an rvalue of type "pointer to cv void" (C++ 2096 // 4.10p2). 2097 if (FromPointeeType->isIncompleteOrObjectType() && 2098 ToPointeeType->isVoidType()) { 2099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2100 ToPointeeType, 2101 ToType, Context, 2102 /*StripObjCLifetime=*/true); 2103 return true; 2104 } 2105 2106 // MSVC allows implicit function to void* type conversion. 2107 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2108 ToPointeeType->isVoidType()) { 2109 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2110 ToPointeeType, 2111 ToType, Context); 2112 return true; 2113 } 2114 2115 // When we're overloading in C, we allow a special kind of pointer 2116 // conversion for compatible-but-not-identical pointee types. 2117 if (!getLangOpts().CPlusPlus && 2118 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2119 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2120 ToPointeeType, 2121 ToType, Context); 2122 return true; 2123 } 2124 2125 // C++ [conv.ptr]p3: 2126 // 2127 // An rvalue of type "pointer to cv D," where D is a class type, 2128 // can be converted to an rvalue of type "pointer to cv B," where 2129 // B is a base class (clause 10) of D. If B is an inaccessible 2130 // (clause 11) or ambiguous (10.2) base class of D, a program that 2131 // necessitates this conversion is ill-formed. The result of the 2132 // conversion is a pointer to the base class sub-object of the 2133 // derived class object. The null pointer value is converted to 2134 // the null pointer value of the destination type. 2135 // 2136 // Note that we do not check for ambiguity or inaccessibility 2137 // here. That is handled by CheckPointerConversion. 2138 if (getLangOpts().CPlusPlus && 2139 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2140 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2141 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2142 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2143 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2144 ToPointeeType, 2145 ToType, Context); 2146 return true; 2147 } 2148 2149 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2150 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2152 ToPointeeType, 2153 ToType, Context); 2154 return true; 2155 } 2156 2157 return false; 2158 } 2159 2160 /// \brief Adopt the given qualifiers for the given type. 2161 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2162 Qualifiers TQs = T.getQualifiers(); 2163 2164 // Check whether qualifiers already match. 2165 if (TQs == Qs) 2166 return T; 2167 2168 if (Qs.compatiblyIncludes(TQs)) 2169 return Context.getQualifiedType(T, Qs); 2170 2171 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2172 } 2173 2174 /// isObjCPointerConversion - Determines whether this is an 2175 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2176 /// with the same arguments and return values. 2177 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2178 QualType& ConvertedType, 2179 bool &IncompatibleObjC) { 2180 if (!getLangOpts().ObjC1) 2181 return false; 2182 2183 // The set of qualifiers on the type we're converting from. 2184 Qualifiers FromQualifiers = FromType.getQualifiers(); 2185 2186 // First, we handle all conversions on ObjC object pointer types. 2187 const ObjCObjectPointerType* ToObjCPtr = 2188 ToType->getAs<ObjCObjectPointerType>(); 2189 const ObjCObjectPointerType *FromObjCPtr = 2190 FromType->getAs<ObjCObjectPointerType>(); 2191 2192 if (ToObjCPtr && FromObjCPtr) { 2193 // If the pointee types are the same (ignoring qualifications), 2194 // then this is not a pointer conversion. 2195 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2196 FromObjCPtr->getPointeeType())) 2197 return false; 2198 2199 // Conversion between Objective-C pointers. 2200 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2201 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2202 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2203 if (getLangOpts().CPlusPlus && LHS && RHS && 2204 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2205 FromObjCPtr->getPointeeType())) 2206 return false; 2207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2208 ToObjCPtr->getPointeeType(), 2209 ToType, Context); 2210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2211 return true; 2212 } 2213 2214 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2215 // Okay: this is some kind of implicit downcast of Objective-C 2216 // interfaces, which is permitted. However, we're going to 2217 // complain about it. 2218 IncompatibleObjC = true; 2219 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2220 ToObjCPtr->getPointeeType(), 2221 ToType, Context); 2222 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2223 return true; 2224 } 2225 } 2226 // Beyond this point, both types need to be C pointers or block pointers. 2227 QualType ToPointeeType; 2228 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2229 ToPointeeType = ToCPtr->getPointeeType(); 2230 else if (const BlockPointerType *ToBlockPtr = 2231 ToType->getAs<BlockPointerType>()) { 2232 // Objective C++: We're able to convert from a pointer to any object 2233 // to a block pointer type. 2234 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2236 return true; 2237 } 2238 ToPointeeType = ToBlockPtr->getPointeeType(); 2239 } 2240 else if (FromType->getAs<BlockPointerType>() && 2241 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2242 // Objective C++: We're able to convert from a block pointer type to a 2243 // pointer to any object. 2244 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2245 return true; 2246 } 2247 else 2248 return false; 2249 2250 QualType FromPointeeType; 2251 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2252 FromPointeeType = FromCPtr->getPointeeType(); 2253 else if (const BlockPointerType *FromBlockPtr = 2254 FromType->getAs<BlockPointerType>()) 2255 FromPointeeType = FromBlockPtr->getPointeeType(); 2256 else 2257 return false; 2258 2259 // If we have pointers to pointers, recursively check whether this 2260 // is an Objective-C conversion. 2261 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2262 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2263 IncompatibleObjC)) { 2264 // We always complain about this conversion. 2265 IncompatibleObjC = true; 2266 ConvertedType = Context.getPointerType(ConvertedType); 2267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2268 return true; 2269 } 2270 // Allow conversion of pointee being objective-c pointer to another one; 2271 // as in I* to id. 2272 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2273 ToPointeeType->getAs<ObjCObjectPointerType>() && 2274 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2275 IncompatibleObjC)) { 2276 2277 ConvertedType = Context.getPointerType(ConvertedType); 2278 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2279 return true; 2280 } 2281 2282 // If we have pointers to functions or blocks, check whether the only 2283 // differences in the argument and result types are in Objective-C 2284 // pointer conversions. If so, we permit the conversion (but 2285 // complain about it). 2286 const FunctionProtoType *FromFunctionType 2287 = FromPointeeType->getAs<FunctionProtoType>(); 2288 const FunctionProtoType *ToFunctionType 2289 = ToPointeeType->getAs<FunctionProtoType>(); 2290 if (FromFunctionType && ToFunctionType) { 2291 // If the function types are exactly the same, this isn't an 2292 // Objective-C pointer conversion. 2293 if (Context.getCanonicalType(FromPointeeType) 2294 == Context.getCanonicalType(ToPointeeType)) 2295 return false; 2296 2297 // Perform the quick checks that will tell us whether these 2298 // function types are obviously different. 2299 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2300 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2301 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2302 return false; 2303 2304 bool HasObjCConversion = false; 2305 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2306 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2307 // Okay, the types match exactly. Nothing to do. 2308 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2309 ToFunctionType->getReturnType(), 2310 ConvertedType, IncompatibleObjC)) { 2311 // Okay, we have an Objective-C pointer conversion. 2312 HasObjCConversion = true; 2313 } else { 2314 // Function types are too different. Abort. 2315 return false; 2316 } 2317 2318 // Check argument types. 2319 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2320 ArgIdx != NumArgs; ++ArgIdx) { 2321 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2322 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2323 if (Context.getCanonicalType(FromArgType) 2324 == Context.getCanonicalType(ToArgType)) { 2325 // Okay, the types match exactly. Nothing to do. 2326 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2327 ConvertedType, IncompatibleObjC)) { 2328 // Okay, we have an Objective-C pointer conversion. 2329 HasObjCConversion = true; 2330 } else { 2331 // Argument types are too different. Abort. 2332 return false; 2333 } 2334 } 2335 2336 if (HasObjCConversion) { 2337 // We had an Objective-C conversion. Allow this pointer 2338 // conversion, but complain about it. 2339 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2340 IncompatibleObjC = true; 2341 return true; 2342 } 2343 } 2344 2345 return false; 2346 } 2347 2348 /// \brief Determine whether this is an Objective-C writeback conversion, 2349 /// used for parameter passing when performing automatic reference counting. 2350 /// 2351 /// \param FromType The type we're converting form. 2352 /// 2353 /// \param ToType The type we're converting to. 2354 /// 2355 /// \param ConvertedType The type that will be produced after applying 2356 /// this conversion. 2357 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2358 QualType &ConvertedType) { 2359 if (!getLangOpts().ObjCAutoRefCount || 2360 Context.hasSameUnqualifiedType(FromType, ToType)) 2361 return false; 2362 2363 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2364 QualType ToPointee; 2365 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2366 ToPointee = ToPointer->getPointeeType(); 2367 else 2368 return false; 2369 2370 Qualifiers ToQuals = ToPointee.getQualifiers(); 2371 if (!ToPointee->isObjCLifetimeType() || 2372 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2373 !ToQuals.withoutObjCLifetime().empty()) 2374 return false; 2375 2376 // Argument must be a pointer to __strong to __weak. 2377 QualType FromPointee; 2378 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2379 FromPointee = FromPointer->getPointeeType(); 2380 else 2381 return false; 2382 2383 Qualifiers FromQuals = FromPointee.getQualifiers(); 2384 if (!FromPointee->isObjCLifetimeType() || 2385 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2386 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2387 return false; 2388 2389 // Make sure that we have compatible qualifiers. 2390 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2391 if (!ToQuals.compatiblyIncludes(FromQuals)) 2392 return false; 2393 2394 // Remove qualifiers from the pointee type we're converting from; they 2395 // aren't used in the compatibility check belong, and we'll be adding back 2396 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2397 FromPointee = FromPointee.getUnqualifiedType(); 2398 2399 // The unqualified form of the pointee types must be compatible. 2400 ToPointee = ToPointee.getUnqualifiedType(); 2401 bool IncompatibleObjC; 2402 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2403 FromPointee = ToPointee; 2404 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2405 IncompatibleObjC)) 2406 return false; 2407 2408 /// \brief Construct the type we're converting to, which is a pointer to 2409 /// __autoreleasing pointee. 2410 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2411 ConvertedType = Context.getPointerType(FromPointee); 2412 return true; 2413 } 2414 2415 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2416 QualType& ConvertedType) { 2417 QualType ToPointeeType; 2418 if (const BlockPointerType *ToBlockPtr = 2419 ToType->getAs<BlockPointerType>()) 2420 ToPointeeType = ToBlockPtr->getPointeeType(); 2421 else 2422 return false; 2423 2424 QualType FromPointeeType; 2425 if (const BlockPointerType *FromBlockPtr = 2426 FromType->getAs<BlockPointerType>()) 2427 FromPointeeType = FromBlockPtr->getPointeeType(); 2428 else 2429 return false; 2430 // We have pointer to blocks, check whether the only 2431 // differences in the argument and result types are in Objective-C 2432 // pointer conversions. If so, we permit the conversion. 2433 2434 const FunctionProtoType *FromFunctionType 2435 = FromPointeeType->getAs<FunctionProtoType>(); 2436 const FunctionProtoType *ToFunctionType 2437 = ToPointeeType->getAs<FunctionProtoType>(); 2438 2439 if (!FromFunctionType || !ToFunctionType) 2440 return false; 2441 2442 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2443 return true; 2444 2445 // Perform the quick checks that will tell us whether these 2446 // function types are obviously different. 2447 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2448 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2449 return false; 2450 2451 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2452 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2453 if (FromEInfo != ToEInfo) 2454 return false; 2455 2456 bool IncompatibleObjC = false; 2457 if (Context.hasSameType(FromFunctionType->getReturnType(), 2458 ToFunctionType->getReturnType())) { 2459 // Okay, the types match exactly. Nothing to do. 2460 } else { 2461 QualType RHS = FromFunctionType->getReturnType(); 2462 QualType LHS = ToFunctionType->getReturnType(); 2463 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2464 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2465 LHS = LHS.getUnqualifiedType(); 2466 2467 if (Context.hasSameType(RHS,LHS)) { 2468 // OK exact match. 2469 } else if (isObjCPointerConversion(RHS, LHS, 2470 ConvertedType, IncompatibleObjC)) { 2471 if (IncompatibleObjC) 2472 return false; 2473 // Okay, we have an Objective-C pointer conversion. 2474 } 2475 else 2476 return false; 2477 } 2478 2479 // Check argument types. 2480 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2481 ArgIdx != NumArgs; ++ArgIdx) { 2482 IncompatibleObjC = false; 2483 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2484 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2485 if (Context.hasSameType(FromArgType, ToArgType)) { 2486 // Okay, the types match exactly. Nothing to do. 2487 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2488 ConvertedType, IncompatibleObjC)) { 2489 if (IncompatibleObjC) 2490 return false; 2491 // Okay, we have an Objective-C pointer conversion. 2492 } else 2493 // Argument types are too different. Abort. 2494 return false; 2495 } 2496 if (LangOpts.ObjCAutoRefCount && 2497 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2498 ToFunctionType)) 2499 return false; 2500 2501 ConvertedType = ToType; 2502 return true; 2503 } 2504 2505 enum { 2506 ft_default, 2507 ft_different_class, 2508 ft_parameter_arity, 2509 ft_parameter_mismatch, 2510 ft_return_type, 2511 ft_qualifer_mismatch, 2512 ft_addr_enable_if 2513 }; 2514 2515 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2516 /// function types. Catches different number of parameter, mismatch in 2517 /// parameter types, and different return types. 2518 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2519 QualType FromType, QualType ToType) { 2520 // If either type is not valid, include no extra info. 2521 if (FromType.isNull() || ToType.isNull()) { 2522 PDiag << ft_default; 2523 return; 2524 } 2525 2526 // Get the function type from the pointers. 2527 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2528 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2529 *ToMember = ToType->getAs<MemberPointerType>(); 2530 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2531 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2532 << QualType(FromMember->getClass(), 0); 2533 return; 2534 } 2535 FromType = FromMember->getPointeeType(); 2536 ToType = ToMember->getPointeeType(); 2537 } 2538 2539 if (FromType->isPointerType()) 2540 FromType = FromType->getPointeeType(); 2541 if (ToType->isPointerType()) 2542 ToType = ToType->getPointeeType(); 2543 2544 // Remove references. 2545 FromType = FromType.getNonReferenceType(); 2546 ToType = ToType.getNonReferenceType(); 2547 2548 // Don't print extra info for non-specialized template functions. 2549 if (FromType->isInstantiationDependentType() && 2550 !FromType->getAs<TemplateSpecializationType>()) { 2551 PDiag << ft_default; 2552 return; 2553 } 2554 2555 // No extra info for same types. 2556 if (Context.hasSameType(FromType, ToType)) { 2557 PDiag << ft_default; 2558 return; 2559 } 2560 2561 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2562 *ToFunction = ToType->getAs<FunctionProtoType>(); 2563 2564 // Both types need to be function types. 2565 if (!FromFunction || !ToFunction) { 2566 PDiag << ft_default; 2567 return; 2568 } 2569 2570 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2571 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2572 << FromFunction->getNumParams(); 2573 return; 2574 } 2575 2576 // Handle different parameter types. 2577 unsigned ArgPos; 2578 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2579 PDiag << ft_parameter_mismatch << ArgPos + 1 2580 << ToFunction->getParamType(ArgPos) 2581 << FromFunction->getParamType(ArgPos); 2582 return; 2583 } 2584 2585 // Handle different return type. 2586 if (!Context.hasSameType(FromFunction->getReturnType(), 2587 ToFunction->getReturnType())) { 2588 PDiag << ft_return_type << ToFunction->getReturnType() 2589 << FromFunction->getReturnType(); 2590 return; 2591 } 2592 2593 unsigned FromQuals = FromFunction->getTypeQuals(), 2594 ToQuals = ToFunction->getTypeQuals(); 2595 if (FromQuals != ToQuals) { 2596 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2597 return; 2598 } 2599 2600 // Unable to find a difference, so add no extra info. 2601 PDiag << ft_default; 2602 } 2603 2604 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2605 /// for equality of their argument types. Caller has already checked that 2606 /// they have same number of arguments. If the parameters are different, 2607 /// ArgPos will have the parameter index of the first different parameter. 2608 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2609 const FunctionProtoType *NewType, 2610 unsigned *ArgPos) { 2611 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2612 N = NewType->param_type_begin(), 2613 E = OldType->param_type_end(); 2614 O && (O != E); ++O, ++N) { 2615 if (!Context.hasSameType(O->getUnqualifiedType(), 2616 N->getUnqualifiedType())) { 2617 if (ArgPos) 2618 *ArgPos = O - OldType->param_type_begin(); 2619 return false; 2620 } 2621 } 2622 return true; 2623 } 2624 2625 /// CheckPointerConversion - Check the pointer conversion from the 2626 /// expression From to the type ToType. This routine checks for 2627 /// ambiguous or inaccessible derived-to-base pointer 2628 /// conversions for which IsPointerConversion has already returned 2629 /// true. It returns true and produces a diagnostic if there was an 2630 /// error, or returns false otherwise. 2631 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2632 CastKind &Kind, 2633 CXXCastPath& BasePath, 2634 bool IgnoreBaseAccess) { 2635 QualType FromType = From->getType(); 2636 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2637 2638 Kind = CK_BitCast; 2639 2640 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2641 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2642 Expr::NPCK_ZeroExpression) { 2643 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2644 DiagRuntimeBehavior(From->getExprLoc(), From, 2645 PDiag(diag::warn_impcast_bool_to_null_pointer) 2646 << ToType << From->getSourceRange()); 2647 else if (!isUnevaluatedContext()) 2648 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2649 << ToType << From->getSourceRange(); 2650 } 2651 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2652 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2653 QualType FromPointeeType = FromPtrType->getPointeeType(), 2654 ToPointeeType = ToPtrType->getPointeeType(); 2655 2656 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2657 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2658 // We must have a derived-to-base conversion. Check an 2659 // ambiguous or inaccessible conversion. 2660 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2661 From->getExprLoc(), 2662 From->getSourceRange(), &BasePath, 2663 IgnoreBaseAccess)) 2664 return true; 2665 2666 // The conversion was successful. 2667 Kind = CK_DerivedToBase; 2668 } 2669 2670 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() && 2671 ToPointeeType->isVoidType()) { 2672 assert(getLangOpts().MSVCCompat && 2673 "this should only be possible with MSVCCompat!"); 2674 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2675 << From->getSourceRange(); 2676 } 2677 } 2678 } else if (const ObjCObjectPointerType *ToPtrType = 2679 ToType->getAs<ObjCObjectPointerType>()) { 2680 if (const ObjCObjectPointerType *FromPtrType = 2681 FromType->getAs<ObjCObjectPointerType>()) { 2682 // Objective-C++ conversions are always okay. 2683 // FIXME: We should have a different class of conversions for the 2684 // Objective-C++ implicit conversions. 2685 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2686 return false; 2687 } else if (FromType->isBlockPointerType()) { 2688 Kind = CK_BlockPointerToObjCPointerCast; 2689 } else { 2690 Kind = CK_CPointerToObjCPointerCast; 2691 } 2692 } else if (ToType->isBlockPointerType()) { 2693 if (!FromType->isBlockPointerType()) 2694 Kind = CK_AnyPointerToBlockPointerCast; 2695 } 2696 2697 // We shouldn't fall into this case unless it's valid for other 2698 // reasons. 2699 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2700 Kind = CK_NullToPointer; 2701 2702 return false; 2703 } 2704 2705 /// IsMemberPointerConversion - Determines whether the conversion of the 2706 /// expression From, which has the (possibly adjusted) type FromType, can be 2707 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2708 /// If so, returns true and places the converted type (that might differ from 2709 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2710 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2711 QualType ToType, 2712 bool InOverloadResolution, 2713 QualType &ConvertedType) { 2714 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2715 if (!ToTypePtr) 2716 return false; 2717 2718 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2719 if (From->isNullPointerConstant(Context, 2720 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2721 : Expr::NPC_ValueDependentIsNull)) { 2722 ConvertedType = ToType; 2723 return true; 2724 } 2725 2726 // Otherwise, both types have to be member pointers. 2727 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2728 if (!FromTypePtr) 2729 return false; 2730 2731 // A pointer to member of B can be converted to a pointer to member of D, 2732 // where D is derived from B (C++ 4.11p2). 2733 QualType FromClass(FromTypePtr->getClass(), 0); 2734 QualType ToClass(ToTypePtr->getClass(), 0); 2735 2736 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2737 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2738 IsDerivedFrom(ToClass, FromClass)) { 2739 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2740 ToClass.getTypePtr()); 2741 return true; 2742 } 2743 2744 return false; 2745 } 2746 2747 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2748 /// expression From to the type ToType. This routine checks for ambiguous or 2749 /// virtual or inaccessible base-to-derived member pointer conversions 2750 /// for which IsMemberPointerConversion has already returned true. It returns 2751 /// true and produces a diagnostic if there was an error, or returns false 2752 /// otherwise. 2753 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2754 CastKind &Kind, 2755 CXXCastPath &BasePath, 2756 bool IgnoreBaseAccess) { 2757 QualType FromType = From->getType(); 2758 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2759 if (!FromPtrType) { 2760 // This must be a null pointer to member pointer conversion 2761 assert(From->isNullPointerConstant(Context, 2762 Expr::NPC_ValueDependentIsNull) && 2763 "Expr must be null pointer constant!"); 2764 Kind = CK_NullToMemberPointer; 2765 return false; 2766 } 2767 2768 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2769 assert(ToPtrType && "No member pointer cast has a target type " 2770 "that is not a member pointer."); 2771 2772 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2773 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2774 2775 // FIXME: What about dependent types? 2776 assert(FromClass->isRecordType() && "Pointer into non-class."); 2777 assert(ToClass->isRecordType() && "Pointer into non-class."); 2778 2779 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2780 /*DetectVirtual=*/true); 2781 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2782 assert(DerivationOkay && 2783 "Should not have been called if derivation isn't OK."); 2784 (void)DerivationOkay; 2785 2786 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2787 getUnqualifiedType())) { 2788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2789 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2790 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2791 return true; 2792 } 2793 2794 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2795 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2796 << FromClass << ToClass << QualType(VBase, 0) 2797 << From->getSourceRange(); 2798 return true; 2799 } 2800 2801 if (!IgnoreBaseAccess) 2802 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2803 Paths.front(), 2804 diag::err_downcast_from_inaccessible_base); 2805 2806 // Must be a base to derived member conversion. 2807 BuildBasePathArray(Paths, BasePath); 2808 Kind = CK_BaseToDerivedMemberPointer; 2809 return false; 2810 } 2811 2812 /// Determine whether the lifetime conversion between the two given 2813 /// qualifiers sets is nontrivial. 2814 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2815 Qualifiers ToQuals) { 2816 // Converting anything to const __unsafe_unretained is trivial. 2817 if (ToQuals.hasConst() && 2818 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2819 return false; 2820 2821 return true; 2822 } 2823 2824 /// IsQualificationConversion - Determines whether the conversion from 2825 /// an rvalue of type FromType to ToType is a qualification conversion 2826 /// (C++ 4.4). 2827 /// 2828 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2829 /// when the qualification conversion involves a change in the Objective-C 2830 /// object lifetime. 2831 bool 2832 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2833 bool CStyle, bool &ObjCLifetimeConversion) { 2834 FromType = Context.getCanonicalType(FromType); 2835 ToType = Context.getCanonicalType(ToType); 2836 ObjCLifetimeConversion = false; 2837 2838 // If FromType and ToType are the same type, this is not a 2839 // qualification conversion. 2840 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2841 return false; 2842 2843 // (C++ 4.4p4): 2844 // A conversion can add cv-qualifiers at levels other than the first 2845 // in multi-level pointers, subject to the following rules: [...] 2846 bool PreviousToQualsIncludeConst = true; 2847 bool UnwrappedAnyPointer = false; 2848 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2849 // Within each iteration of the loop, we check the qualifiers to 2850 // determine if this still looks like a qualification 2851 // conversion. Then, if all is well, we unwrap one more level of 2852 // pointers or pointers-to-members and do it all again 2853 // until there are no more pointers or pointers-to-members left to 2854 // unwrap. 2855 UnwrappedAnyPointer = true; 2856 2857 Qualifiers FromQuals = FromType.getQualifiers(); 2858 Qualifiers ToQuals = ToType.getQualifiers(); 2859 2860 // Objective-C ARC: 2861 // Check Objective-C lifetime conversions. 2862 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2863 UnwrappedAnyPointer) { 2864 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2865 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2866 ObjCLifetimeConversion = true; 2867 FromQuals.removeObjCLifetime(); 2868 ToQuals.removeObjCLifetime(); 2869 } else { 2870 // Qualification conversions cannot cast between different 2871 // Objective-C lifetime qualifiers. 2872 return false; 2873 } 2874 } 2875 2876 // Allow addition/removal of GC attributes but not changing GC attributes. 2877 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2878 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2879 FromQuals.removeObjCGCAttr(); 2880 ToQuals.removeObjCGCAttr(); 2881 } 2882 2883 // -- for every j > 0, if const is in cv 1,j then const is in cv 2884 // 2,j, and similarly for volatile. 2885 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2886 return false; 2887 2888 // -- if the cv 1,j and cv 2,j are different, then const is in 2889 // every cv for 0 < k < j. 2890 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2891 && !PreviousToQualsIncludeConst) 2892 return false; 2893 2894 // Keep track of whether all prior cv-qualifiers in the "to" type 2895 // include const. 2896 PreviousToQualsIncludeConst 2897 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2898 } 2899 2900 // We are left with FromType and ToType being the pointee types 2901 // after unwrapping the original FromType and ToType the same number 2902 // of types. If we unwrapped any pointers, and if FromType and 2903 // ToType have the same unqualified type (since we checked 2904 // qualifiers above), then this is a qualification conversion. 2905 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2906 } 2907 2908 /// \brief - Determine whether this is a conversion from a scalar type to an 2909 /// atomic type. 2910 /// 2911 /// If successful, updates \c SCS's second and third steps in the conversion 2912 /// sequence to finish the conversion. 2913 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2914 bool InOverloadResolution, 2915 StandardConversionSequence &SCS, 2916 bool CStyle) { 2917 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2918 if (!ToAtomic) 2919 return false; 2920 2921 StandardConversionSequence InnerSCS; 2922 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2923 InOverloadResolution, InnerSCS, 2924 CStyle, /*AllowObjCWritebackConversion=*/false)) 2925 return false; 2926 2927 SCS.Second = InnerSCS.Second; 2928 SCS.setToType(1, InnerSCS.getToType(1)); 2929 SCS.Third = InnerSCS.Third; 2930 SCS.QualificationIncludesObjCLifetime 2931 = InnerSCS.QualificationIncludesObjCLifetime; 2932 SCS.setToType(2, InnerSCS.getToType(2)); 2933 return true; 2934 } 2935 2936 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2937 CXXConstructorDecl *Constructor, 2938 QualType Type) { 2939 const FunctionProtoType *CtorType = 2940 Constructor->getType()->getAs<FunctionProtoType>(); 2941 if (CtorType->getNumParams() > 0) { 2942 QualType FirstArg = CtorType->getParamType(0); 2943 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2944 return true; 2945 } 2946 return false; 2947 } 2948 2949 static OverloadingResult 2950 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2951 CXXRecordDecl *To, 2952 UserDefinedConversionSequence &User, 2953 OverloadCandidateSet &CandidateSet, 2954 bool AllowExplicit) { 2955 DeclContext::lookup_result R = S.LookupConstructors(To); 2956 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2957 Con != ConEnd; ++Con) { 2958 NamedDecl *D = *Con; 2959 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2960 2961 // Find the constructor (which may be a template). 2962 CXXConstructorDecl *Constructor = nullptr; 2963 FunctionTemplateDecl *ConstructorTmpl 2964 = dyn_cast<FunctionTemplateDecl>(D); 2965 if (ConstructorTmpl) 2966 Constructor 2967 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2968 else 2969 Constructor = cast<CXXConstructorDecl>(D); 2970 2971 bool Usable = !Constructor->isInvalidDecl() && 2972 S.isInitListConstructor(Constructor) && 2973 (AllowExplicit || !Constructor->isExplicit()); 2974 if (Usable) { 2975 // If the first argument is (a reference to) the target type, 2976 // suppress conversions. 2977 bool SuppressUserConversions = 2978 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2979 if (ConstructorTmpl) 2980 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2981 /*ExplicitArgs*/ nullptr, 2982 From, CandidateSet, 2983 SuppressUserConversions); 2984 else 2985 S.AddOverloadCandidate(Constructor, FoundDecl, 2986 From, CandidateSet, 2987 SuppressUserConversions); 2988 } 2989 } 2990 2991 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2992 2993 OverloadCandidateSet::iterator Best; 2994 switch (auto Result = 2995 CandidateSet.BestViableFunction(S, From->getLocStart(), 2996 Best, true)) { 2997 case OR_Deleted: 2998 case OR_Success: { 2999 // Record the standard conversion we used and the conversion function. 3000 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3001 QualType ThisType = Constructor->getThisType(S.Context); 3002 // Initializer lists don't have conversions as such. 3003 User.Before.setAsIdentityConversion(); 3004 User.HadMultipleCandidates = HadMultipleCandidates; 3005 User.ConversionFunction = Constructor; 3006 User.FoundConversionFunction = Best->FoundDecl; 3007 User.After.setAsIdentityConversion(); 3008 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3009 User.After.setAllToTypes(ToType); 3010 return Result; 3011 } 3012 3013 case OR_No_Viable_Function: 3014 return OR_No_Viable_Function; 3015 case OR_Ambiguous: 3016 return OR_Ambiguous; 3017 } 3018 3019 llvm_unreachable("Invalid OverloadResult!"); 3020 } 3021 3022 /// Determines whether there is a user-defined conversion sequence 3023 /// (C++ [over.ics.user]) that converts expression From to the type 3024 /// ToType. If such a conversion exists, User will contain the 3025 /// user-defined conversion sequence that performs such a conversion 3026 /// and this routine will return true. Otherwise, this routine returns 3027 /// false and User is unspecified. 3028 /// 3029 /// \param AllowExplicit true if the conversion should consider C++0x 3030 /// "explicit" conversion functions as well as non-explicit conversion 3031 /// functions (C++0x [class.conv.fct]p2). 3032 /// 3033 /// \param AllowObjCConversionOnExplicit true if the conversion should 3034 /// allow an extra Objective-C pointer conversion on uses of explicit 3035 /// constructors. Requires \c AllowExplicit to also be set. 3036 static OverloadingResult 3037 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3038 UserDefinedConversionSequence &User, 3039 OverloadCandidateSet &CandidateSet, 3040 bool AllowExplicit, 3041 bool AllowObjCConversionOnExplicit) { 3042 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3043 3044 // Whether we will only visit constructors. 3045 bool ConstructorsOnly = false; 3046 3047 // If the type we are conversion to is a class type, enumerate its 3048 // constructors. 3049 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3050 // C++ [over.match.ctor]p1: 3051 // When objects of class type are direct-initialized (8.5), or 3052 // copy-initialized from an expression of the same or a 3053 // derived class type (8.5), overload resolution selects the 3054 // constructor. [...] For copy-initialization, the candidate 3055 // functions are all the converting constructors (12.3.1) of 3056 // that class. The argument list is the expression-list within 3057 // the parentheses of the initializer. 3058 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3059 (From->getType()->getAs<RecordType>() && 3060 S.IsDerivedFrom(From->getType(), ToType))) 3061 ConstructorsOnly = true; 3062 3063 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3064 // RequireCompleteType may have returned true due to some invalid decl 3065 // during template instantiation, but ToType may be complete enough now 3066 // to try to recover. 3067 if (ToType->isIncompleteType()) { 3068 // We're not going to find any constructors. 3069 } else if (CXXRecordDecl *ToRecordDecl 3070 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3071 3072 Expr **Args = &From; 3073 unsigned NumArgs = 1; 3074 bool ListInitializing = false; 3075 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3076 // But first, see if there is an init-list-constructor that will work. 3077 OverloadingResult Result = IsInitializerListConstructorConversion( 3078 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3079 if (Result != OR_No_Viable_Function) 3080 return Result; 3081 // Never mind. 3082 CandidateSet.clear(); 3083 3084 // If we're list-initializing, we pass the individual elements as 3085 // arguments, not the entire list. 3086 Args = InitList->getInits(); 3087 NumArgs = InitList->getNumInits(); 3088 ListInitializing = true; 3089 } 3090 3091 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3092 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3093 Con != ConEnd; ++Con) { 3094 NamedDecl *D = *Con; 3095 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3096 3097 // Find the constructor (which may be a template). 3098 CXXConstructorDecl *Constructor = nullptr; 3099 FunctionTemplateDecl *ConstructorTmpl 3100 = dyn_cast<FunctionTemplateDecl>(D); 3101 if (ConstructorTmpl) 3102 Constructor 3103 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3104 else 3105 Constructor = cast<CXXConstructorDecl>(D); 3106 3107 bool Usable = !Constructor->isInvalidDecl(); 3108 if (ListInitializing) 3109 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3110 else 3111 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3112 if (Usable) { 3113 bool SuppressUserConversions = !ConstructorsOnly; 3114 if (SuppressUserConversions && ListInitializing) { 3115 SuppressUserConversions = false; 3116 if (NumArgs == 1) { 3117 // If the first argument is (a reference to) the target type, 3118 // suppress conversions. 3119 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3120 S.Context, Constructor, ToType); 3121 } 3122 } 3123 if (ConstructorTmpl) 3124 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3125 /*ExplicitArgs*/ nullptr, 3126 llvm::makeArrayRef(Args, NumArgs), 3127 CandidateSet, SuppressUserConversions); 3128 else 3129 // Allow one user-defined conversion when user specifies a 3130 // From->ToType conversion via an static cast (c-style, etc). 3131 S.AddOverloadCandidate(Constructor, FoundDecl, 3132 llvm::makeArrayRef(Args, NumArgs), 3133 CandidateSet, SuppressUserConversions); 3134 } 3135 } 3136 } 3137 } 3138 3139 // Enumerate conversion functions, if we're allowed to. 3140 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3141 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3142 // No conversion functions from incomplete types. 3143 } else if (const RecordType *FromRecordType 3144 = From->getType()->getAs<RecordType>()) { 3145 if (CXXRecordDecl *FromRecordDecl 3146 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3147 // Add all of the conversion functions as candidates. 3148 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3149 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3150 DeclAccessPair FoundDecl = I.getPair(); 3151 NamedDecl *D = FoundDecl.getDecl(); 3152 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3153 if (isa<UsingShadowDecl>(D)) 3154 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3155 3156 CXXConversionDecl *Conv; 3157 FunctionTemplateDecl *ConvTemplate; 3158 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3159 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3160 else 3161 Conv = cast<CXXConversionDecl>(D); 3162 3163 if (AllowExplicit || !Conv->isExplicit()) { 3164 if (ConvTemplate) 3165 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3166 ActingContext, From, ToType, 3167 CandidateSet, 3168 AllowObjCConversionOnExplicit); 3169 else 3170 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3171 From, ToType, CandidateSet, 3172 AllowObjCConversionOnExplicit); 3173 } 3174 } 3175 } 3176 } 3177 3178 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3179 3180 OverloadCandidateSet::iterator Best; 3181 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3182 Best, true)) { 3183 case OR_Success: 3184 case OR_Deleted: 3185 // Record the standard conversion we used and the conversion function. 3186 if (CXXConstructorDecl *Constructor 3187 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3188 // C++ [over.ics.user]p1: 3189 // If the user-defined conversion is specified by a 3190 // constructor (12.3.1), the initial standard conversion 3191 // sequence converts the source type to the type required by 3192 // the argument of the constructor. 3193 // 3194 QualType ThisType = Constructor->getThisType(S.Context); 3195 if (isa<InitListExpr>(From)) { 3196 // Initializer lists don't have conversions as such. 3197 User.Before.setAsIdentityConversion(); 3198 } else { 3199 if (Best->Conversions[0].isEllipsis()) 3200 User.EllipsisConversion = true; 3201 else { 3202 User.Before = Best->Conversions[0].Standard; 3203 User.EllipsisConversion = false; 3204 } 3205 } 3206 User.HadMultipleCandidates = HadMultipleCandidates; 3207 User.ConversionFunction = Constructor; 3208 User.FoundConversionFunction = Best->FoundDecl; 3209 User.After.setAsIdentityConversion(); 3210 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3211 User.After.setAllToTypes(ToType); 3212 return Result; 3213 } 3214 if (CXXConversionDecl *Conversion 3215 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3216 // C++ [over.ics.user]p1: 3217 // 3218 // [...] If the user-defined conversion is specified by a 3219 // conversion function (12.3.2), the initial standard 3220 // conversion sequence converts the source type to the 3221 // implicit object parameter of the conversion function. 3222 User.Before = Best->Conversions[0].Standard; 3223 User.HadMultipleCandidates = HadMultipleCandidates; 3224 User.ConversionFunction = Conversion; 3225 User.FoundConversionFunction = Best->FoundDecl; 3226 User.EllipsisConversion = false; 3227 3228 // C++ [over.ics.user]p2: 3229 // The second standard conversion sequence converts the 3230 // result of the user-defined conversion to the target type 3231 // for the sequence. Since an implicit conversion sequence 3232 // is an initialization, the special rules for 3233 // initialization by user-defined conversion apply when 3234 // selecting the best user-defined conversion for a 3235 // user-defined conversion sequence (see 13.3.3 and 3236 // 13.3.3.1). 3237 User.After = Best->FinalConversion; 3238 return Result; 3239 } 3240 llvm_unreachable("Not a constructor or conversion function?"); 3241 3242 case OR_No_Viable_Function: 3243 return OR_No_Viable_Function; 3244 3245 case OR_Ambiguous: 3246 return OR_Ambiguous; 3247 } 3248 3249 llvm_unreachable("Invalid OverloadResult!"); 3250 } 3251 3252 bool 3253 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3254 ImplicitConversionSequence ICS; 3255 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3256 OverloadCandidateSet::CSK_Normal); 3257 OverloadingResult OvResult = 3258 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3259 CandidateSet, false, false); 3260 if (OvResult == OR_Ambiguous) 3261 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3262 << From->getType() << ToType << From->getSourceRange(); 3263 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3264 if (!RequireCompleteType(From->getLocStart(), ToType, 3265 diag::err_typecheck_nonviable_condition_incomplete, 3266 From->getType(), From->getSourceRange())) 3267 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3268 << false << From->getType() << From->getSourceRange() << ToType; 3269 } else 3270 return false; 3271 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3272 return true; 3273 } 3274 3275 /// \brief Compare the user-defined conversion functions or constructors 3276 /// of two user-defined conversion sequences to determine whether any ordering 3277 /// is possible. 3278 static ImplicitConversionSequence::CompareKind 3279 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3280 FunctionDecl *Function2) { 3281 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3282 return ImplicitConversionSequence::Indistinguishable; 3283 3284 // Objective-C++: 3285 // If both conversion functions are implicitly-declared conversions from 3286 // a lambda closure type to a function pointer and a block pointer, 3287 // respectively, always prefer the conversion to a function pointer, 3288 // because the function pointer is more lightweight and is more likely 3289 // to keep code working. 3290 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3291 if (!Conv1) 3292 return ImplicitConversionSequence::Indistinguishable; 3293 3294 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3295 if (!Conv2) 3296 return ImplicitConversionSequence::Indistinguishable; 3297 3298 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3299 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3300 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3301 if (Block1 != Block2) 3302 return Block1 ? ImplicitConversionSequence::Worse 3303 : ImplicitConversionSequence::Better; 3304 } 3305 3306 return ImplicitConversionSequence::Indistinguishable; 3307 } 3308 3309 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3310 const ImplicitConversionSequence &ICS) { 3311 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3312 (ICS.isUserDefined() && 3313 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3314 } 3315 3316 /// CompareImplicitConversionSequences - Compare two implicit 3317 /// conversion sequences to determine whether one is better than the 3318 /// other or if they are indistinguishable (C++ 13.3.3.2). 3319 static ImplicitConversionSequence::CompareKind 3320 CompareImplicitConversionSequences(Sema &S, 3321 const ImplicitConversionSequence& ICS1, 3322 const ImplicitConversionSequence& ICS2) 3323 { 3324 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3325 // conversion sequences (as defined in 13.3.3.1) 3326 // -- a standard conversion sequence (13.3.3.1.1) is a better 3327 // conversion sequence than a user-defined conversion sequence or 3328 // an ellipsis conversion sequence, and 3329 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3330 // conversion sequence than an ellipsis conversion sequence 3331 // (13.3.3.1.3). 3332 // 3333 // C++0x [over.best.ics]p10: 3334 // For the purpose of ranking implicit conversion sequences as 3335 // described in 13.3.3.2, the ambiguous conversion sequence is 3336 // treated as a user-defined sequence that is indistinguishable 3337 // from any other user-defined conversion sequence. 3338 3339 // String literal to 'char *' conversion has been deprecated in C++03. It has 3340 // been removed from C++11. We still accept this conversion, if it happens at 3341 // the best viable function. Otherwise, this conversion is considered worse 3342 // than ellipsis conversion. Consider this as an extension; this is not in the 3343 // standard. For example: 3344 // 3345 // int &f(...); // #1 3346 // void f(char*); // #2 3347 // void g() { int &r = f("foo"); } 3348 // 3349 // In C++03, we pick #2 as the best viable function. 3350 // In C++11, we pick #1 as the best viable function, because ellipsis 3351 // conversion is better than string-literal to char* conversion (since there 3352 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3353 // convert arguments, #2 would be the best viable function in C++11. 3354 // If the best viable function has this conversion, a warning will be issued 3355 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3356 3357 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3358 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3359 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3360 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3361 ? ImplicitConversionSequence::Worse 3362 : ImplicitConversionSequence::Better; 3363 3364 if (ICS1.getKindRank() < ICS2.getKindRank()) 3365 return ImplicitConversionSequence::Better; 3366 if (ICS2.getKindRank() < ICS1.getKindRank()) 3367 return ImplicitConversionSequence::Worse; 3368 3369 // The following checks require both conversion sequences to be of 3370 // the same kind. 3371 if (ICS1.getKind() != ICS2.getKind()) 3372 return ImplicitConversionSequence::Indistinguishable; 3373 3374 ImplicitConversionSequence::CompareKind Result = 3375 ImplicitConversionSequence::Indistinguishable; 3376 3377 // Two implicit conversion sequences of the same form are 3378 // indistinguishable conversion sequences unless one of the 3379 // following rules apply: (C++ 13.3.3.2p3): 3380 3381 // List-initialization sequence L1 is a better conversion sequence than 3382 // list-initialization sequence L2 if: 3383 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3384 // if not that, 3385 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3386 // and N1 is smaller than N2., 3387 // even if one of the other rules in this paragraph would otherwise apply. 3388 if (!ICS1.isBad()) { 3389 if (ICS1.isStdInitializerListElement() && 3390 !ICS2.isStdInitializerListElement()) 3391 return ImplicitConversionSequence::Better; 3392 if (!ICS1.isStdInitializerListElement() && 3393 ICS2.isStdInitializerListElement()) 3394 return ImplicitConversionSequence::Worse; 3395 } 3396 3397 if (ICS1.isStandard()) 3398 // Standard conversion sequence S1 is a better conversion sequence than 3399 // standard conversion sequence S2 if [...] 3400 Result = CompareStandardConversionSequences(S, 3401 ICS1.Standard, ICS2.Standard); 3402 else if (ICS1.isUserDefined()) { 3403 // User-defined conversion sequence U1 is a better conversion 3404 // sequence than another user-defined conversion sequence U2 if 3405 // they contain the same user-defined conversion function or 3406 // constructor and if the second standard conversion sequence of 3407 // U1 is better than the second standard conversion sequence of 3408 // U2 (C++ 13.3.3.2p3). 3409 if (ICS1.UserDefined.ConversionFunction == 3410 ICS2.UserDefined.ConversionFunction) 3411 Result = CompareStandardConversionSequences(S, 3412 ICS1.UserDefined.After, 3413 ICS2.UserDefined.After); 3414 else 3415 Result = compareConversionFunctions(S, 3416 ICS1.UserDefined.ConversionFunction, 3417 ICS2.UserDefined.ConversionFunction); 3418 } 3419 3420 return Result; 3421 } 3422 3423 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3424 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3425 Qualifiers Quals; 3426 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3427 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3428 } 3429 3430 return Context.hasSameUnqualifiedType(T1, T2); 3431 } 3432 3433 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3434 // determine if one is a proper subset of the other. 3435 static ImplicitConversionSequence::CompareKind 3436 compareStandardConversionSubsets(ASTContext &Context, 3437 const StandardConversionSequence& SCS1, 3438 const StandardConversionSequence& SCS2) { 3439 ImplicitConversionSequence::CompareKind Result 3440 = ImplicitConversionSequence::Indistinguishable; 3441 3442 // the identity conversion sequence is considered to be a subsequence of 3443 // any non-identity conversion sequence 3444 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3445 return ImplicitConversionSequence::Better; 3446 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3447 return ImplicitConversionSequence::Worse; 3448 3449 if (SCS1.Second != SCS2.Second) { 3450 if (SCS1.Second == ICK_Identity) 3451 Result = ImplicitConversionSequence::Better; 3452 else if (SCS2.Second == ICK_Identity) 3453 Result = ImplicitConversionSequence::Worse; 3454 else 3455 return ImplicitConversionSequence::Indistinguishable; 3456 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3457 return ImplicitConversionSequence::Indistinguishable; 3458 3459 if (SCS1.Third == SCS2.Third) { 3460 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3461 : ImplicitConversionSequence::Indistinguishable; 3462 } 3463 3464 if (SCS1.Third == ICK_Identity) 3465 return Result == ImplicitConversionSequence::Worse 3466 ? ImplicitConversionSequence::Indistinguishable 3467 : ImplicitConversionSequence::Better; 3468 3469 if (SCS2.Third == ICK_Identity) 3470 return Result == ImplicitConversionSequence::Better 3471 ? ImplicitConversionSequence::Indistinguishable 3472 : ImplicitConversionSequence::Worse; 3473 3474 return ImplicitConversionSequence::Indistinguishable; 3475 } 3476 3477 /// \brief Determine whether one of the given reference bindings is better 3478 /// than the other based on what kind of bindings they are. 3479 static bool 3480 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3481 const StandardConversionSequence &SCS2) { 3482 // C++0x [over.ics.rank]p3b4: 3483 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3484 // implicit object parameter of a non-static member function declared 3485 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3486 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3487 // lvalue reference to a function lvalue and S2 binds an rvalue 3488 // reference*. 3489 // 3490 // FIXME: Rvalue references. We're going rogue with the above edits, 3491 // because the semantics in the current C++0x working paper (N3225 at the 3492 // time of this writing) break the standard definition of std::forward 3493 // and std::reference_wrapper when dealing with references to functions. 3494 // Proposed wording changes submitted to CWG for consideration. 3495 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3496 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3497 return false; 3498 3499 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3500 SCS2.IsLvalueReference) || 3501 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3502 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3503 } 3504 3505 /// CompareStandardConversionSequences - Compare two standard 3506 /// conversion sequences to determine whether one is better than the 3507 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3508 static ImplicitConversionSequence::CompareKind 3509 CompareStandardConversionSequences(Sema &S, 3510 const StandardConversionSequence& SCS1, 3511 const StandardConversionSequence& SCS2) 3512 { 3513 // Standard conversion sequence S1 is a better conversion sequence 3514 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3515 3516 // -- S1 is a proper subsequence of S2 (comparing the conversion 3517 // sequences in the canonical form defined by 13.3.3.1.1, 3518 // excluding any Lvalue Transformation; the identity conversion 3519 // sequence is considered to be a subsequence of any 3520 // non-identity conversion sequence) or, if not that, 3521 if (ImplicitConversionSequence::CompareKind CK 3522 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3523 return CK; 3524 3525 // -- the rank of S1 is better than the rank of S2 (by the rules 3526 // defined below), or, if not that, 3527 ImplicitConversionRank Rank1 = SCS1.getRank(); 3528 ImplicitConversionRank Rank2 = SCS2.getRank(); 3529 if (Rank1 < Rank2) 3530 return ImplicitConversionSequence::Better; 3531 else if (Rank2 < Rank1) 3532 return ImplicitConversionSequence::Worse; 3533 3534 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3535 // are indistinguishable unless one of the following rules 3536 // applies: 3537 3538 // A conversion that is not a conversion of a pointer, or 3539 // pointer to member, to bool is better than another conversion 3540 // that is such a conversion. 3541 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3542 return SCS2.isPointerConversionToBool() 3543 ? ImplicitConversionSequence::Better 3544 : ImplicitConversionSequence::Worse; 3545 3546 // C++ [over.ics.rank]p4b2: 3547 // 3548 // If class B is derived directly or indirectly from class A, 3549 // conversion of B* to A* is better than conversion of B* to 3550 // void*, and conversion of A* to void* is better than conversion 3551 // of B* to void*. 3552 bool SCS1ConvertsToVoid 3553 = SCS1.isPointerConversionToVoidPointer(S.Context); 3554 bool SCS2ConvertsToVoid 3555 = SCS2.isPointerConversionToVoidPointer(S.Context); 3556 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3557 // Exactly one of the conversion sequences is a conversion to 3558 // a void pointer; it's the worse conversion. 3559 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3560 : ImplicitConversionSequence::Worse; 3561 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3562 // Neither conversion sequence converts to a void pointer; compare 3563 // their derived-to-base conversions. 3564 if (ImplicitConversionSequence::CompareKind DerivedCK 3565 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3566 return DerivedCK; 3567 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3568 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3569 // Both conversion sequences are conversions to void 3570 // pointers. Compare the source types to determine if there's an 3571 // inheritance relationship in their sources. 3572 QualType FromType1 = SCS1.getFromType(); 3573 QualType FromType2 = SCS2.getFromType(); 3574 3575 // Adjust the types we're converting from via the array-to-pointer 3576 // conversion, if we need to. 3577 if (SCS1.First == ICK_Array_To_Pointer) 3578 FromType1 = S.Context.getArrayDecayedType(FromType1); 3579 if (SCS2.First == ICK_Array_To_Pointer) 3580 FromType2 = S.Context.getArrayDecayedType(FromType2); 3581 3582 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3583 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3584 3585 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3586 return ImplicitConversionSequence::Better; 3587 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3588 return ImplicitConversionSequence::Worse; 3589 3590 // Objective-C++: If one interface is more specific than the 3591 // other, it is the better one. 3592 const ObjCObjectPointerType* FromObjCPtr1 3593 = FromType1->getAs<ObjCObjectPointerType>(); 3594 const ObjCObjectPointerType* FromObjCPtr2 3595 = FromType2->getAs<ObjCObjectPointerType>(); 3596 if (FromObjCPtr1 && FromObjCPtr2) { 3597 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3598 FromObjCPtr2); 3599 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3600 FromObjCPtr1); 3601 if (AssignLeft != AssignRight) { 3602 return AssignLeft? ImplicitConversionSequence::Better 3603 : ImplicitConversionSequence::Worse; 3604 } 3605 } 3606 } 3607 3608 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3609 // bullet 3). 3610 if (ImplicitConversionSequence::CompareKind QualCK 3611 = CompareQualificationConversions(S, SCS1, SCS2)) 3612 return QualCK; 3613 3614 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3615 // Check for a better reference binding based on the kind of bindings. 3616 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3617 return ImplicitConversionSequence::Better; 3618 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3619 return ImplicitConversionSequence::Worse; 3620 3621 // C++ [over.ics.rank]p3b4: 3622 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3623 // which the references refer are the same type except for 3624 // top-level cv-qualifiers, and the type to which the reference 3625 // initialized by S2 refers is more cv-qualified than the type 3626 // to which the reference initialized by S1 refers. 3627 QualType T1 = SCS1.getToType(2); 3628 QualType T2 = SCS2.getToType(2); 3629 T1 = S.Context.getCanonicalType(T1); 3630 T2 = S.Context.getCanonicalType(T2); 3631 Qualifiers T1Quals, T2Quals; 3632 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3633 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3634 if (UnqualT1 == UnqualT2) { 3635 // Objective-C++ ARC: If the references refer to objects with different 3636 // lifetimes, prefer bindings that don't change lifetime. 3637 if (SCS1.ObjCLifetimeConversionBinding != 3638 SCS2.ObjCLifetimeConversionBinding) { 3639 return SCS1.ObjCLifetimeConversionBinding 3640 ? ImplicitConversionSequence::Worse 3641 : ImplicitConversionSequence::Better; 3642 } 3643 3644 // If the type is an array type, promote the element qualifiers to the 3645 // type for comparison. 3646 if (isa<ArrayType>(T1) && T1Quals) 3647 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3648 if (isa<ArrayType>(T2) && T2Quals) 3649 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3650 if (T2.isMoreQualifiedThan(T1)) 3651 return ImplicitConversionSequence::Better; 3652 else if (T1.isMoreQualifiedThan(T2)) 3653 return ImplicitConversionSequence::Worse; 3654 } 3655 } 3656 3657 // In Microsoft mode, prefer an integral conversion to a 3658 // floating-to-integral conversion if the integral conversion 3659 // is between types of the same size. 3660 // For example: 3661 // void f(float); 3662 // void f(int); 3663 // int main { 3664 // long a; 3665 // f(a); 3666 // } 3667 // Here, MSVC will call f(int) instead of generating a compile error 3668 // as clang will do in standard mode. 3669 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3670 SCS2.Second == ICK_Floating_Integral && 3671 S.Context.getTypeSize(SCS1.getFromType()) == 3672 S.Context.getTypeSize(SCS1.getToType(2))) 3673 return ImplicitConversionSequence::Better; 3674 3675 return ImplicitConversionSequence::Indistinguishable; 3676 } 3677 3678 /// CompareQualificationConversions - Compares two standard conversion 3679 /// sequences to determine whether they can be ranked based on their 3680 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3681 static ImplicitConversionSequence::CompareKind 3682 CompareQualificationConversions(Sema &S, 3683 const StandardConversionSequence& SCS1, 3684 const StandardConversionSequence& SCS2) { 3685 // C++ 13.3.3.2p3: 3686 // -- S1 and S2 differ only in their qualification conversion and 3687 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3688 // cv-qualification signature of type T1 is a proper subset of 3689 // the cv-qualification signature of type T2, and S1 is not the 3690 // deprecated string literal array-to-pointer conversion (4.2). 3691 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3692 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3693 return ImplicitConversionSequence::Indistinguishable; 3694 3695 // FIXME: the example in the standard doesn't use a qualification 3696 // conversion (!) 3697 QualType T1 = SCS1.getToType(2); 3698 QualType T2 = SCS2.getToType(2); 3699 T1 = S.Context.getCanonicalType(T1); 3700 T2 = S.Context.getCanonicalType(T2); 3701 Qualifiers T1Quals, T2Quals; 3702 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3703 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3704 3705 // If the types are the same, we won't learn anything by unwrapped 3706 // them. 3707 if (UnqualT1 == UnqualT2) 3708 return ImplicitConversionSequence::Indistinguishable; 3709 3710 // If the type is an array type, promote the element qualifiers to the type 3711 // for comparison. 3712 if (isa<ArrayType>(T1) && T1Quals) 3713 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3714 if (isa<ArrayType>(T2) && T2Quals) 3715 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3716 3717 ImplicitConversionSequence::CompareKind Result 3718 = ImplicitConversionSequence::Indistinguishable; 3719 3720 // Objective-C++ ARC: 3721 // Prefer qualification conversions not involving a change in lifetime 3722 // to qualification conversions that do not change lifetime. 3723 if (SCS1.QualificationIncludesObjCLifetime != 3724 SCS2.QualificationIncludesObjCLifetime) { 3725 Result = SCS1.QualificationIncludesObjCLifetime 3726 ? ImplicitConversionSequence::Worse 3727 : ImplicitConversionSequence::Better; 3728 } 3729 3730 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3731 // Within each iteration of the loop, we check the qualifiers to 3732 // determine if this still looks like a qualification 3733 // conversion. Then, if all is well, we unwrap one more level of 3734 // pointers or pointers-to-members and do it all again 3735 // until there are no more pointers or pointers-to-members left 3736 // to unwrap. This essentially mimics what 3737 // IsQualificationConversion does, but here we're checking for a 3738 // strict subset of qualifiers. 3739 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3740 // The qualifiers are the same, so this doesn't tell us anything 3741 // about how the sequences rank. 3742 ; 3743 else if (T2.isMoreQualifiedThan(T1)) { 3744 // T1 has fewer qualifiers, so it could be the better sequence. 3745 if (Result == ImplicitConversionSequence::Worse) 3746 // Neither has qualifiers that are a subset of the other's 3747 // qualifiers. 3748 return ImplicitConversionSequence::Indistinguishable; 3749 3750 Result = ImplicitConversionSequence::Better; 3751 } else if (T1.isMoreQualifiedThan(T2)) { 3752 // T2 has fewer qualifiers, so it could be the better sequence. 3753 if (Result == ImplicitConversionSequence::Better) 3754 // Neither has qualifiers that are a subset of the other's 3755 // qualifiers. 3756 return ImplicitConversionSequence::Indistinguishable; 3757 3758 Result = ImplicitConversionSequence::Worse; 3759 } else { 3760 // Qualifiers are disjoint. 3761 return ImplicitConversionSequence::Indistinguishable; 3762 } 3763 3764 // If the types after this point are equivalent, we're done. 3765 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3766 break; 3767 } 3768 3769 // Check that the winning standard conversion sequence isn't using 3770 // the deprecated string literal array to pointer conversion. 3771 switch (Result) { 3772 case ImplicitConversionSequence::Better: 3773 if (SCS1.DeprecatedStringLiteralToCharPtr) 3774 Result = ImplicitConversionSequence::Indistinguishable; 3775 break; 3776 3777 case ImplicitConversionSequence::Indistinguishable: 3778 break; 3779 3780 case ImplicitConversionSequence::Worse: 3781 if (SCS2.DeprecatedStringLiteralToCharPtr) 3782 Result = ImplicitConversionSequence::Indistinguishable; 3783 break; 3784 } 3785 3786 return Result; 3787 } 3788 3789 /// CompareDerivedToBaseConversions - Compares two standard conversion 3790 /// sequences to determine whether they can be ranked based on their 3791 /// various kinds of derived-to-base conversions (C++ 3792 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3793 /// conversions between Objective-C interface types. 3794 static ImplicitConversionSequence::CompareKind 3795 CompareDerivedToBaseConversions(Sema &S, 3796 const StandardConversionSequence& SCS1, 3797 const StandardConversionSequence& SCS2) { 3798 QualType FromType1 = SCS1.getFromType(); 3799 QualType ToType1 = SCS1.getToType(1); 3800 QualType FromType2 = SCS2.getFromType(); 3801 QualType ToType2 = SCS2.getToType(1); 3802 3803 // Adjust the types we're converting from via the array-to-pointer 3804 // conversion, if we need to. 3805 if (SCS1.First == ICK_Array_To_Pointer) 3806 FromType1 = S.Context.getArrayDecayedType(FromType1); 3807 if (SCS2.First == ICK_Array_To_Pointer) 3808 FromType2 = S.Context.getArrayDecayedType(FromType2); 3809 3810 // Canonicalize all of the types. 3811 FromType1 = S.Context.getCanonicalType(FromType1); 3812 ToType1 = S.Context.getCanonicalType(ToType1); 3813 FromType2 = S.Context.getCanonicalType(FromType2); 3814 ToType2 = S.Context.getCanonicalType(ToType2); 3815 3816 // C++ [over.ics.rank]p4b3: 3817 // 3818 // If class B is derived directly or indirectly from class A and 3819 // class C is derived directly or indirectly from B, 3820 // 3821 // Compare based on pointer conversions. 3822 if (SCS1.Second == ICK_Pointer_Conversion && 3823 SCS2.Second == ICK_Pointer_Conversion && 3824 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3825 FromType1->isPointerType() && FromType2->isPointerType() && 3826 ToType1->isPointerType() && ToType2->isPointerType()) { 3827 QualType FromPointee1 3828 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3829 QualType ToPointee1 3830 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3831 QualType FromPointee2 3832 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3833 QualType ToPointee2 3834 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3835 3836 // -- conversion of C* to B* is better than conversion of C* to A*, 3837 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3838 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3839 return ImplicitConversionSequence::Better; 3840 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3841 return ImplicitConversionSequence::Worse; 3842 } 3843 3844 // -- conversion of B* to A* is better than conversion of C* to A*, 3845 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3846 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3847 return ImplicitConversionSequence::Better; 3848 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3849 return ImplicitConversionSequence::Worse; 3850 } 3851 } else if (SCS1.Second == ICK_Pointer_Conversion && 3852 SCS2.Second == ICK_Pointer_Conversion) { 3853 const ObjCObjectPointerType *FromPtr1 3854 = FromType1->getAs<ObjCObjectPointerType>(); 3855 const ObjCObjectPointerType *FromPtr2 3856 = FromType2->getAs<ObjCObjectPointerType>(); 3857 const ObjCObjectPointerType *ToPtr1 3858 = ToType1->getAs<ObjCObjectPointerType>(); 3859 const ObjCObjectPointerType *ToPtr2 3860 = ToType2->getAs<ObjCObjectPointerType>(); 3861 3862 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3863 // Apply the same conversion ranking rules for Objective-C pointer types 3864 // that we do for C++ pointers to class types. However, we employ the 3865 // Objective-C pseudo-subtyping relationship used for assignment of 3866 // Objective-C pointer types. 3867 bool FromAssignLeft 3868 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3869 bool FromAssignRight 3870 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3871 bool ToAssignLeft 3872 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3873 bool ToAssignRight 3874 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3875 3876 // A conversion to an a non-id object pointer type or qualified 'id' 3877 // type is better than a conversion to 'id'. 3878 if (ToPtr1->isObjCIdType() && 3879 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3880 return ImplicitConversionSequence::Worse; 3881 if (ToPtr2->isObjCIdType() && 3882 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3883 return ImplicitConversionSequence::Better; 3884 3885 // A conversion to a non-id object pointer type is better than a 3886 // conversion to a qualified 'id' type 3887 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3888 return ImplicitConversionSequence::Worse; 3889 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3890 return ImplicitConversionSequence::Better; 3891 3892 // A conversion to an a non-Class object pointer type or qualified 'Class' 3893 // type is better than a conversion to 'Class'. 3894 if (ToPtr1->isObjCClassType() && 3895 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3896 return ImplicitConversionSequence::Worse; 3897 if (ToPtr2->isObjCClassType() && 3898 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3899 return ImplicitConversionSequence::Better; 3900 3901 // A conversion to a non-Class object pointer type is better than a 3902 // conversion to a qualified 'Class' type. 3903 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3904 return ImplicitConversionSequence::Worse; 3905 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3906 return ImplicitConversionSequence::Better; 3907 3908 // -- "conversion of C* to B* is better than conversion of C* to A*," 3909 if (S.Context.hasSameType(FromType1, FromType2) && 3910 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3911 (ToAssignLeft != ToAssignRight)) 3912 return ToAssignLeft? ImplicitConversionSequence::Worse 3913 : ImplicitConversionSequence::Better; 3914 3915 // -- "conversion of B* to A* is better than conversion of C* to A*," 3916 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3917 (FromAssignLeft != FromAssignRight)) 3918 return FromAssignLeft? ImplicitConversionSequence::Better 3919 : ImplicitConversionSequence::Worse; 3920 } 3921 } 3922 3923 // Ranking of member-pointer types. 3924 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3925 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3926 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3927 const MemberPointerType * FromMemPointer1 = 3928 FromType1->getAs<MemberPointerType>(); 3929 const MemberPointerType * ToMemPointer1 = 3930 ToType1->getAs<MemberPointerType>(); 3931 const MemberPointerType * FromMemPointer2 = 3932 FromType2->getAs<MemberPointerType>(); 3933 const MemberPointerType * ToMemPointer2 = 3934 ToType2->getAs<MemberPointerType>(); 3935 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3936 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3937 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3938 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3939 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3940 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3941 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3942 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3943 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3944 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3945 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3946 return ImplicitConversionSequence::Worse; 3947 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3948 return ImplicitConversionSequence::Better; 3949 } 3950 // conversion of B::* to C::* is better than conversion of A::* to C::* 3951 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3952 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3953 return ImplicitConversionSequence::Better; 3954 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3955 return ImplicitConversionSequence::Worse; 3956 } 3957 } 3958 3959 if (SCS1.Second == ICK_Derived_To_Base) { 3960 // -- conversion of C to B is better than conversion of C to A, 3961 // -- binding of an expression of type C to a reference of type 3962 // B& is better than binding an expression of type C to a 3963 // reference of type A&, 3964 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3965 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3966 if (S.IsDerivedFrom(ToType1, ToType2)) 3967 return ImplicitConversionSequence::Better; 3968 else if (S.IsDerivedFrom(ToType2, ToType1)) 3969 return ImplicitConversionSequence::Worse; 3970 } 3971 3972 // -- conversion of B to A is better than conversion of C to A. 3973 // -- binding of an expression of type B to a reference of type 3974 // A& is better than binding an expression of type C to a 3975 // reference of type A&, 3976 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3977 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3978 if (S.IsDerivedFrom(FromType2, FromType1)) 3979 return ImplicitConversionSequence::Better; 3980 else if (S.IsDerivedFrom(FromType1, FromType2)) 3981 return ImplicitConversionSequence::Worse; 3982 } 3983 } 3984 3985 return ImplicitConversionSequence::Indistinguishable; 3986 } 3987 3988 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3989 /// C++ class. 3990 static bool isTypeValid(QualType T) { 3991 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3992 return !Record->isInvalidDecl(); 3993 3994 return true; 3995 } 3996 3997 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3998 /// determine whether they are reference-related, 3999 /// reference-compatible, reference-compatible with added 4000 /// qualification, or incompatible, for use in C++ initialization by 4001 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4002 /// type, and the first type (T1) is the pointee type of the reference 4003 /// type being initialized. 4004 Sema::ReferenceCompareResult 4005 Sema::CompareReferenceRelationship(SourceLocation Loc, 4006 QualType OrigT1, QualType OrigT2, 4007 bool &DerivedToBase, 4008 bool &ObjCConversion, 4009 bool &ObjCLifetimeConversion) { 4010 assert(!OrigT1->isReferenceType() && 4011 "T1 must be the pointee type of the reference type"); 4012 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4013 4014 QualType T1 = Context.getCanonicalType(OrigT1); 4015 QualType T2 = Context.getCanonicalType(OrigT2); 4016 Qualifiers T1Quals, T2Quals; 4017 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4018 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4019 4020 // C++ [dcl.init.ref]p4: 4021 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4022 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4023 // T1 is a base class of T2. 4024 DerivedToBase = false; 4025 ObjCConversion = false; 4026 ObjCLifetimeConversion = false; 4027 if (UnqualT1 == UnqualT2) { 4028 // Nothing to do. 4029 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4030 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4031 IsDerivedFrom(UnqualT2, UnqualT1)) 4032 DerivedToBase = true; 4033 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4034 UnqualT2->isObjCObjectOrInterfaceType() && 4035 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4036 ObjCConversion = true; 4037 else 4038 return Ref_Incompatible; 4039 4040 // At this point, we know that T1 and T2 are reference-related (at 4041 // least). 4042 4043 // If the type is an array type, promote the element qualifiers to the type 4044 // for comparison. 4045 if (isa<ArrayType>(T1) && T1Quals) 4046 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4047 if (isa<ArrayType>(T2) && T2Quals) 4048 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4049 4050 // C++ [dcl.init.ref]p4: 4051 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4052 // reference-related to T2 and cv1 is the same cv-qualification 4053 // as, or greater cv-qualification than, cv2. For purposes of 4054 // overload resolution, cases for which cv1 is greater 4055 // cv-qualification than cv2 are identified as 4056 // reference-compatible with added qualification (see 13.3.3.2). 4057 // 4058 // Note that we also require equivalence of Objective-C GC and address-space 4059 // qualifiers when performing these computations, so that e.g., an int in 4060 // address space 1 is not reference-compatible with an int in address 4061 // space 2. 4062 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4063 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4064 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4065 ObjCLifetimeConversion = true; 4066 4067 T1Quals.removeObjCLifetime(); 4068 T2Quals.removeObjCLifetime(); 4069 } 4070 4071 if (T1Quals == T2Quals) 4072 return Ref_Compatible; 4073 else if (T1Quals.compatiblyIncludes(T2Quals)) 4074 return Ref_Compatible_With_Added_Qualification; 4075 else 4076 return Ref_Related; 4077 } 4078 4079 /// \brief Look for a user-defined conversion to an value reference-compatible 4080 /// with DeclType. Return true if something definite is found. 4081 static bool 4082 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4083 QualType DeclType, SourceLocation DeclLoc, 4084 Expr *Init, QualType T2, bool AllowRvalues, 4085 bool AllowExplicit) { 4086 assert(T2->isRecordType() && "Can only find conversions of record types."); 4087 CXXRecordDecl *T2RecordDecl 4088 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4089 4090 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4091 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4092 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4093 NamedDecl *D = *I; 4094 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4095 if (isa<UsingShadowDecl>(D)) 4096 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4097 4098 FunctionTemplateDecl *ConvTemplate 4099 = dyn_cast<FunctionTemplateDecl>(D); 4100 CXXConversionDecl *Conv; 4101 if (ConvTemplate) 4102 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4103 else 4104 Conv = cast<CXXConversionDecl>(D); 4105 4106 // If this is an explicit conversion, and we're not allowed to consider 4107 // explicit conversions, skip it. 4108 if (!AllowExplicit && Conv->isExplicit()) 4109 continue; 4110 4111 if (AllowRvalues) { 4112 bool DerivedToBase = false; 4113 bool ObjCConversion = false; 4114 bool ObjCLifetimeConversion = false; 4115 4116 // If we are initializing an rvalue reference, don't permit conversion 4117 // functions that return lvalues. 4118 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4119 const ReferenceType *RefType 4120 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4121 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4122 continue; 4123 } 4124 4125 if (!ConvTemplate && 4126 S.CompareReferenceRelationship( 4127 DeclLoc, 4128 Conv->getConversionType().getNonReferenceType() 4129 .getUnqualifiedType(), 4130 DeclType.getNonReferenceType().getUnqualifiedType(), 4131 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4132 Sema::Ref_Incompatible) 4133 continue; 4134 } else { 4135 // If the conversion function doesn't return a reference type, 4136 // it can't be considered for this conversion. An rvalue reference 4137 // is only acceptable if its referencee is a function type. 4138 4139 const ReferenceType *RefType = 4140 Conv->getConversionType()->getAs<ReferenceType>(); 4141 if (!RefType || 4142 (!RefType->isLValueReferenceType() && 4143 !RefType->getPointeeType()->isFunctionType())) 4144 continue; 4145 } 4146 4147 if (ConvTemplate) 4148 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4149 Init, DeclType, CandidateSet, 4150 /*AllowObjCConversionOnExplicit=*/false); 4151 else 4152 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4153 DeclType, CandidateSet, 4154 /*AllowObjCConversionOnExplicit=*/false); 4155 } 4156 4157 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4158 4159 OverloadCandidateSet::iterator Best; 4160 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4161 case OR_Success: 4162 // C++ [over.ics.ref]p1: 4163 // 4164 // [...] If the parameter binds directly to the result of 4165 // applying a conversion function to the argument 4166 // expression, the implicit conversion sequence is a 4167 // user-defined conversion sequence (13.3.3.1.2), with the 4168 // second standard conversion sequence either an identity 4169 // conversion or, if the conversion function returns an 4170 // entity of a type that is a derived class of the parameter 4171 // type, a derived-to-base Conversion. 4172 if (!Best->FinalConversion.DirectBinding) 4173 return false; 4174 4175 ICS.setUserDefined(); 4176 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4177 ICS.UserDefined.After = Best->FinalConversion; 4178 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4179 ICS.UserDefined.ConversionFunction = Best->Function; 4180 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4181 ICS.UserDefined.EllipsisConversion = false; 4182 assert(ICS.UserDefined.After.ReferenceBinding && 4183 ICS.UserDefined.After.DirectBinding && 4184 "Expected a direct reference binding!"); 4185 return true; 4186 4187 case OR_Ambiguous: 4188 ICS.setAmbiguous(); 4189 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4190 Cand != CandidateSet.end(); ++Cand) 4191 if (Cand->Viable) 4192 ICS.Ambiguous.addConversion(Cand->Function); 4193 return true; 4194 4195 case OR_No_Viable_Function: 4196 case OR_Deleted: 4197 // There was no suitable conversion, or we found a deleted 4198 // conversion; continue with other checks. 4199 return false; 4200 } 4201 4202 llvm_unreachable("Invalid OverloadResult!"); 4203 } 4204 4205 /// \brief Compute an implicit conversion sequence for reference 4206 /// initialization. 4207 static ImplicitConversionSequence 4208 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4209 SourceLocation DeclLoc, 4210 bool SuppressUserConversions, 4211 bool AllowExplicit) { 4212 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4213 4214 // Most paths end in a failed conversion. 4215 ImplicitConversionSequence ICS; 4216 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4217 4218 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4219 QualType T2 = Init->getType(); 4220 4221 // If the initializer is the address of an overloaded function, try 4222 // to resolve the overloaded function. If all goes well, T2 is the 4223 // type of the resulting function. 4224 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4225 DeclAccessPair Found; 4226 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4227 false, Found)) 4228 T2 = Fn->getType(); 4229 } 4230 4231 // Compute some basic properties of the types and the initializer. 4232 bool isRValRef = DeclType->isRValueReferenceType(); 4233 bool DerivedToBase = false; 4234 bool ObjCConversion = false; 4235 bool ObjCLifetimeConversion = false; 4236 Expr::Classification InitCategory = Init->Classify(S.Context); 4237 Sema::ReferenceCompareResult RefRelationship 4238 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4239 ObjCConversion, ObjCLifetimeConversion); 4240 4241 4242 // C++0x [dcl.init.ref]p5: 4243 // A reference to type "cv1 T1" is initialized by an expression 4244 // of type "cv2 T2" as follows: 4245 4246 // -- If reference is an lvalue reference and the initializer expression 4247 if (!isRValRef) { 4248 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4249 // reference-compatible with "cv2 T2," or 4250 // 4251 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4252 if (InitCategory.isLValue() && 4253 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4254 // C++ [over.ics.ref]p1: 4255 // When a parameter of reference type binds directly (8.5.3) 4256 // to an argument expression, the implicit conversion sequence 4257 // is the identity conversion, unless the argument expression 4258 // has a type that is a derived class of the parameter type, 4259 // in which case the implicit conversion sequence is a 4260 // derived-to-base Conversion (13.3.3.1). 4261 ICS.setStandard(); 4262 ICS.Standard.First = ICK_Identity; 4263 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4264 : ObjCConversion? ICK_Compatible_Conversion 4265 : ICK_Identity; 4266 ICS.Standard.Third = ICK_Identity; 4267 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4268 ICS.Standard.setToType(0, T2); 4269 ICS.Standard.setToType(1, T1); 4270 ICS.Standard.setToType(2, T1); 4271 ICS.Standard.ReferenceBinding = true; 4272 ICS.Standard.DirectBinding = true; 4273 ICS.Standard.IsLvalueReference = !isRValRef; 4274 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4275 ICS.Standard.BindsToRvalue = false; 4276 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4277 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4278 ICS.Standard.CopyConstructor = nullptr; 4279 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4280 4281 // Nothing more to do: the inaccessibility/ambiguity check for 4282 // derived-to-base conversions is suppressed when we're 4283 // computing the implicit conversion sequence (C++ 4284 // [over.best.ics]p2). 4285 return ICS; 4286 } 4287 4288 // -- has a class type (i.e., T2 is a class type), where T1 is 4289 // not reference-related to T2, and can be implicitly 4290 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4291 // is reference-compatible with "cv3 T3" 92) (this 4292 // conversion is selected by enumerating the applicable 4293 // conversion functions (13.3.1.6) and choosing the best 4294 // one through overload resolution (13.3)), 4295 if (!SuppressUserConversions && T2->isRecordType() && 4296 !S.RequireCompleteType(DeclLoc, T2, 0) && 4297 RefRelationship == Sema::Ref_Incompatible) { 4298 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4299 Init, T2, /*AllowRvalues=*/false, 4300 AllowExplicit)) 4301 return ICS; 4302 } 4303 } 4304 4305 // -- Otherwise, the reference shall be an lvalue reference to a 4306 // non-volatile const type (i.e., cv1 shall be const), or the reference 4307 // shall be an rvalue reference. 4308 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4309 return ICS; 4310 4311 // -- If the initializer expression 4312 // 4313 // -- is an xvalue, class prvalue, array prvalue or function 4314 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4315 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4316 (InitCategory.isXValue() || 4317 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4318 (InitCategory.isLValue() && T2->isFunctionType()))) { 4319 ICS.setStandard(); 4320 ICS.Standard.First = ICK_Identity; 4321 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4322 : ObjCConversion? ICK_Compatible_Conversion 4323 : ICK_Identity; 4324 ICS.Standard.Third = ICK_Identity; 4325 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4326 ICS.Standard.setToType(0, T2); 4327 ICS.Standard.setToType(1, T1); 4328 ICS.Standard.setToType(2, T1); 4329 ICS.Standard.ReferenceBinding = true; 4330 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4331 // binding unless we're binding to a class prvalue. 4332 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4333 // allow the use of rvalue references in C++98/03 for the benefit of 4334 // standard library implementors; therefore, we need the xvalue check here. 4335 ICS.Standard.DirectBinding = 4336 S.getLangOpts().CPlusPlus11 || 4337 !(InitCategory.isPRValue() || T2->isRecordType()); 4338 ICS.Standard.IsLvalueReference = !isRValRef; 4339 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4340 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4341 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4342 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4343 ICS.Standard.CopyConstructor = nullptr; 4344 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4345 return ICS; 4346 } 4347 4348 // -- has a class type (i.e., T2 is a class type), where T1 is not 4349 // reference-related to T2, and can be implicitly converted to 4350 // an xvalue, class prvalue, or function lvalue of type 4351 // "cv3 T3", where "cv1 T1" is reference-compatible with 4352 // "cv3 T3", 4353 // 4354 // then the reference is bound to the value of the initializer 4355 // expression in the first case and to the result of the conversion 4356 // in the second case (or, in either case, to an appropriate base 4357 // class subobject). 4358 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4359 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4360 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4361 Init, T2, /*AllowRvalues=*/true, 4362 AllowExplicit)) { 4363 // In the second case, if the reference is an rvalue reference 4364 // and the second standard conversion sequence of the 4365 // user-defined conversion sequence includes an lvalue-to-rvalue 4366 // conversion, the program is ill-formed. 4367 if (ICS.isUserDefined() && isRValRef && 4368 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4369 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4370 4371 return ICS; 4372 } 4373 4374 // A temporary of function type cannot be created; don't even try. 4375 if (T1->isFunctionType()) 4376 return ICS; 4377 4378 // -- Otherwise, a temporary of type "cv1 T1" is created and 4379 // initialized from the initializer expression using the 4380 // rules for a non-reference copy initialization (8.5). The 4381 // reference is then bound to the temporary. If T1 is 4382 // reference-related to T2, cv1 must be the same 4383 // cv-qualification as, or greater cv-qualification than, 4384 // cv2; otherwise, the program is ill-formed. 4385 if (RefRelationship == Sema::Ref_Related) { 4386 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4387 // we would be reference-compatible or reference-compatible with 4388 // added qualification. But that wasn't the case, so the reference 4389 // initialization fails. 4390 // 4391 // Note that we only want to check address spaces and cvr-qualifiers here. 4392 // ObjC GC and lifetime qualifiers aren't important. 4393 Qualifiers T1Quals = T1.getQualifiers(); 4394 Qualifiers T2Quals = T2.getQualifiers(); 4395 T1Quals.removeObjCGCAttr(); 4396 T1Quals.removeObjCLifetime(); 4397 T2Quals.removeObjCGCAttr(); 4398 T2Quals.removeObjCLifetime(); 4399 if (!T1Quals.compatiblyIncludes(T2Quals)) 4400 return ICS; 4401 } 4402 4403 // If at least one of the types is a class type, the types are not 4404 // related, and we aren't allowed any user conversions, the 4405 // reference binding fails. This case is important for breaking 4406 // recursion, since TryImplicitConversion below will attempt to 4407 // create a temporary through the use of a copy constructor. 4408 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4409 (T1->isRecordType() || T2->isRecordType())) 4410 return ICS; 4411 4412 // If T1 is reference-related to T2 and the reference is an rvalue 4413 // reference, the initializer expression shall not be an lvalue. 4414 if (RefRelationship >= Sema::Ref_Related && 4415 isRValRef && Init->Classify(S.Context).isLValue()) 4416 return ICS; 4417 4418 // C++ [over.ics.ref]p2: 4419 // When a parameter of reference type is not bound directly to 4420 // an argument expression, the conversion sequence is the one 4421 // required to convert the argument expression to the 4422 // underlying type of the reference according to 4423 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4424 // to copy-initializing a temporary of the underlying type with 4425 // the argument expression. Any difference in top-level 4426 // cv-qualification is subsumed by the initialization itself 4427 // and does not constitute a conversion. 4428 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4429 /*AllowExplicit=*/false, 4430 /*InOverloadResolution=*/false, 4431 /*CStyle=*/false, 4432 /*AllowObjCWritebackConversion=*/false, 4433 /*AllowObjCConversionOnExplicit=*/false); 4434 4435 // Of course, that's still a reference binding. 4436 if (ICS.isStandard()) { 4437 ICS.Standard.ReferenceBinding = true; 4438 ICS.Standard.IsLvalueReference = !isRValRef; 4439 ICS.Standard.BindsToFunctionLvalue = false; 4440 ICS.Standard.BindsToRvalue = true; 4441 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4442 ICS.Standard.ObjCLifetimeConversionBinding = false; 4443 } else if (ICS.isUserDefined()) { 4444 const ReferenceType *LValRefType = 4445 ICS.UserDefined.ConversionFunction->getReturnType() 4446 ->getAs<LValueReferenceType>(); 4447 4448 // C++ [over.ics.ref]p3: 4449 // Except for an implicit object parameter, for which see 13.3.1, a 4450 // standard conversion sequence cannot be formed if it requires [...] 4451 // binding an rvalue reference to an lvalue other than a function 4452 // lvalue. 4453 // Note that the function case is not possible here. 4454 if (DeclType->isRValueReferenceType() && LValRefType) { 4455 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4456 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4457 // reference to an rvalue! 4458 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4459 return ICS; 4460 } 4461 4462 ICS.UserDefined.Before.setAsIdentityConversion(); 4463 ICS.UserDefined.After.ReferenceBinding = true; 4464 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4465 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4466 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4467 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4468 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4469 } 4470 4471 return ICS; 4472 } 4473 4474 static ImplicitConversionSequence 4475 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4476 bool SuppressUserConversions, 4477 bool InOverloadResolution, 4478 bool AllowObjCWritebackConversion, 4479 bool AllowExplicit = false); 4480 4481 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4482 /// initializer list From. 4483 static ImplicitConversionSequence 4484 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4485 bool SuppressUserConversions, 4486 bool InOverloadResolution, 4487 bool AllowObjCWritebackConversion) { 4488 // C++11 [over.ics.list]p1: 4489 // When an argument is an initializer list, it is not an expression and 4490 // special rules apply for converting it to a parameter type. 4491 4492 ImplicitConversionSequence Result; 4493 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4494 4495 // We need a complete type for what follows. Incomplete types can never be 4496 // initialized from init lists. 4497 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4498 return Result; 4499 4500 // Per DR1467: 4501 // If the parameter type is a class X and the initializer list has a single 4502 // element of type cv U, where U is X or a class derived from X, the 4503 // implicit conversion sequence is the one required to convert the element 4504 // to the parameter type. 4505 // 4506 // Otherwise, if the parameter type is a character array [... ] 4507 // and the initializer list has a single element that is an 4508 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4509 // implicit conversion sequence is the identity conversion. 4510 if (From->getNumInits() == 1) { 4511 if (ToType->isRecordType()) { 4512 QualType InitType = From->getInit(0)->getType(); 4513 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4514 S.IsDerivedFrom(InitType, ToType)) 4515 return TryCopyInitialization(S, From->getInit(0), ToType, 4516 SuppressUserConversions, 4517 InOverloadResolution, 4518 AllowObjCWritebackConversion); 4519 } 4520 // FIXME: Check the other conditions here: array of character type, 4521 // initializer is a string literal. 4522 if (ToType->isArrayType()) { 4523 InitializedEntity Entity = 4524 InitializedEntity::InitializeParameter(S.Context, ToType, 4525 /*Consumed=*/false); 4526 if (S.CanPerformCopyInitialization(Entity, From)) { 4527 Result.setStandard(); 4528 Result.Standard.setAsIdentityConversion(); 4529 Result.Standard.setFromType(ToType); 4530 Result.Standard.setAllToTypes(ToType); 4531 return Result; 4532 } 4533 } 4534 } 4535 4536 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4537 // C++11 [over.ics.list]p2: 4538 // If the parameter type is std::initializer_list<X> or "array of X" and 4539 // all the elements can be implicitly converted to X, the implicit 4540 // conversion sequence is the worst conversion necessary to convert an 4541 // element of the list to X. 4542 // 4543 // C++14 [over.ics.list]p3: 4544 // Otherwise, if the parameter type is "array of N X", if the initializer 4545 // list has exactly N elements or if it has fewer than N elements and X is 4546 // default-constructible, and if all the elements of the initializer list 4547 // can be implicitly converted to X, the implicit conversion sequence is 4548 // the worst conversion necessary to convert an element of the list to X. 4549 // 4550 // FIXME: We're missing a lot of these checks. 4551 bool toStdInitializerList = false; 4552 QualType X; 4553 if (ToType->isArrayType()) 4554 X = S.Context.getAsArrayType(ToType)->getElementType(); 4555 else 4556 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4557 if (!X.isNull()) { 4558 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4559 Expr *Init = From->getInit(i); 4560 ImplicitConversionSequence ICS = 4561 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4562 InOverloadResolution, 4563 AllowObjCWritebackConversion); 4564 // If a single element isn't convertible, fail. 4565 if (ICS.isBad()) { 4566 Result = ICS; 4567 break; 4568 } 4569 // Otherwise, look for the worst conversion. 4570 if (Result.isBad() || 4571 CompareImplicitConversionSequences(S, ICS, Result) == 4572 ImplicitConversionSequence::Worse) 4573 Result = ICS; 4574 } 4575 4576 // For an empty list, we won't have computed any conversion sequence. 4577 // Introduce the identity conversion sequence. 4578 if (From->getNumInits() == 0) { 4579 Result.setStandard(); 4580 Result.Standard.setAsIdentityConversion(); 4581 Result.Standard.setFromType(ToType); 4582 Result.Standard.setAllToTypes(ToType); 4583 } 4584 4585 Result.setStdInitializerListElement(toStdInitializerList); 4586 return Result; 4587 } 4588 4589 // C++14 [over.ics.list]p4: 4590 // C++11 [over.ics.list]p3: 4591 // Otherwise, if the parameter is a non-aggregate class X and overload 4592 // resolution chooses a single best constructor [...] the implicit 4593 // conversion sequence is a user-defined conversion sequence. If multiple 4594 // constructors are viable but none is better than the others, the 4595 // implicit conversion sequence is a user-defined conversion sequence. 4596 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4597 // This function can deal with initializer lists. 4598 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4599 /*AllowExplicit=*/false, 4600 InOverloadResolution, /*CStyle=*/false, 4601 AllowObjCWritebackConversion, 4602 /*AllowObjCConversionOnExplicit=*/false); 4603 } 4604 4605 // C++14 [over.ics.list]p5: 4606 // C++11 [over.ics.list]p4: 4607 // Otherwise, if the parameter has an aggregate type which can be 4608 // initialized from the initializer list [...] the implicit conversion 4609 // sequence is a user-defined conversion sequence. 4610 if (ToType->isAggregateType()) { 4611 // Type is an aggregate, argument is an init list. At this point it comes 4612 // down to checking whether the initialization works. 4613 // FIXME: Find out whether this parameter is consumed or not. 4614 InitializedEntity Entity = 4615 InitializedEntity::InitializeParameter(S.Context, ToType, 4616 /*Consumed=*/false); 4617 if (S.CanPerformCopyInitialization(Entity, From)) { 4618 Result.setUserDefined(); 4619 Result.UserDefined.Before.setAsIdentityConversion(); 4620 // Initializer lists don't have a type. 4621 Result.UserDefined.Before.setFromType(QualType()); 4622 Result.UserDefined.Before.setAllToTypes(QualType()); 4623 4624 Result.UserDefined.After.setAsIdentityConversion(); 4625 Result.UserDefined.After.setFromType(ToType); 4626 Result.UserDefined.After.setAllToTypes(ToType); 4627 Result.UserDefined.ConversionFunction = nullptr; 4628 } 4629 return Result; 4630 } 4631 4632 // C++14 [over.ics.list]p6: 4633 // C++11 [over.ics.list]p5: 4634 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4635 if (ToType->isReferenceType()) { 4636 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4637 // mention initializer lists in any way. So we go by what list- 4638 // initialization would do and try to extrapolate from that. 4639 4640 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4641 4642 // If the initializer list has a single element that is reference-related 4643 // to the parameter type, we initialize the reference from that. 4644 if (From->getNumInits() == 1) { 4645 Expr *Init = From->getInit(0); 4646 4647 QualType T2 = Init->getType(); 4648 4649 // If the initializer is the address of an overloaded function, try 4650 // to resolve the overloaded function. If all goes well, T2 is the 4651 // type of the resulting function. 4652 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4653 DeclAccessPair Found; 4654 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4655 Init, ToType, false, Found)) 4656 T2 = Fn->getType(); 4657 } 4658 4659 // Compute some basic properties of the types and the initializer. 4660 bool dummy1 = false; 4661 bool dummy2 = false; 4662 bool dummy3 = false; 4663 Sema::ReferenceCompareResult RefRelationship 4664 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4665 dummy2, dummy3); 4666 4667 if (RefRelationship >= Sema::Ref_Related) { 4668 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4669 SuppressUserConversions, 4670 /*AllowExplicit=*/false); 4671 } 4672 } 4673 4674 // Otherwise, we bind the reference to a temporary created from the 4675 // initializer list. 4676 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4677 InOverloadResolution, 4678 AllowObjCWritebackConversion); 4679 if (Result.isFailure()) 4680 return Result; 4681 assert(!Result.isEllipsis() && 4682 "Sub-initialization cannot result in ellipsis conversion."); 4683 4684 // Can we even bind to a temporary? 4685 if (ToType->isRValueReferenceType() || 4686 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4687 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4688 Result.UserDefined.After; 4689 SCS.ReferenceBinding = true; 4690 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4691 SCS.BindsToRvalue = true; 4692 SCS.BindsToFunctionLvalue = false; 4693 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4694 SCS.ObjCLifetimeConversionBinding = false; 4695 } else 4696 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4697 From, ToType); 4698 return Result; 4699 } 4700 4701 // C++14 [over.ics.list]p7: 4702 // C++11 [over.ics.list]p6: 4703 // Otherwise, if the parameter type is not a class: 4704 if (!ToType->isRecordType()) { 4705 // - if the initializer list has one element that is not itself an 4706 // initializer list, the implicit conversion sequence is the one 4707 // required to convert the element to the parameter type. 4708 unsigned NumInits = From->getNumInits(); 4709 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4710 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4711 SuppressUserConversions, 4712 InOverloadResolution, 4713 AllowObjCWritebackConversion); 4714 // - if the initializer list has no elements, the implicit conversion 4715 // sequence is the identity conversion. 4716 else if (NumInits == 0) { 4717 Result.setStandard(); 4718 Result.Standard.setAsIdentityConversion(); 4719 Result.Standard.setFromType(ToType); 4720 Result.Standard.setAllToTypes(ToType); 4721 } 4722 return Result; 4723 } 4724 4725 // C++14 [over.ics.list]p8: 4726 // C++11 [over.ics.list]p7: 4727 // In all cases other than those enumerated above, no conversion is possible 4728 return Result; 4729 } 4730 4731 /// TryCopyInitialization - Try to copy-initialize a value of type 4732 /// ToType from the expression From. Return the implicit conversion 4733 /// sequence required to pass this argument, which may be a bad 4734 /// conversion sequence (meaning that the argument cannot be passed to 4735 /// a parameter of this type). If @p SuppressUserConversions, then we 4736 /// do not permit any user-defined conversion sequences. 4737 static ImplicitConversionSequence 4738 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4739 bool SuppressUserConversions, 4740 bool InOverloadResolution, 4741 bool AllowObjCWritebackConversion, 4742 bool AllowExplicit) { 4743 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4744 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4745 InOverloadResolution,AllowObjCWritebackConversion); 4746 4747 if (ToType->isReferenceType()) 4748 return TryReferenceInit(S, From, ToType, 4749 /*FIXME:*/From->getLocStart(), 4750 SuppressUserConversions, 4751 AllowExplicit); 4752 4753 return TryImplicitConversion(S, From, ToType, 4754 SuppressUserConversions, 4755 /*AllowExplicit=*/false, 4756 InOverloadResolution, 4757 /*CStyle=*/false, 4758 AllowObjCWritebackConversion, 4759 /*AllowObjCConversionOnExplicit=*/false); 4760 } 4761 4762 static bool TryCopyInitialization(const CanQualType FromQTy, 4763 const CanQualType ToQTy, 4764 Sema &S, 4765 SourceLocation Loc, 4766 ExprValueKind FromVK) { 4767 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4768 ImplicitConversionSequence ICS = 4769 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4770 4771 return !ICS.isBad(); 4772 } 4773 4774 /// TryObjectArgumentInitialization - Try to initialize the object 4775 /// parameter of the given member function (@c Method) from the 4776 /// expression @p From. 4777 static ImplicitConversionSequence 4778 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4779 Expr::Classification FromClassification, 4780 CXXMethodDecl *Method, 4781 CXXRecordDecl *ActingContext) { 4782 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4783 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4784 // const volatile object. 4785 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4786 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4787 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4788 4789 // Set up the conversion sequence as a "bad" conversion, to allow us 4790 // to exit early. 4791 ImplicitConversionSequence ICS; 4792 4793 // We need to have an object of class type. 4794 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4795 FromType = PT->getPointeeType(); 4796 4797 // When we had a pointer, it's implicitly dereferenced, so we 4798 // better have an lvalue. 4799 assert(FromClassification.isLValue()); 4800 } 4801 4802 assert(FromType->isRecordType()); 4803 4804 // C++0x [over.match.funcs]p4: 4805 // For non-static member functions, the type of the implicit object 4806 // parameter is 4807 // 4808 // - "lvalue reference to cv X" for functions declared without a 4809 // ref-qualifier or with the & ref-qualifier 4810 // - "rvalue reference to cv X" for functions declared with the && 4811 // ref-qualifier 4812 // 4813 // where X is the class of which the function is a member and cv is the 4814 // cv-qualification on the member function declaration. 4815 // 4816 // However, when finding an implicit conversion sequence for the argument, we 4817 // are not allowed to create temporaries or perform user-defined conversions 4818 // (C++ [over.match.funcs]p5). We perform a simplified version of 4819 // reference binding here, that allows class rvalues to bind to 4820 // non-constant references. 4821 4822 // First check the qualifiers. 4823 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4824 if (ImplicitParamType.getCVRQualifiers() 4825 != FromTypeCanon.getLocalCVRQualifiers() && 4826 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4827 ICS.setBad(BadConversionSequence::bad_qualifiers, 4828 FromType, ImplicitParamType); 4829 return ICS; 4830 } 4831 4832 // Check that we have either the same type or a derived type. It 4833 // affects the conversion rank. 4834 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4835 ImplicitConversionKind SecondKind; 4836 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4837 SecondKind = ICK_Identity; 4838 } else if (S.IsDerivedFrom(FromType, ClassType)) 4839 SecondKind = ICK_Derived_To_Base; 4840 else { 4841 ICS.setBad(BadConversionSequence::unrelated_class, 4842 FromType, ImplicitParamType); 4843 return ICS; 4844 } 4845 4846 // Check the ref-qualifier. 4847 switch (Method->getRefQualifier()) { 4848 case RQ_None: 4849 // Do nothing; we don't care about lvalueness or rvalueness. 4850 break; 4851 4852 case RQ_LValue: 4853 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4854 // non-const lvalue reference cannot bind to an rvalue 4855 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4856 ImplicitParamType); 4857 return ICS; 4858 } 4859 break; 4860 4861 case RQ_RValue: 4862 if (!FromClassification.isRValue()) { 4863 // rvalue reference cannot bind to an lvalue 4864 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4865 ImplicitParamType); 4866 return ICS; 4867 } 4868 break; 4869 } 4870 4871 // Success. Mark this as a reference binding. 4872 ICS.setStandard(); 4873 ICS.Standard.setAsIdentityConversion(); 4874 ICS.Standard.Second = SecondKind; 4875 ICS.Standard.setFromType(FromType); 4876 ICS.Standard.setAllToTypes(ImplicitParamType); 4877 ICS.Standard.ReferenceBinding = true; 4878 ICS.Standard.DirectBinding = true; 4879 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4880 ICS.Standard.BindsToFunctionLvalue = false; 4881 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4882 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4883 = (Method->getRefQualifier() == RQ_None); 4884 return ICS; 4885 } 4886 4887 /// PerformObjectArgumentInitialization - Perform initialization of 4888 /// the implicit object parameter for the given Method with the given 4889 /// expression. 4890 ExprResult 4891 Sema::PerformObjectArgumentInitialization(Expr *From, 4892 NestedNameSpecifier *Qualifier, 4893 NamedDecl *FoundDecl, 4894 CXXMethodDecl *Method) { 4895 QualType FromRecordType, DestType; 4896 QualType ImplicitParamRecordType = 4897 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4898 4899 Expr::Classification FromClassification; 4900 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4901 FromRecordType = PT->getPointeeType(); 4902 DestType = Method->getThisType(Context); 4903 FromClassification = Expr::Classification::makeSimpleLValue(); 4904 } else { 4905 FromRecordType = From->getType(); 4906 DestType = ImplicitParamRecordType; 4907 FromClassification = From->Classify(Context); 4908 } 4909 4910 // Note that we always use the true parent context when performing 4911 // the actual argument initialization. 4912 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4913 *this, From->getType(), FromClassification, Method, Method->getParent()); 4914 if (ICS.isBad()) { 4915 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4916 Qualifiers FromQs = FromRecordType.getQualifiers(); 4917 Qualifiers ToQs = DestType.getQualifiers(); 4918 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4919 if (CVR) { 4920 Diag(From->getLocStart(), 4921 diag::err_member_function_call_bad_cvr) 4922 << Method->getDeclName() << FromRecordType << (CVR - 1) 4923 << From->getSourceRange(); 4924 Diag(Method->getLocation(), diag::note_previous_decl) 4925 << Method->getDeclName(); 4926 return ExprError(); 4927 } 4928 } 4929 4930 return Diag(From->getLocStart(), 4931 diag::err_implicit_object_parameter_init) 4932 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4933 } 4934 4935 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4936 ExprResult FromRes = 4937 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4938 if (FromRes.isInvalid()) 4939 return ExprError(); 4940 From = FromRes.get(); 4941 } 4942 4943 if (!Context.hasSameType(From->getType(), DestType)) 4944 From = ImpCastExprToType(From, DestType, CK_NoOp, 4945 From->getValueKind()).get(); 4946 return From; 4947 } 4948 4949 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4950 /// expression From to bool (C++0x [conv]p3). 4951 static ImplicitConversionSequence 4952 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4953 return TryImplicitConversion(S, From, S.Context.BoolTy, 4954 /*SuppressUserConversions=*/false, 4955 /*AllowExplicit=*/true, 4956 /*InOverloadResolution=*/false, 4957 /*CStyle=*/false, 4958 /*AllowObjCWritebackConversion=*/false, 4959 /*AllowObjCConversionOnExplicit=*/false); 4960 } 4961 4962 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4963 /// of the expression From to bool (C++0x [conv]p3). 4964 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4965 if (checkPlaceholderForOverload(*this, From)) 4966 return ExprError(); 4967 4968 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4969 if (!ICS.isBad()) 4970 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4971 4972 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4973 return Diag(From->getLocStart(), 4974 diag::err_typecheck_bool_condition) 4975 << From->getType() << From->getSourceRange(); 4976 return ExprError(); 4977 } 4978 4979 /// Check that the specified conversion is permitted in a converted constant 4980 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4981 /// is acceptable. 4982 static bool CheckConvertedConstantConversions(Sema &S, 4983 StandardConversionSequence &SCS) { 4984 // Since we know that the target type is an integral or unscoped enumeration 4985 // type, most conversion kinds are impossible. All possible First and Third 4986 // conversions are fine. 4987 switch (SCS.Second) { 4988 case ICK_Identity: 4989 case ICK_NoReturn_Adjustment: 4990 case ICK_Integral_Promotion: 4991 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 4992 return true; 4993 4994 case ICK_Boolean_Conversion: 4995 // Conversion from an integral or unscoped enumeration type to bool is 4996 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 4997 // conversion, so we allow it in a converted constant expression. 4998 // 4999 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5000 // a lot of popular code. We should at least add a warning for this 5001 // (non-conforming) extension. 5002 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5003 SCS.getToType(2)->isBooleanType(); 5004 5005 case ICK_Pointer_Conversion: 5006 case ICK_Pointer_Member: 5007 // C++1z: null pointer conversions and null member pointer conversions are 5008 // only permitted if the source type is std::nullptr_t. 5009 return SCS.getFromType()->isNullPtrType(); 5010 5011 case ICK_Floating_Promotion: 5012 case ICK_Complex_Promotion: 5013 case ICK_Floating_Conversion: 5014 case ICK_Complex_Conversion: 5015 case ICK_Floating_Integral: 5016 case ICK_Compatible_Conversion: 5017 case ICK_Derived_To_Base: 5018 case ICK_Vector_Conversion: 5019 case ICK_Vector_Splat: 5020 case ICK_Complex_Real: 5021 case ICK_Block_Pointer_Conversion: 5022 case ICK_TransparentUnionConversion: 5023 case ICK_Writeback_Conversion: 5024 case ICK_Zero_Event_Conversion: 5025 case ICK_C_Only_Conversion: 5026 return false; 5027 5028 case ICK_Lvalue_To_Rvalue: 5029 case ICK_Array_To_Pointer: 5030 case ICK_Function_To_Pointer: 5031 llvm_unreachable("found a first conversion kind in Second"); 5032 5033 case ICK_Qualification: 5034 llvm_unreachable("found a third conversion kind in Second"); 5035 5036 case ICK_Num_Conversion_Kinds: 5037 break; 5038 } 5039 5040 llvm_unreachable("unknown conversion kind"); 5041 } 5042 5043 /// CheckConvertedConstantExpression - Check that the expression From is a 5044 /// converted constant expression of type T, perform the conversion and produce 5045 /// the converted expression, per C++11 [expr.const]p3. 5046 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5047 QualType T, APValue &Value, 5048 Sema::CCEKind CCE, 5049 bool RequireInt) { 5050 assert(S.getLangOpts().CPlusPlus11 && 5051 "converted constant expression outside C++11"); 5052 5053 if (checkPlaceholderForOverload(S, From)) 5054 return ExprError(); 5055 5056 // C++1z [expr.const]p3: 5057 // A converted constant expression of type T is an expression, 5058 // implicitly converted to type T, where the converted 5059 // expression is a constant expression and the implicit conversion 5060 // sequence contains only [... list of conversions ...]. 5061 ImplicitConversionSequence ICS = 5062 TryCopyInitialization(S, From, T, 5063 /*SuppressUserConversions=*/false, 5064 /*InOverloadResolution=*/false, 5065 /*AllowObjcWritebackConversion=*/false, 5066 /*AllowExplicit=*/false); 5067 StandardConversionSequence *SCS = nullptr; 5068 switch (ICS.getKind()) { 5069 case ImplicitConversionSequence::StandardConversion: 5070 SCS = &ICS.Standard; 5071 break; 5072 case ImplicitConversionSequence::UserDefinedConversion: 5073 // We are converting to a non-class type, so the Before sequence 5074 // must be trivial. 5075 SCS = &ICS.UserDefined.After; 5076 break; 5077 case ImplicitConversionSequence::AmbiguousConversion: 5078 case ImplicitConversionSequence::BadConversion: 5079 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5080 return S.Diag(From->getLocStart(), 5081 diag::err_typecheck_converted_constant_expression) 5082 << From->getType() << From->getSourceRange() << T; 5083 return ExprError(); 5084 5085 case ImplicitConversionSequence::EllipsisConversion: 5086 llvm_unreachable("ellipsis conversion in converted constant expression"); 5087 } 5088 5089 // Check that we would only use permitted conversions. 5090 if (!CheckConvertedConstantConversions(S, *SCS)) { 5091 return S.Diag(From->getLocStart(), 5092 diag::err_typecheck_converted_constant_expression_disallowed) 5093 << From->getType() << From->getSourceRange() << T; 5094 } 5095 // [...] and where the reference binding (if any) binds directly. 5096 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5097 return S.Diag(From->getLocStart(), 5098 diag::err_typecheck_converted_constant_expression_indirect) 5099 << From->getType() << From->getSourceRange() << T; 5100 } 5101 5102 ExprResult Result = 5103 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5104 if (Result.isInvalid()) 5105 return Result; 5106 5107 // Check for a narrowing implicit conversion. 5108 APValue PreNarrowingValue; 5109 QualType PreNarrowingType; 5110 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5111 PreNarrowingType)) { 5112 case NK_Variable_Narrowing: 5113 // Implicit conversion to a narrower type, and the value is not a constant 5114 // expression. We'll diagnose this in a moment. 5115 case NK_Not_Narrowing: 5116 break; 5117 5118 case NK_Constant_Narrowing: 5119 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5120 << CCE << /*Constant*/1 5121 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5122 break; 5123 5124 case NK_Type_Narrowing: 5125 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5126 << CCE << /*Constant*/0 << From->getType() << T; 5127 break; 5128 } 5129 5130 // Check the expression is a constant expression. 5131 SmallVector<PartialDiagnosticAt, 8> Notes; 5132 Expr::EvalResult Eval; 5133 Eval.Diag = &Notes; 5134 5135 if ((T->isReferenceType() 5136 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5137 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5138 (RequireInt && !Eval.Val.isInt())) { 5139 // The expression can't be folded, so we can't keep it at this position in 5140 // the AST. 5141 Result = ExprError(); 5142 } else { 5143 Value = Eval.Val; 5144 5145 if (Notes.empty()) { 5146 // It's a constant expression. 5147 return Result; 5148 } 5149 } 5150 5151 // It's not a constant expression. Produce an appropriate diagnostic. 5152 if (Notes.size() == 1 && 5153 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5154 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5155 else { 5156 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5157 << CCE << From->getSourceRange(); 5158 for (unsigned I = 0; I < Notes.size(); ++I) 5159 S.Diag(Notes[I].first, Notes[I].second); 5160 } 5161 return ExprError(); 5162 } 5163 5164 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5165 APValue &Value, CCEKind CCE) { 5166 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5167 } 5168 5169 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5170 llvm::APSInt &Value, 5171 CCEKind CCE) { 5172 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5173 5174 APValue V; 5175 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5176 if (!R.isInvalid()) 5177 Value = V.getInt(); 5178 return R; 5179 } 5180 5181 5182 /// dropPointerConversions - If the given standard conversion sequence 5183 /// involves any pointer conversions, remove them. This may change 5184 /// the result type of the conversion sequence. 5185 static void dropPointerConversion(StandardConversionSequence &SCS) { 5186 if (SCS.Second == ICK_Pointer_Conversion) { 5187 SCS.Second = ICK_Identity; 5188 SCS.Third = ICK_Identity; 5189 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5190 } 5191 } 5192 5193 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5194 /// convert the expression From to an Objective-C pointer type. 5195 static ImplicitConversionSequence 5196 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5197 // Do an implicit conversion to 'id'. 5198 QualType Ty = S.Context.getObjCIdType(); 5199 ImplicitConversionSequence ICS 5200 = TryImplicitConversion(S, From, Ty, 5201 // FIXME: Are these flags correct? 5202 /*SuppressUserConversions=*/false, 5203 /*AllowExplicit=*/true, 5204 /*InOverloadResolution=*/false, 5205 /*CStyle=*/false, 5206 /*AllowObjCWritebackConversion=*/false, 5207 /*AllowObjCConversionOnExplicit=*/true); 5208 5209 // Strip off any final conversions to 'id'. 5210 switch (ICS.getKind()) { 5211 case ImplicitConversionSequence::BadConversion: 5212 case ImplicitConversionSequence::AmbiguousConversion: 5213 case ImplicitConversionSequence::EllipsisConversion: 5214 break; 5215 5216 case ImplicitConversionSequence::UserDefinedConversion: 5217 dropPointerConversion(ICS.UserDefined.After); 5218 break; 5219 5220 case ImplicitConversionSequence::StandardConversion: 5221 dropPointerConversion(ICS.Standard); 5222 break; 5223 } 5224 5225 return ICS; 5226 } 5227 5228 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5229 /// conversion of the expression From to an Objective-C pointer type. 5230 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5231 if (checkPlaceholderForOverload(*this, From)) 5232 return ExprError(); 5233 5234 QualType Ty = Context.getObjCIdType(); 5235 ImplicitConversionSequence ICS = 5236 TryContextuallyConvertToObjCPointer(*this, From); 5237 if (!ICS.isBad()) 5238 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5239 return ExprError(); 5240 } 5241 5242 /// Determine whether the provided type is an integral type, or an enumeration 5243 /// type of a permitted flavor. 5244 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5245 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5246 : T->isIntegralOrUnscopedEnumerationType(); 5247 } 5248 5249 static ExprResult 5250 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5251 Sema::ContextualImplicitConverter &Converter, 5252 QualType T, UnresolvedSetImpl &ViableConversions) { 5253 5254 if (Converter.Suppress) 5255 return ExprError(); 5256 5257 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5258 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5259 CXXConversionDecl *Conv = 5260 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5261 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5262 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5263 } 5264 return From; 5265 } 5266 5267 static bool 5268 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5269 Sema::ContextualImplicitConverter &Converter, 5270 QualType T, bool HadMultipleCandidates, 5271 UnresolvedSetImpl &ExplicitConversions) { 5272 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5273 DeclAccessPair Found = ExplicitConversions[0]; 5274 CXXConversionDecl *Conversion = 5275 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5276 5277 // The user probably meant to invoke the given explicit 5278 // conversion; use it. 5279 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5280 std::string TypeStr; 5281 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5282 5283 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5284 << FixItHint::CreateInsertion(From->getLocStart(), 5285 "static_cast<" + TypeStr + ">(") 5286 << FixItHint::CreateInsertion( 5287 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5288 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5289 5290 // If we aren't in a SFINAE context, build a call to the 5291 // explicit conversion function. 5292 if (SemaRef.isSFINAEContext()) 5293 return true; 5294 5295 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5296 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5297 HadMultipleCandidates); 5298 if (Result.isInvalid()) 5299 return true; 5300 // Record usage of conversion in an implicit cast. 5301 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5302 CK_UserDefinedConversion, Result.get(), 5303 nullptr, Result.get()->getValueKind()); 5304 } 5305 return false; 5306 } 5307 5308 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5309 Sema::ContextualImplicitConverter &Converter, 5310 QualType T, bool HadMultipleCandidates, 5311 DeclAccessPair &Found) { 5312 CXXConversionDecl *Conversion = 5313 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5314 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5315 5316 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5317 if (!Converter.SuppressConversion) { 5318 if (SemaRef.isSFINAEContext()) 5319 return true; 5320 5321 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5322 << From->getSourceRange(); 5323 } 5324 5325 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5326 HadMultipleCandidates); 5327 if (Result.isInvalid()) 5328 return true; 5329 // Record usage of conversion in an implicit cast. 5330 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5331 CK_UserDefinedConversion, Result.get(), 5332 nullptr, Result.get()->getValueKind()); 5333 return false; 5334 } 5335 5336 static ExprResult finishContextualImplicitConversion( 5337 Sema &SemaRef, SourceLocation Loc, Expr *From, 5338 Sema::ContextualImplicitConverter &Converter) { 5339 if (!Converter.match(From->getType()) && !Converter.Suppress) 5340 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5341 << From->getSourceRange(); 5342 5343 return SemaRef.DefaultLvalueConversion(From); 5344 } 5345 5346 static void 5347 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5348 UnresolvedSetImpl &ViableConversions, 5349 OverloadCandidateSet &CandidateSet) { 5350 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5351 DeclAccessPair FoundDecl = ViableConversions[I]; 5352 NamedDecl *D = FoundDecl.getDecl(); 5353 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5354 if (isa<UsingShadowDecl>(D)) 5355 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5356 5357 CXXConversionDecl *Conv; 5358 FunctionTemplateDecl *ConvTemplate; 5359 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5360 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5361 else 5362 Conv = cast<CXXConversionDecl>(D); 5363 5364 if (ConvTemplate) 5365 SemaRef.AddTemplateConversionCandidate( 5366 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5367 /*AllowObjCConversionOnExplicit=*/false); 5368 else 5369 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5370 ToType, CandidateSet, 5371 /*AllowObjCConversionOnExplicit=*/false); 5372 } 5373 } 5374 5375 /// \brief Attempt to convert the given expression to a type which is accepted 5376 /// by the given converter. 5377 /// 5378 /// This routine will attempt to convert an expression of class type to a 5379 /// type accepted by the specified converter. In C++11 and before, the class 5380 /// must have a single non-explicit conversion function converting to a matching 5381 /// type. In C++1y, there can be multiple such conversion functions, but only 5382 /// one target type. 5383 /// 5384 /// \param Loc The source location of the construct that requires the 5385 /// conversion. 5386 /// 5387 /// \param From The expression we're converting from. 5388 /// 5389 /// \param Converter Used to control and diagnose the conversion process. 5390 /// 5391 /// \returns The expression, converted to an integral or enumeration type if 5392 /// successful. 5393 ExprResult Sema::PerformContextualImplicitConversion( 5394 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5395 // We can't perform any more checking for type-dependent expressions. 5396 if (From->isTypeDependent()) 5397 return From; 5398 5399 // Process placeholders immediately. 5400 if (From->hasPlaceholderType()) { 5401 ExprResult result = CheckPlaceholderExpr(From); 5402 if (result.isInvalid()) 5403 return result; 5404 From = result.get(); 5405 } 5406 5407 // If the expression already has a matching type, we're golden. 5408 QualType T = From->getType(); 5409 if (Converter.match(T)) 5410 return DefaultLvalueConversion(From); 5411 5412 // FIXME: Check for missing '()' if T is a function type? 5413 5414 // We can only perform contextual implicit conversions on objects of class 5415 // type. 5416 const RecordType *RecordTy = T->getAs<RecordType>(); 5417 if (!RecordTy || !getLangOpts().CPlusPlus) { 5418 if (!Converter.Suppress) 5419 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5420 return From; 5421 } 5422 5423 // We must have a complete class type. 5424 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5425 ContextualImplicitConverter &Converter; 5426 Expr *From; 5427 5428 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5429 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5430 5431 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5432 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5433 } 5434 } IncompleteDiagnoser(Converter, From); 5435 5436 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5437 return From; 5438 5439 // Look for a conversion to an integral or enumeration type. 5440 UnresolvedSet<4> 5441 ViableConversions; // These are *potentially* viable in C++1y. 5442 UnresolvedSet<4> ExplicitConversions; 5443 const auto &Conversions = 5444 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5445 5446 bool HadMultipleCandidates = 5447 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5448 5449 // To check that there is only one target type, in C++1y: 5450 QualType ToType; 5451 bool HasUniqueTargetType = true; 5452 5453 // Collect explicit or viable (potentially in C++1y) conversions. 5454 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5455 NamedDecl *D = (*I)->getUnderlyingDecl(); 5456 CXXConversionDecl *Conversion; 5457 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5458 if (ConvTemplate) { 5459 if (getLangOpts().CPlusPlus14) 5460 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5461 else 5462 continue; // C++11 does not consider conversion operator templates(?). 5463 } else 5464 Conversion = cast<CXXConversionDecl>(D); 5465 5466 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5467 "Conversion operator templates are considered potentially " 5468 "viable in C++1y"); 5469 5470 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5471 if (Converter.match(CurToType) || ConvTemplate) { 5472 5473 if (Conversion->isExplicit()) { 5474 // FIXME: For C++1y, do we need this restriction? 5475 // cf. diagnoseNoViableConversion() 5476 if (!ConvTemplate) 5477 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5478 } else { 5479 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5480 if (ToType.isNull()) 5481 ToType = CurToType.getUnqualifiedType(); 5482 else if (HasUniqueTargetType && 5483 (CurToType.getUnqualifiedType() != ToType)) 5484 HasUniqueTargetType = false; 5485 } 5486 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5487 } 5488 } 5489 } 5490 5491 if (getLangOpts().CPlusPlus14) { 5492 // C++1y [conv]p6: 5493 // ... An expression e of class type E appearing in such a context 5494 // is said to be contextually implicitly converted to a specified 5495 // type T and is well-formed if and only if e can be implicitly 5496 // converted to a type T that is determined as follows: E is searched 5497 // for conversion functions whose return type is cv T or reference to 5498 // cv T such that T is allowed by the context. There shall be 5499 // exactly one such T. 5500 5501 // If no unique T is found: 5502 if (ToType.isNull()) { 5503 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5504 HadMultipleCandidates, 5505 ExplicitConversions)) 5506 return ExprError(); 5507 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5508 } 5509 5510 // If more than one unique Ts are found: 5511 if (!HasUniqueTargetType) 5512 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5513 ViableConversions); 5514 5515 // If one unique T is found: 5516 // First, build a candidate set from the previously recorded 5517 // potentially viable conversions. 5518 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5519 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5520 CandidateSet); 5521 5522 // Then, perform overload resolution over the candidate set. 5523 OverloadCandidateSet::iterator Best; 5524 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5525 case OR_Success: { 5526 // Apply this conversion. 5527 DeclAccessPair Found = 5528 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5529 if (recordConversion(*this, Loc, From, Converter, T, 5530 HadMultipleCandidates, Found)) 5531 return ExprError(); 5532 break; 5533 } 5534 case OR_Ambiguous: 5535 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5536 ViableConversions); 5537 case OR_No_Viable_Function: 5538 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5539 HadMultipleCandidates, 5540 ExplicitConversions)) 5541 return ExprError(); 5542 // fall through 'OR_Deleted' case. 5543 case OR_Deleted: 5544 // We'll complain below about a non-integral condition type. 5545 break; 5546 } 5547 } else { 5548 switch (ViableConversions.size()) { 5549 case 0: { 5550 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5551 HadMultipleCandidates, 5552 ExplicitConversions)) 5553 return ExprError(); 5554 5555 // We'll complain below about a non-integral condition type. 5556 break; 5557 } 5558 case 1: { 5559 // Apply this conversion. 5560 DeclAccessPair Found = ViableConversions[0]; 5561 if (recordConversion(*this, Loc, From, Converter, T, 5562 HadMultipleCandidates, Found)) 5563 return ExprError(); 5564 break; 5565 } 5566 default: 5567 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5568 ViableConversions); 5569 } 5570 } 5571 5572 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5573 } 5574 5575 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5576 /// an acceptable non-member overloaded operator for a call whose 5577 /// arguments have types T1 (and, if non-empty, T2). This routine 5578 /// implements the check in C++ [over.match.oper]p3b2 concerning 5579 /// enumeration types. 5580 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5581 FunctionDecl *Fn, 5582 ArrayRef<Expr *> Args) { 5583 QualType T1 = Args[0]->getType(); 5584 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5585 5586 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5587 return true; 5588 5589 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5590 return true; 5591 5592 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5593 if (Proto->getNumParams() < 1) 5594 return false; 5595 5596 if (T1->isEnumeralType()) { 5597 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5598 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5599 return true; 5600 } 5601 5602 if (Proto->getNumParams() < 2) 5603 return false; 5604 5605 if (!T2.isNull() && T2->isEnumeralType()) { 5606 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5607 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5608 return true; 5609 } 5610 5611 return false; 5612 } 5613 5614 /// AddOverloadCandidate - Adds the given function to the set of 5615 /// candidate functions, using the given function call arguments. If 5616 /// @p SuppressUserConversions, then don't allow user-defined 5617 /// conversions via constructors or conversion operators. 5618 /// 5619 /// \param PartialOverloading true if we are performing "partial" overloading 5620 /// based on an incomplete set of function arguments. This feature is used by 5621 /// code completion. 5622 void 5623 Sema::AddOverloadCandidate(FunctionDecl *Function, 5624 DeclAccessPair FoundDecl, 5625 ArrayRef<Expr *> Args, 5626 OverloadCandidateSet &CandidateSet, 5627 bool SuppressUserConversions, 5628 bool PartialOverloading, 5629 bool AllowExplicit) { 5630 const FunctionProtoType *Proto 5631 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5632 assert(Proto && "Functions without a prototype cannot be overloaded"); 5633 assert(!Function->getDescribedFunctionTemplate() && 5634 "Use AddTemplateOverloadCandidate for function templates"); 5635 5636 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5637 if (!isa<CXXConstructorDecl>(Method)) { 5638 // If we get here, it's because we're calling a member function 5639 // that is named without a member access expression (e.g., 5640 // "this->f") that was either written explicitly or created 5641 // implicitly. This can happen with a qualified call to a member 5642 // function, e.g., X::f(). We use an empty type for the implied 5643 // object argument (C++ [over.call.func]p3), and the acting context 5644 // is irrelevant. 5645 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5646 QualType(), Expr::Classification::makeSimpleLValue(), 5647 Args, CandidateSet, SuppressUserConversions, 5648 PartialOverloading); 5649 return; 5650 } 5651 // We treat a constructor like a non-member function, since its object 5652 // argument doesn't participate in overload resolution. 5653 } 5654 5655 if (!CandidateSet.isNewCandidate(Function)) 5656 return; 5657 5658 // C++ [over.match.oper]p3: 5659 // if no operand has a class type, only those non-member functions in the 5660 // lookup set that have a first parameter of type T1 or "reference to 5661 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5662 // is a right operand) a second parameter of type T2 or "reference to 5663 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5664 // candidate functions. 5665 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5666 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5667 return; 5668 5669 // C++11 [class.copy]p11: [DR1402] 5670 // A defaulted move constructor that is defined as deleted is ignored by 5671 // overload resolution. 5672 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5673 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5674 Constructor->isMoveConstructor()) 5675 return; 5676 5677 // Overload resolution is always an unevaluated context. 5678 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5679 5680 // Add this candidate 5681 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5682 Candidate.FoundDecl = FoundDecl; 5683 Candidate.Function = Function; 5684 Candidate.Viable = true; 5685 Candidate.IsSurrogate = false; 5686 Candidate.IgnoreObjectArgument = false; 5687 Candidate.ExplicitCallArguments = Args.size(); 5688 5689 if (Constructor) { 5690 // C++ [class.copy]p3: 5691 // A member function template is never instantiated to perform the copy 5692 // of a class object to an object of its class type. 5693 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5694 if (Args.size() == 1 && 5695 Constructor->isSpecializationCopyingObject() && 5696 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5697 IsDerivedFrom(Args[0]->getType(), ClassType))) { 5698 Candidate.Viable = false; 5699 Candidate.FailureKind = ovl_fail_illegal_constructor; 5700 return; 5701 } 5702 } 5703 5704 unsigned NumParams = Proto->getNumParams(); 5705 5706 // (C++ 13.3.2p2): A candidate function having fewer than m 5707 // parameters is viable only if it has an ellipsis in its parameter 5708 // list (8.3.5). 5709 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5710 !Proto->isVariadic()) { 5711 Candidate.Viable = false; 5712 Candidate.FailureKind = ovl_fail_too_many_arguments; 5713 return; 5714 } 5715 5716 // (C++ 13.3.2p2): A candidate function having more than m parameters 5717 // is viable only if the (m+1)st parameter has a default argument 5718 // (8.3.6). For the purposes of overload resolution, the 5719 // parameter list is truncated on the right, so that there are 5720 // exactly m parameters. 5721 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5722 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5723 // Not enough arguments. 5724 Candidate.Viable = false; 5725 Candidate.FailureKind = ovl_fail_too_few_arguments; 5726 return; 5727 } 5728 5729 // (CUDA B.1): Check for invalid calls between targets. 5730 if (getLangOpts().CUDA) 5731 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5732 // Skip the check for callers that are implicit members, because in this 5733 // case we may not yet know what the member's target is; the target is 5734 // inferred for the member automatically, based on the bases and fields of 5735 // the class. 5736 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5737 Candidate.Viable = false; 5738 Candidate.FailureKind = ovl_fail_bad_target; 5739 return; 5740 } 5741 5742 // Determine the implicit conversion sequences for each of the 5743 // arguments. 5744 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5745 if (ArgIdx < NumParams) { 5746 // (C++ 13.3.2p3): for F to be a viable function, there shall 5747 // exist for each argument an implicit conversion sequence 5748 // (13.3.3.1) that converts that argument to the corresponding 5749 // parameter of F. 5750 QualType ParamType = Proto->getParamType(ArgIdx); 5751 Candidate.Conversions[ArgIdx] 5752 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5753 SuppressUserConversions, 5754 /*InOverloadResolution=*/true, 5755 /*AllowObjCWritebackConversion=*/ 5756 getLangOpts().ObjCAutoRefCount, 5757 AllowExplicit); 5758 if (Candidate.Conversions[ArgIdx].isBad()) { 5759 Candidate.Viable = false; 5760 Candidate.FailureKind = ovl_fail_bad_conversion; 5761 return; 5762 } 5763 } else { 5764 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5765 // argument for which there is no corresponding parameter is 5766 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5767 Candidate.Conversions[ArgIdx].setEllipsis(); 5768 } 5769 } 5770 5771 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5772 Candidate.Viable = false; 5773 Candidate.FailureKind = ovl_fail_enable_if; 5774 Candidate.DeductionFailure.Data = FailedAttr; 5775 return; 5776 } 5777 } 5778 5779 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5780 bool IsInstance) { 5781 SmallVector<ObjCMethodDecl*, 4> Methods; 5782 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5783 return nullptr; 5784 5785 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5786 bool Match = true; 5787 ObjCMethodDecl *Method = Methods[b]; 5788 unsigned NumNamedArgs = Sel.getNumArgs(); 5789 // Method might have more arguments than selector indicates. This is due 5790 // to addition of c-style arguments in method. 5791 if (Method->param_size() > NumNamedArgs) 5792 NumNamedArgs = Method->param_size(); 5793 if (Args.size() < NumNamedArgs) 5794 continue; 5795 5796 for (unsigned i = 0; i < NumNamedArgs; i++) { 5797 // We can't do any type-checking on a type-dependent argument. 5798 if (Args[i]->isTypeDependent()) { 5799 Match = false; 5800 break; 5801 } 5802 5803 ParmVarDecl *param = Method->parameters()[i]; 5804 Expr *argExpr = Args[i]; 5805 assert(argExpr && "SelectBestMethod(): missing expression"); 5806 5807 // Strip the unbridged-cast placeholder expression off unless it's 5808 // a consumed argument. 5809 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5810 !param->hasAttr<CFConsumedAttr>()) 5811 argExpr = stripARCUnbridgedCast(argExpr); 5812 5813 // If the parameter is __unknown_anytype, move on to the next method. 5814 if (param->getType() == Context.UnknownAnyTy) { 5815 Match = false; 5816 break; 5817 } 5818 5819 ImplicitConversionSequence ConversionState 5820 = TryCopyInitialization(*this, argExpr, param->getType(), 5821 /*SuppressUserConversions*/false, 5822 /*InOverloadResolution=*/true, 5823 /*AllowObjCWritebackConversion=*/ 5824 getLangOpts().ObjCAutoRefCount, 5825 /*AllowExplicit*/false); 5826 if (ConversionState.isBad()) { 5827 Match = false; 5828 break; 5829 } 5830 } 5831 // Promote additional arguments to variadic methods. 5832 if (Match && Method->isVariadic()) { 5833 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5834 if (Args[i]->isTypeDependent()) { 5835 Match = false; 5836 break; 5837 } 5838 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5839 nullptr); 5840 if (Arg.isInvalid()) { 5841 Match = false; 5842 break; 5843 } 5844 } 5845 } else { 5846 // Check for extra arguments to non-variadic methods. 5847 if (Args.size() != NumNamedArgs) 5848 Match = false; 5849 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5850 // Special case when selectors have no argument. In this case, select 5851 // one with the most general result type of 'id'. 5852 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5853 QualType ReturnT = Methods[b]->getReturnType(); 5854 if (ReturnT->isObjCIdType()) 5855 return Methods[b]; 5856 } 5857 } 5858 } 5859 5860 if (Match) 5861 return Method; 5862 } 5863 return nullptr; 5864 } 5865 5866 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5867 // enable_if is order-sensitive. As a result, we need to reverse things 5868 // sometimes. Size of 4 elements is arbitrary. 5869 static SmallVector<EnableIfAttr *, 4> 5870 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5871 SmallVector<EnableIfAttr *, 4> Result; 5872 if (!Function->hasAttrs()) 5873 return Result; 5874 5875 const auto &FuncAttrs = Function->getAttrs(); 5876 for (Attr *Attr : FuncAttrs) 5877 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5878 Result.push_back(EnableIf); 5879 5880 std::reverse(Result.begin(), Result.end()); 5881 return Result; 5882 } 5883 5884 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5885 bool MissingImplicitThis) { 5886 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5887 if (EnableIfAttrs.empty()) 5888 return nullptr; 5889 5890 SFINAETrap Trap(*this); 5891 SmallVector<Expr *, 16> ConvertedArgs; 5892 bool InitializationFailed = false; 5893 bool ContainsValueDependentExpr = false; 5894 5895 // Convert the arguments. 5896 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5897 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5898 !cast<CXXMethodDecl>(Function)->isStatic() && 5899 !isa<CXXConstructorDecl>(Function)) { 5900 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5901 ExprResult R = 5902 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5903 Method, Method); 5904 if (R.isInvalid()) { 5905 InitializationFailed = true; 5906 break; 5907 } 5908 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5909 ConvertedArgs.push_back(R.get()); 5910 } else { 5911 ExprResult R = 5912 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5913 Context, 5914 Function->getParamDecl(i)), 5915 SourceLocation(), 5916 Args[i]); 5917 if (R.isInvalid()) { 5918 InitializationFailed = true; 5919 break; 5920 } 5921 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5922 ConvertedArgs.push_back(R.get()); 5923 } 5924 } 5925 5926 if (InitializationFailed || Trap.hasErrorOccurred()) 5927 return EnableIfAttrs[0]; 5928 5929 // Push default arguments if needed. 5930 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5931 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5932 ParmVarDecl *P = Function->getParamDecl(i); 5933 ExprResult R = PerformCopyInitialization( 5934 InitializedEntity::InitializeParameter(Context, 5935 Function->getParamDecl(i)), 5936 SourceLocation(), 5937 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 5938 : P->getDefaultArg()); 5939 if (R.isInvalid()) { 5940 InitializationFailed = true; 5941 break; 5942 } 5943 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5944 ConvertedArgs.push_back(R.get()); 5945 } 5946 5947 if (InitializationFailed || Trap.hasErrorOccurred()) 5948 return EnableIfAttrs[0]; 5949 } 5950 5951 for (auto *EIA : EnableIfAttrs) { 5952 APValue Result; 5953 if (EIA->getCond()->isValueDependent()) { 5954 // Don't even try now, we'll examine it after instantiation. 5955 continue; 5956 } 5957 5958 if (!EIA->getCond()->EvaluateWithSubstitution( 5959 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5960 if (!ContainsValueDependentExpr) 5961 return EIA; 5962 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5963 return EIA; 5964 } 5965 } 5966 return nullptr; 5967 } 5968 5969 /// \brief Add all of the function declarations in the given function set to 5970 /// the overload candidate set. 5971 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5972 ArrayRef<Expr *> Args, 5973 OverloadCandidateSet& CandidateSet, 5974 TemplateArgumentListInfo *ExplicitTemplateArgs, 5975 bool SuppressUserConversions, 5976 bool PartialOverloading) { 5977 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5978 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5979 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5980 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5981 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5982 cast<CXXMethodDecl>(FD)->getParent(), 5983 Args[0]->getType(), Args[0]->Classify(Context), 5984 Args.slice(1), CandidateSet, 5985 SuppressUserConversions, PartialOverloading); 5986 else 5987 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5988 SuppressUserConversions, PartialOverloading); 5989 } else { 5990 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5991 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5992 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5993 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5994 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5995 ExplicitTemplateArgs, 5996 Args[0]->getType(), 5997 Args[0]->Classify(Context), Args.slice(1), 5998 CandidateSet, SuppressUserConversions, 5999 PartialOverloading); 6000 else 6001 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6002 ExplicitTemplateArgs, Args, 6003 CandidateSet, SuppressUserConversions, 6004 PartialOverloading); 6005 } 6006 } 6007 } 6008 6009 /// AddMethodCandidate - Adds a named decl (which is some kind of 6010 /// method) as a method candidate to the given overload set. 6011 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6012 QualType ObjectType, 6013 Expr::Classification ObjectClassification, 6014 ArrayRef<Expr *> Args, 6015 OverloadCandidateSet& CandidateSet, 6016 bool SuppressUserConversions) { 6017 NamedDecl *Decl = FoundDecl.getDecl(); 6018 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6019 6020 if (isa<UsingShadowDecl>(Decl)) 6021 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6022 6023 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6024 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6025 "Expected a member function template"); 6026 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6027 /*ExplicitArgs*/ nullptr, 6028 ObjectType, ObjectClassification, 6029 Args, CandidateSet, 6030 SuppressUserConversions); 6031 } else { 6032 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6033 ObjectType, ObjectClassification, 6034 Args, 6035 CandidateSet, SuppressUserConversions); 6036 } 6037 } 6038 6039 /// AddMethodCandidate - Adds the given C++ member function to the set 6040 /// of candidate functions, using the given function call arguments 6041 /// and the object argument (@c Object). For example, in a call 6042 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6043 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6044 /// allow user-defined conversions via constructors or conversion 6045 /// operators. 6046 void 6047 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6048 CXXRecordDecl *ActingContext, QualType ObjectType, 6049 Expr::Classification ObjectClassification, 6050 ArrayRef<Expr *> Args, 6051 OverloadCandidateSet &CandidateSet, 6052 bool SuppressUserConversions, 6053 bool PartialOverloading) { 6054 const FunctionProtoType *Proto 6055 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6056 assert(Proto && "Methods without a prototype cannot be overloaded"); 6057 assert(!isa<CXXConstructorDecl>(Method) && 6058 "Use AddOverloadCandidate for constructors"); 6059 6060 if (!CandidateSet.isNewCandidate(Method)) 6061 return; 6062 6063 // C++11 [class.copy]p23: [DR1402] 6064 // A defaulted move assignment operator that is defined as deleted is 6065 // ignored by overload resolution. 6066 if (Method->isDefaulted() && Method->isDeleted() && 6067 Method->isMoveAssignmentOperator()) 6068 return; 6069 6070 // Overload resolution is always an unevaluated context. 6071 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6072 6073 // Add this candidate 6074 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6075 Candidate.FoundDecl = FoundDecl; 6076 Candidate.Function = Method; 6077 Candidate.IsSurrogate = false; 6078 Candidate.IgnoreObjectArgument = false; 6079 Candidate.ExplicitCallArguments = Args.size(); 6080 6081 unsigned NumParams = Proto->getNumParams(); 6082 6083 // (C++ 13.3.2p2): A candidate function having fewer than m 6084 // parameters is viable only if it has an ellipsis in its parameter 6085 // list (8.3.5). 6086 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6087 !Proto->isVariadic()) { 6088 Candidate.Viable = false; 6089 Candidate.FailureKind = ovl_fail_too_many_arguments; 6090 return; 6091 } 6092 6093 // (C++ 13.3.2p2): A candidate function having more than m parameters 6094 // is viable only if the (m+1)st parameter has a default argument 6095 // (8.3.6). For the purposes of overload resolution, the 6096 // parameter list is truncated on the right, so that there are 6097 // exactly m parameters. 6098 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6099 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6100 // Not enough arguments. 6101 Candidate.Viable = false; 6102 Candidate.FailureKind = ovl_fail_too_few_arguments; 6103 return; 6104 } 6105 6106 Candidate.Viable = true; 6107 6108 if (Method->isStatic() || ObjectType.isNull()) 6109 // The implicit object argument is ignored. 6110 Candidate.IgnoreObjectArgument = true; 6111 else { 6112 // Determine the implicit conversion sequence for the object 6113 // parameter. 6114 Candidate.Conversions[0] 6115 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 6116 Method, ActingContext); 6117 if (Candidate.Conversions[0].isBad()) { 6118 Candidate.Viable = false; 6119 Candidate.FailureKind = ovl_fail_bad_conversion; 6120 return; 6121 } 6122 } 6123 6124 // (CUDA B.1): Check for invalid calls between targets. 6125 if (getLangOpts().CUDA) 6126 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6127 if (CheckCUDATarget(Caller, Method)) { 6128 Candidate.Viable = false; 6129 Candidate.FailureKind = ovl_fail_bad_target; 6130 return; 6131 } 6132 6133 // Determine the implicit conversion sequences for each of the 6134 // arguments. 6135 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6136 if (ArgIdx < NumParams) { 6137 // (C++ 13.3.2p3): for F to be a viable function, there shall 6138 // exist for each argument an implicit conversion sequence 6139 // (13.3.3.1) that converts that argument to the corresponding 6140 // parameter of F. 6141 QualType ParamType = Proto->getParamType(ArgIdx); 6142 Candidate.Conversions[ArgIdx + 1] 6143 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6144 SuppressUserConversions, 6145 /*InOverloadResolution=*/true, 6146 /*AllowObjCWritebackConversion=*/ 6147 getLangOpts().ObjCAutoRefCount); 6148 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6149 Candidate.Viable = false; 6150 Candidate.FailureKind = ovl_fail_bad_conversion; 6151 return; 6152 } 6153 } else { 6154 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6155 // argument for which there is no corresponding parameter is 6156 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6157 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6158 } 6159 } 6160 6161 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6162 Candidate.Viable = false; 6163 Candidate.FailureKind = ovl_fail_enable_if; 6164 Candidate.DeductionFailure.Data = FailedAttr; 6165 return; 6166 } 6167 } 6168 6169 /// \brief Add a C++ member function template as a candidate to the candidate 6170 /// set, using template argument deduction to produce an appropriate member 6171 /// function template specialization. 6172 void 6173 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6174 DeclAccessPair FoundDecl, 6175 CXXRecordDecl *ActingContext, 6176 TemplateArgumentListInfo *ExplicitTemplateArgs, 6177 QualType ObjectType, 6178 Expr::Classification ObjectClassification, 6179 ArrayRef<Expr *> Args, 6180 OverloadCandidateSet& CandidateSet, 6181 bool SuppressUserConversions, 6182 bool PartialOverloading) { 6183 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6184 return; 6185 6186 // C++ [over.match.funcs]p7: 6187 // In each case where a candidate is a function template, candidate 6188 // function template specializations are generated using template argument 6189 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6190 // candidate functions in the usual way.113) A given name can refer to one 6191 // or more function templates and also to a set of overloaded non-template 6192 // functions. In such a case, the candidate functions generated from each 6193 // function template are combined with the set of non-template candidate 6194 // functions. 6195 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6196 FunctionDecl *Specialization = nullptr; 6197 if (TemplateDeductionResult Result 6198 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6199 Specialization, Info, PartialOverloading)) { 6200 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6201 Candidate.FoundDecl = FoundDecl; 6202 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6203 Candidate.Viable = false; 6204 Candidate.FailureKind = ovl_fail_bad_deduction; 6205 Candidate.IsSurrogate = false; 6206 Candidate.IgnoreObjectArgument = false; 6207 Candidate.ExplicitCallArguments = Args.size(); 6208 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6209 Info); 6210 return; 6211 } 6212 6213 // Add the function template specialization produced by template argument 6214 // deduction as a candidate. 6215 assert(Specialization && "Missing member function template specialization?"); 6216 assert(isa<CXXMethodDecl>(Specialization) && 6217 "Specialization is not a member function?"); 6218 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6219 ActingContext, ObjectType, ObjectClassification, Args, 6220 CandidateSet, SuppressUserConversions, PartialOverloading); 6221 } 6222 6223 /// \brief Add a C++ function template specialization as a candidate 6224 /// in the candidate set, using template argument deduction to produce 6225 /// an appropriate function template specialization. 6226 void 6227 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6228 DeclAccessPair FoundDecl, 6229 TemplateArgumentListInfo *ExplicitTemplateArgs, 6230 ArrayRef<Expr *> Args, 6231 OverloadCandidateSet& CandidateSet, 6232 bool SuppressUserConversions, 6233 bool PartialOverloading) { 6234 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6235 return; 6236 6237 // C++ [over.match.funcs]p7: 6238 // In each case where a candidate is a function template, candidate 6239 // function template specializations are generated using template argument 6240 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6241 // candidate functions in the usual way.113) A given name can refer to one 6242 // or more function templates and also to a set of overloaded non-template 6243 // functions. In such a case, the candidate functions generated from each 6244 // function template are combined with the set of non-template candidate 6245 // functions. 6246 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6247 FunctionDecl *Specialization = nullptr; 6248 if (TemplateDeductionResult Result 6249 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6250 Specialization, Info, PartialOverloading)) { 6251 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6252 Candidate.FoundDecl = FoundDecl; 6253 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6254 Candidate.Viable = false; 6255 Candidate.FailureKind = ovl_fail_bad_deduction; 6256 Candidate.IsSurrogate = false; 6257 Candidate.IgnoreObjectArgument = false; 6258 Candidate.ExplicitCallArguments = Args.size(); 6259 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6260 Info); 6261 return; 6262 } 6263 6264 // Add the function template specialization produced by template argument 6265 // deduction as a candidate. 6266 assert(Specialization && "Missing function template specialization?"); 6267 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6268 SuppressUserConversions, PartialOverloading); 6269 } 6270 6271 /// Determine whether this is an allowable conversion from the result 6272 /// of an explicit conversion operator to the expected type, per C++ 6273 /// [over.match.conv]p1 and [over.match.ref]p1. 6274 /// 6275 /// \param ConvType The return type of the conversion function. 6276 /// 6277 /// \param ToType The type we are converting to. 6278 /// 6279 /// \param AllowObjCPointerConversion Allow a conversion from one 6280 /// Objective-C pointer to another. 6281 /// 6282 /// \returns true if the conversion is allowable, false otherwise. 6283 static bool isAllowableExplicitConversion(Sema &S, 6284 QualType ConvType, QualType ToType, 6285 bool AllowObjCPointerConversion) { 6286 QualType ToNonRefType = ToType.getNonReferenceType(); 6287 6288 // Easy case: the types are the same. 6289 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6290 return true; 6291 6292 // Allow qualification conversions. 6293 bool ObjCLifetimeConversion; 6294 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6295 ObjCLifetimeConversion)) 6296 return true; 6297 6298 // If we're not allowed to consider Objective-C pointer conversions, 6299 // we're done. 6300 if (!AllowObjCPointerConversion) 6301 return false; 6302 6303 // Is this an Objective-C pointer conversion? 6304 bool IncompatibleObjC = false; 6305 QualType ConvertedType; 6306 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6307 IncompatibleObjC); 6308 } 6309 6310 /// AddConversionCandidate - Add a C++ conversion function as a 6311 /// candidate in the candidate set (C++ [over.match.conv], 6312 /// C++ [over.match.copy]). From is the expression we're converting from, 6313 /// and ToType is the type that we're eventually trying to convert to 6314 /// (which may or may not be the same type as the type that the 6315 /// conversion function produces). 6316 void 6317 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6318 DeclAccessPair FoundDecl, 6319 CXXRecordDecl *ActingContext, 6320 Expr *From, QualType ToType, 6321 OverloadCandidateSet& CandidateSet, 6322 bool AllowObjCConversionOnExplicit) { 6323 assert(!Conversion->getDescribedFunctionTemplate() && 6324 "Conversion function templates use AddTemplateConversionCandidate"); 6325 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6326 if (!CandidateSet.isNewCandidate(Conversion)) 6327 return; 6328 6329 // If the conversion function has an undeduced return type, trigger its 6330 // deduction now. 6331 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6332 if (DeduceReturnType(Conversion, From->getExprLoc())) 6333 return; 6334 ConvType = Conversion->getConversionType().getNonReferenceType(); 6335 } 6336 6337 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6338 // operator is only a candidate if its return type is the target type or 6339 // can be converted to the target type with a qualification conversion. 6340 if (Conversion->isExplicit() && 6341 !isAllowableExplicitConversion(*this, ConvType, ToType, 6342 AllowObjCConversionOnExplicit)) 6343 return; 6344 6345 // Overload resolution is always an unevaluated context. 6346 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6347 6348 // Add this candidate 6349 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6350 Candidate.FoundDecl = FoundDecl; 6351 Candidate.Function = Conversion; 6352 Candidate.IsSurrogate = false; 6353 Candidate.IgnoreObjectArgument = false; 6354 Candidate.FinalConversion.setAsIdentityConversion(); 6355 Candidate.FinalConversion.setFromType(ConvType); 6356 Candidate.FinalConversion.setAllToTypes(ToType); 6357 Candidate.Viable = true; 6358 Candidate.ExplicitCallArguments = 1; 6359 6360 // C++ [over.match.funcs]p4: 6361 // For conversion functions, the function is considered to be a member of 6362 // the class of the implicit implied object argument for the purpose of 6363 // defining the type of the implicit object parameter. 6364 // 6365 // Determine the implicit conversion sequence for the implicit 6366 // object parameter. 6367 QualType ImplicitParamType = From->getType(); 6368 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6369 ImplicitParamType = FromPtrType->getPointeeType(); 6370 CXXRecordDecl *ConversionContext 6371 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6372 6373 Candidate.Conversions[0] 6374 = TryObjectArgumentInitialization(*this, From->getType(), 6375 From->Classify(Context), 6376 Conversion, ConversionContext); 6377 6378 if (Candidate.Conversions[0].isBad()) { 6379 Candidate.Viable = false; 6380 Candidate.FailureKind = ovl_fail_bad_conversion; 6381 return; 6382 } 6383 6384 // We won't go through a user-defined type conversion function to convert a 6385 // derived to base as such conversions are given Conversion Rank. They only 6386 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6387 QualType FromCanon 6388 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6389 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6390 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6391 Candidate.Viable = false; 6392 Candidate.FailureKind = ovl_fail_trivial_conversion; 6393 return; 6394 } 6395 6396 // To determine what the conversion from the result of calling the 6397 // conversion function to the type we're eventually trying to 6398 // convert to (ToType), we need to synthesize a call to the 6399 // conversion function and attempt copy initialization from it. This 6400 // makes sure that we get the right semantics with respect to 6401 // lvalues/rvalues and the type. Fortunately, we can allocate this 6402 // call on the stack and we don't need its arguments to be 6403 // well-formed. 6404 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6405 VK_LValue, From->getLocStart()); 6406 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6407 Context.getPointerType(Conversion->getType()), 6408 CK_FunctionToPointerDecay, 6409 &ConversionRef, VK_RValue); 6410 6411 QualType ConversionType = Conversion->getConversionType(); 6412 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6413 Candidate.Viable = false; 6414 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6415 return; 6416 } 6417 6418 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6419 6420 // Note that it is safe to allocate CallExpr on the stack here because 6421 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6422 // allocator). 6423 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6424 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6425 From->getLocStart()); 6426 ImplicitConversionSequence ICS = 6427 TryCopyInitialization(*this, &Call, ToType, 6428 /*SuppressUserConversions=*/true, 6429 /*InOverloadResolution=*/false, 6430 /*AllowObjCWritebackConversion=*/false); 6431 6432 switch (ICS.getKind()) { 6433 case ImplicitConversionSequence::StandardConversion: 6434 Candidate.FinalConversion = ICS.Standard; 6435 6436 // C++ [over.ics.user]p3: 6437 // If the user-defined conversion is specified by a specialization of a 6438 // conversion function template, the second standard conversion sequence 6439 // shall have exact match rank. 6440 if (Conversion->getPrimaryTemplate() && 6441 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6442 Candidate.Viable = false; 6443 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6444 return; 6445 } 6446 6447 // C++0x [dcl.init.ref]p5: 6448 // In the second case, if the reference is an rvalue reference and 6449 // the second standard conversion sequence of the user-defined 6450 // conversion sequence includes an lvalue-to-rvalue conversion, the 6451 // program is ill-formed. 6452 if (ToType->isRValueReferenceType() && 6453 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6454 Candidate.Viable = false; 6455 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6456 return; 6457 } 6458 break; 6459 6460 case ImplicitConversionSequence::BadConversion: 6461 Candidate.Viable = false; 6462 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6463 return; 6464 6465 default: 6466 llvm_unreachable( 6467 "Can only end up with a standard conversion sequence or failure"); 6468 } 6469 6470 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6471 Candidate.Viable = false; 6472 Candidate.FailureKind = ovl_fail_enable_if; 6473 Candidate.DeductionFailure.Data = FailedAttr; 6474 return; 6475 } 6476 } 6477 6478 /// \brief Adds a conversion function template specialization 6479 /// candidate to the overload set, using template argument deduction 6480 /// to deduce the template arguments of the conversion function 6481 /// template from the type that we are converting to (C++ 6482 /// [temp.deduct.conv]). 6483 void 6484 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6485 DeclAccessPair FoundDecl, 6486 CXXRecordDecl *ActingDC, 6487 Expr *From, QualType ToType, 6488 OverloadCandidateSet &CandidateSet, 6489 bool AllowObjCConversionOnExplicit) { 6490 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6491 "Only conversion function templates permitted here"); 6492 6493 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6494 return; 6495 6496 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6497 CXXConversionDecl *Specialization = nullptr; 6498 if (TemplateDeductionResult Result 6499 = DeduceTemplateArguments(FunctionTemplate, ToType, 6500 Specialization, Info)) { 6501 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6502 Candidate.FoundDecl = FoundDecl; 6503 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6504 Candidate.Viable = false; 6505 Candidate.FailureKind = ovl_fail_bad_deduction; 6506 Candidate.IsSurrogate = false; 6507 Candidate.IgnoreObjectArgument = false; 6508 Candidate.ExplicitCallArguments = 1; 6509 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6510 Info); 6511 return; 6512 } 6513 6514 // Add the conversion function template specialization produced by 6515 // template argument deduction as a candidate. 6516 assert(Specialization && "Missing function template specialization?"); 6517 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6518 CandidateSet, AllowObjCConversionOnExplicit); 6519 } 6520 6521 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6522 /// converts the given @c Object to a function pointer via the 6523 /// conversion function @c Conversion, and then attempts to call it 6524 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6525 /// the type of function that we'll eventually be calling. 6526 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6527 DeclAccessPair FoundDecl, 6528 CXXRecordDecl *ActingContext, 6529 const FunctionProtoType *Proto, 6530 Expr *Object, 6531 ArrayRef<Expr *> Args, 6532 OverloadCandidateSet& CandidateSet) { 6533 if (!CandidateSet.isNewCandidate(Conversion)) 6534 return; 6535 6536 // Overload resolution is always an unevaluated context. 6537 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6538 6539 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6540 Candidate.FoundDecl = FoundDecl; 6541 Candidate.Function = nullptr; 6542 Candidate.Surrogate = Conversion; 6543 Candidate.Viable = true; 6544 Candidate.IsSurrogate = true; 6545 Candidate.IgnoreObjectArgument = false; 6546 Candidate.ExplicitCallArguments = Args.size(); 6547 6548 // Determine the implicit conversion sequence for the implicit 6549 // object parameter. 6550 ImplicitConversionSequence ObjectInit 6551 = TryObjectArgumentInitialization(*this, Object->getType(), 6552 Object->Classify(Context), 6553 Conversion, ActingContext); 6554 if (ObjectInit.isBad()) { 6555 Candidate.Viable = false; 6556 Candidate.FailureKind = ovl_fail_bad_conversion; 6557 Candidate.Conversions[0] = ObjectInit; 6558 return; 6559 } 6560 6561 // The first conversion is actually a user-defined conversion whose 6562 // first conversion is ObjectInit's standard conversion (which is 6563 // effectively a reference binding). Record it as such. 6564 Candidate.Conversions[0].setUserDefined(); 6565 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6566 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6567 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6568 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6569 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6570 Candidate.Conversions[0].UserDefined.After 6571 = Candidate.Conversions[0].UserDefined.Before; 6572 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6573 6574 // Find the 6575 unsigned NumParams = Proto->getNumParams(); 6576 6577 // (C++ 13.3.2p2): A candidate function having fewer than m 6578 // parameters is viable only if it has an ellipsis in its parameter 6579 // list (8.3.5). 6580 if (Args.size() > NumParams && !Proto->isVariadic()) { 6581 Candidate.Viable = false; 6582 Candidate.FailureKind = ovl_fail_too_many_arguments; 6583 return; 6584 } 6585 6586 // Function types don't have any default arguments, so just check if 6587 // we have enough arguments. 6588 if (Args.size() < NumParams) { 6589 // Not enough arguments. 6590 Candidate.Viable = false; 6591 Candidate.FailureKind = ovl_fail_too_few_arguments; 6592 return; 6593 } 6594 6595 // Determine the implicit conversion sequences for each of the 6596 // arguments. 6597 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6598 if (ArgIdx < NumParams) { 6599 // (C++ 13.3.2p3): for F to be a viable function, there shall 6600 // exist for each argument an implicit conversion sequence 6601 // (13.3.3.1) that converts that argument to the corresponding 6602 // parameter of F. 6603 QualType ParamType = Proto->getParamType(ArgIdx); 6604 Candidate.Conversions[ArgIdx + 1] 6605 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6606 /*SuppressUserConversions=*/false, 6607 /*InOverloadResolution=*/false, 6608 /*AllowObjCWritebackConversion=*/ 6609 getLangOpts().ObjCAutoRefCount); 6610 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6611 Candidate.Viable = false; 6612 Candidate.FailureKind = ovl_fail_bad_conversion; 6613 return; 6614 } 6615 } else { 6616 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6617 // argument for which there is no corresponding parameter is 6618 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6619 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6620 } 6621 } 6622 6623 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6624 Candidate.Viable = false; 6625 Candidate.FailureKind = ovl_fail_enable_if; 6626 Candidate.DeductionFailure.Data = FailedAttr; 6627 return; 6628 } 6629 } 6630 6631 /// \brief Add overload candidates for overloaded operators that are 6632 /// member functions. 6633 /// 6634 /// Add the overloaded operator candidates that are member functions 6635 /// for the operator Op that was used in an operator expression such 6636 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6637 /// CandidateSet will store the added overload candidates. (C++ 6638 /// [over.match.oper]). 6639 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6640 SourceLocation OpLoc, 6641 ArrayRef<Expr *> Args, 6642 OverloadCandidateSet& CandidateSet, 6643 SourceRange OpRange) { 6644 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6645 6646 // C++ [over.match.oper]p3: 6647 // For a unary operator @ with an operand of a type whose 6648 // cv-unqualified version is T1, and for a binary operator @ with 6649 // a left operand of a type whose cv-unqualified version is T1 and 6650 // a right operand of a type whose cv-unqualified version is T2, 6651 // three sets of candidate functions, designated member 6652 // candidates, non-member candidates and built-in candidates, are 6653 // constructed as follows: 6654 QualType T1 = Args[0]->getType(); 6655 6656 // -- If T1 is a complete class type or a class currently being 6657 // defined, the set of member candidates is the result of the 6658 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6659 // the set of member candidates is empty. 6660 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6661 // Complete the type if it can be completed. 6662 RequireCompleteType(OpLoc, T1, 0); 6663 // If the type is neither complete nor being defined, bail out now. 6664 if (!T1Rec->getDecl()->getDefinition()) 6665 return; 6666 6667 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6668 LookupQualifiedName(Operators, T1Rec->getDecl()); 6669 Operators.suppressDiagnostics(); 6670 6671 for (LookupResult::iterator Oper = Operators.begin(), 6672 OperEnd = Operators.end(); 6673 Oper != OperEnd; 6674 ++Oper) 6675 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6676 Args[0]->Classify(Context), 6677 Args.slice(1), 6678 CandidateSet, 6679 /* SuppressUserConversions = */ false); 6680 } 6681 } 6682 6683 /// AddBuiltinCandidate - Add a candidate for a built-in 6684 /// operator. ResultTy and ParamTys are the result and parameter types 6685 /// of the built-in candidate, respectively. Args and NumArgs are the 6686 /// arguments being passed to the candidate. IsAssignmentOperator 6687 /// should be true when this built-in candidate is an assignment 6688 /// operator. NumContextualBoolArguments is the number of arguments 6689 /// (at the beginning of the argument list) that will be contextually 6690 /// converted to bool. 6691 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6692 ArrayRef<Expr *> Args, 6693 OverloadCandidateSet& CandidateSet, 6694 bool IsAssignmentOperator, 6695 unsigned NumContextualBoolArguments) { 6696 // Overload resolution is always an unevaluated context. 6697 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6698 6699 // Add this candidate 6700 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6701 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6702 Candidate.Function = nullptr; 6703 Candidate.IsSurrogate = false; 6704 Candidate.IgnoreObjectArgument = false; 6705 Candidate.BuiltinTypes.ResultTy = ResultTy; 6706 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6707 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6708 6709 // Determine the implicit conversion sequences for each of the 6710 // arguments. 6711 Candidate.Viable = true; 6712 Candidate.ExplicitCallArguments = Args.size(); 6713 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6714 // C++ [over.match.oper]p4: 6715 // For the built-in assignment operators, conversions of the 6716 // left operand are restricted as follows: 6717 // -- no temporaries are introduced to hold the left operand, and 6718 // -- no user-defined conversions are applied to the left 6719 // operand to achieve a type match with the left-most 6720 // parameter of a built-in candidate. 6721 // 6722 // We block these conversions by turning off user-defined 6723 // conversions, since that is the only way that initialization of 6724 // a reference to a non-class type can occur from something that 6725 // is not of the same type. 6726 if (ArgIdx < NumContextualBoolArguments) { 6727 assert(ParamTys[ArgIdx] == Context.BoolTy && 6728 "Contextual conversion to bool requires bool type"); 6729 Candidate.Conversions[ArgIdx] 6730 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6731 } else { 6732 Candidate.Conversions[ArgIdx] 6733 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6734 ArgIdx == 0 && IsAssignmentOperator, 6735 /*InOverloadResolution=*/false, 6736 /*AllowObjCWritebackConversion=*/ 6737 getLangOpts().ObjCAutoRefCount); 6738 } 6739 if (Candidate.Conversions[ArgIdx].isBad()) { 6740 Candidate.Viable = false; 6741 Candidate.FailureKind = ovl_fail_bad_conversion; 6742 break; 6743 } 6744 } 6745 } 6746 6747 namespace { 6748 6749 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6750 /// candidate operator functions for built-in operators (C++ 6751 /// [over.built]). The types are separated into pointer types and 6752 /// enumeration types. 6753 class BuiltinCandidateTypeSet { 6754 /// TypeSet - A set of types. 6755 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6756 6757 /// PointerTypes - The set of pointer types that will be used in the 6758 /// built-in candidates. 6759 TypeSet PointerTypes; 6760 6761 /// MemberPointerTypes - The set of member pointer types that will be 6762 /// used in the built-in candidates. 6763 TypeSet MemberPointerTypes; 6764 6765 /// EnumerationTypes - The set of enumeration types that will be 6766 /// used in the built-in candidates. 6767 TypeSet EnumerationTypes; 6768 6769 /// \brief The set of vector types that will be used in the built-in 6770 /// candidates. 6771 TypeSet VectorTypes; 6772 6773 /// \brief A flag indicating non-record types are viable candidates 6774 bool HasNonRecordTypes; 6775 6776 /// \brief A flag indicating whether either arithmetic or enumeration types 6777 /// were present in the candidate set. 6778 bool HasArithmeticOrEnumeralTypes; 6779 6780 /// \brief A flag indicating whether the nullptr type was present in the 6781 /// candidate set. 6782 bool HasNullPtrType; 6783 6784 /// Sema - The semantic analysis instance where we are building the 6785 /// candidate type set. 6786 Sema &SemaRef; 6787 6788 /// Context - The AST context in which we will build the type sets. 6789 ASTContext &Context; 6790 6791 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6792 const Qualifiers &VisibleQuals); 6793 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6794 6795 public: 6796 /// iterator - Iterates through the types that are part of the set. 6797 typedef TypeSet::iterator iterator; 6798 6799 BuiltinCandidateTypeSet(Sema &SemaRef) 6800 : HasNonRecordTypes(false), 6801 HasArithmeticOrEnumeralTypes(false), 6802 HasNullPtrType(false), 6803 SemaRef(SemaRef), 6804 Context(SemaRef.Context) { } 6805 6806 void AddTypesConvertedFrom(QualType Ty, 6807 SourceLocation Loc, 6808 bool AllowUserConversions, 6809 bool AllowExplicitConversions, 6810 const Qualifiers &VisibleTypeConversionsQuals); 6811 6812 /// pointer_begin - First pointer type found; 6813 iterator pointer_begin() { return PointerTypes.begin(); } 6814 6815 /// pointer_end - Past the last pointer type found; 6816 iterator pointer_end() { return PointerTypes.end(); } 6817 6818 /// member_pointer_begin - First member pointer type found; 6819 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6820 6821 /// member_pointer_end - Past the last member pointer type found; 6822 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6823 6824 /// enumeration_begin - First enumeration type found; 6825 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6826 6827 /// enumeration_end - Past the last enumeration type found; 6828 iterator enumeration_end() { return EnumerationTypes.end(); } 6829 6830 iterator vector_begin() { return VectorTypes.begin(); } 6831 iterator vector_end() { return VectorTypes.end(); } 6832 6833 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6834 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6835 bool hasNullPtrType() const { return HasNullPtrType; } 6836 }; 6837 6838 } // end anonymous namespace 6839 6840 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6841 /// the set of pointer types along with any more-qualified variants of 6842 /// that type. For example, if @p Ty is "int const *", this routine 6843 /// will add "int const *", "int const volatile *", "int const 6844 /// restrict *", and "int const volatile restrict *" to the set of 6845 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6846 /// false otherwise. 6847 /// 6848 /// FIXME: what to do about extended qualifiers? 6849 bool 6850 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6851 const Qualifiers &VisibleQuals) { 6852 6853 // Insert this type. 6854 if (!PointerTypes.insert(Ty).second) 6855 return false; 6856 6857 QualType PointeeTy; 6858 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6859 bool buildObjCPtr = false; 6860 if (!PointerTy) { 6861 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6862 PointeeTy = PTy->getPointeeType(); 6863 buildObjCPtr = true; 6864 } else { 6865 PointeeTy = PointerTy->getPointeeType(); 6866 } 6867 6868 // Don't add qualified variants of arrays. For one, they're not allowed 6869 // (the qualifier would sink to the element type), and for another, the 6870 // only overload situation where it matters is subscript or pointer +- int, 6871 // and those shouldn't have qualifier variants anyway. 6872 if (PointeeTy->isArrayType()) 6873 return true; 6874 6875 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6876 bool hasVolatile = VisibleQuals.hasVolatile(); 6877 bool hasRestrict = VisibleQuals.hasRestrict(); 6878 6879 // Iterate through all strict supersets of BaseCVR. 6880 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6881 if ((CVR | BaseCVR) != CVR) continue; 6882 // Skip over volatile if no volatile found anywhere in the types. 6883 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6884 6885 // Skip over restrict if no restrict found anywhere in the types, or if 6886 // the type cannot be restrict-qualified. 6887 if ((CVR & Qualifiers::Restrict) && 6888 (!hasRestrict || 6889 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6890 continue; 6891 6892 // Build qualified pointee type. 6893 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6894 6895 // Build qualified pointer type. 6896 QualType QPointerTy; 6897 if (!buildObjCPtr) 6898 QPointerTy = Context.getPointerType(QPointeeTy); 6899 else 6900 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6901 6902 // Insert qualified pointer type. 6903 PointerTypes.insert(QPointerTy); 6904 } 6905 6906 return true; 6907 } 6908 6909 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6910 /// to the set of pointer types along with any more-qualified variants of 6911 /// that type. For example, if @p Ty is "int const *", this routine 6912 /// will add "int const *", "int const volatile *", "int const 6913 /// restrict *", and "int const volatile restrict *" to the set of 6914 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6915 /// false otherwise. 6916 /// 6917 /// FIXME: what to do about extended qualifiers? 6918 bool 6919 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6920 QualType Ty) { 6921 // Insert this type. 6922 if (!MemberPointerTypes.insert(Ty).second) 6923 return false; 6924 6925 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6926 assert(PointerTy && "type was not a member pointer type!"); 6927 6928 QualType PointeeTy = PointerTy->getPointeeType(); 6929 // Don't add qualified variants of arrays. For one, they're not allowed 6930 // (the qualifier would sink to the element type), and for another, the 6931 // only overload situation where it matters is subscript or pointer +- int, 6932 // and those shouldn't have qualifier variants anyway. 6933 if (PointeeTy->isArrayType()) 6934 return true; 6935 const Type *ClassTy = PointerTy->getClass(); 6936 6937 // Iterate through all strict supersets of the pointee type's CVR 6938 // qualifiers. 6939 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6940 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6941 if ((CVR | BaseCVR) != CVR) continue; 6942 6943 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6944 MemberPointerTypes.insert( 6945 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6946 } 6947 6948 return true; 6949 } 6950 6951 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6952 /// Ty can be implicit converted to the given set of @p Types. We're 6953 /// primarily interested in pointer types and enumeration types. We also 6954 /// take member pointer types, for the conditional operator. 6955 /// AllowUserConversions is true if we should look at the conversion 6956 /// functions of a class type, and AllowExplicitConversions if we 6957 /// should also include the explicit conversion functions of a class 6958 /// type. 6959 void 6960 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6961 SourceLocation Loc, 6962 bool AllowUserConversions, 6963 bool AllowExplicitConversions, 6964 const Qualifiers &VisibleQuals) { 6965 // Only deal with canonical types. 6966 Ty = Context.getCanonicalType(Ty); 6967 6968 // Look through reference types; they aren't part of the type of an 6969 // expression for the purposes of conversions. 6970 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6971 Ty = RefTy->getPointeeType(); 6972 6973 // If we're dealing with an array type, decay to the pointer. 6974 if (Ty->isArrayType()) 6975 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6976 6977 // Otherwise, we don't care about qualifiers on the type. 6978 Ty = Ty.getLocalUnqualifiedType(); 6979 6980 // Flag if we ever add a non-record type. 6981 const RecordType *TyRec = Ty->getAs<RecordType>(); 6982 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6983 6984 // Flag if we encounter an arithmetic type. 6985 HasArithmeticOrEnumeralTypes = 6986 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6987 6988 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6989 PointerTypes.insert(Ty); 6990 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6991 // Insert our type, and its more-qualified variants, into the set 6992 // of types. 6993 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6994 return; 6995 } else if (Ty->isMemberPointerType()) { 6996 // Member pointers are far easier, since the pointee can't be converted. 6997 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6998 return; 6999 } else if (Ty->isEnumeralType()) { 7000 HasArithmeticOrEnumeralTypes = true; 7001 EnumerationTypes.insert(Ty); 7002 } else if (Ty->isVectorType()) { 7003 // We treat vector types as arithmetic types in many contexts as an 7004 // extension. 7005 HasArithmeticOrEnumeralTypes = true; 7006 VectorTypes.insert(Ty); 7007 } else if (Ty->isNullPtrType()) { 7008 HasNullPtrType = true; 7009 } else if (AllowUserConversions && TyRec) { 7010 // No conversion functions in incomplete types. 7011 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 7012 return; 7013 7014 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7015 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7016 if (isa<UsingShadowDecl>(D)) 7017 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7018 7019 // Skip conversion function templates; they don't tell us anything 7020 // about which builtin types we can convert to. 7021 if (isa<FunctionTemplateDecl>(D)) 7022 continue; 7023 7024 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7025 if (AllowExplicitConversions || !Conv->isExplicit()) { 7026 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7027 VisibleQuals); 7028 } 7029 } 7030 } 7031 } 7032 7033 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7034 /// the volatile- and non-volatile-qualified assignment operators for the 7035 /// given type to the candidate set. 7036 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7037 QualType T, 7038 ArrayRef<Expr *> Args, 7039 OverloadCandidateSet &CandidateSet) { 7040 QualType ParamTypes[2]; 7041 7042 // T& operator=(T&, T) 7043 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7044 ParamTypes[1] = T; 7045 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7046 /*IsAssignmentOperator=*/true); 7047 7048 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7049 // volatile T& operator=(volatile T&, T) 7050 ParamTypes[0] 7051 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7052 ParamTypes[1] = T; 7053 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7054 /*IsAssignmentOperator=*/true); 7055 } 7056 } 7057 7058 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7059 /// if any, found in visible type conversion functions found in ArgExpr's type. 7060 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7061 Qualifiers VRQuals; 7062 const RecordType *TyRec; 7063 if (const MemberPointerType *RHSMPType = 7064 ArgExpr->getType()->getAs<MemberPointerType>()) 7065 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7066 else 7067 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7068 if (!TyRec) { 7069 // Just to be safe, assume the worst case. 7070 VRQuals.addVolatile(); 7071 VRQuals.addRestrict(); 7072 return VRQuals; 7073 } 7074 7075 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7076 if (!ClassDecl->hasDefinition()) 7077 return VRQuals; 7078 7079 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7080 if (isa<UsingShadowDecl>(D)) 7081 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7082 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7083 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7084 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7085 CanTy = ResTypeRef->getPointeeType(); 7086 // Need to go down the pointer/mempointer chain and add qualifiers 7087 // as see them. 7088 bool done = false; 7089 while (!done) { 7090 if (CanTy.isRestrictQualified()) 7091 VRQuals.addRestrict(); 7092 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7093 CanTy = ResTypePtr->getPointeeType(); 7094 else if (const MemberPointerType *ResTypeMPtr = 7095 CanTy->getAs<MemberPointerType>()) 7096 CanTy = ResTypeMPtr->getPointeeType(); 7097 else 7098 done = true; 7099 if (CanTy.isVolatileQualified()) 7100 VRQuals.addVolatile(); 7101 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7102 return VRQuals; 7103 } 7104 } 7105 } 7106 return VRQuals; 7107 } 7108 7109 namespace { 7110 7111 /// \brief Helper class to manage the addition of builtin operator overload 7112 /// candidates. It provides shared state and utility methods used throughout 7113 /// the process, as well as a helper method to add each group of builtin 7114 /// operator overloads from the standard to a candidate set. 7115 class BuiltinOperatorOverloadBuilder { 7116 // Common instance state available to all overload candidate addition methods. 7117 Sema &S; 7118 ArrayRef<Expr *> Args; 7119 Qualifiers VisibleTypeConversionsQuals; 7120 bool HasArithmeticOrEnumeralCandidateType; 7121 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7122 OverloadCandidateSet &CandidateSet; 7123 7124 // Define some constants used to index and iterate over the arithemetic types 7125 // provided via the getArithmeticType() method below. 7126 // The "promoted arithmetic types" are the arithmetic 7127 // types are that preserved by promotion (C++ [over.built]p2). 7128 static const unsigned FirstIntegralType = 3; 7129 static const unsigned LastIntegralType = 20; 7130 static const unsigned FirstPromotedIntegralType = 3, 7131 LastPromotedIntegralType = 11; 7132 static const unsigned FirstPromotedArithmeticType = 0, 7133 LastPromotedArithmeticType = 11; 7134 static const unsigned NumArithmeticTypes = 20; 7135 7136 /// \brief Get the canonical type for a given arithmetic type index. 7137 CanQualType getArithmeticType(unsigned index) { 7138 assert(index < NumArithmeticTypes); 7139 static CanQualType ASTContext::* const 7140 ArithmeticTypes[NumArithmeticTypes] = { 7141 // Start of promoted types. 7142 &ASTContext::FloatTy, 7143 &ASTContext::DoubleTy, 7144 &ASTContext::LongDoubleTy, 7145 7146 // Start of integral types. 7147 &ASTContext::IntTy, 7148 &ASTContext::LongTy, 7149 &ASTContext::LongLongTy, 7150 &ASTContext::Int128Ty, 7151 &ASTContext::UnsignedIntTy, 7152 &ASTContext::UnsignedLongTy, 7153 &ASTContext::UnsignedLongLongTy, 7154 &ASTContext::UnsignedInt128Ty, 7155 // End of promoted types. 7156 7157 &ASTContext::BoolTy, 7158 &ASTContext::CharTy, 7159 &ASTContext::WCharTy, 7160 &ASTContext::Char16Ty, 7161 &ASTContext::Char32Ty, 7162 &ASTContext::SignedCharTy, 7163 &ASTContext::ShortTy, 7164 &ASTContext::UnsignedCharTy, 7165 &ASTContext::UnsignedShortTy, 7166 // End of integral types. 7167 // FIXME: What about complex? What about half? 7168 }; 7169 return S.Context.*ArithmeticTypes[index]; 7170 } 7171 7172 /// \brief Gets the canonical type resulting from the usual arithemetic 7173 /// converions for the given arithmetic types. 7174 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7175 // Accelerator table for performing the usual arithmetic conversions. 7176 // The rules are basically: 7177 // - if either is floating-point, use the wider floating-point 7178 // - if same signedness, use the higher rank 7179 // - if same size, use unsigned of the higher rank 7180 // - use the larger type 7181 // These rules, together with the axiom that higher ranks are 7182 // never smaller, are sufficient to precompute all of these results 7183 // *except* when dealing with signed types of higher rank. 7184 // (we could precompute SLL x UI for all known platforms, but it's 7185 // better not to make any assumptions). 7186 // We assume that int128 has a higher rank than long long on all platforms. 7187 enum PromotedType { 7188 Dep=-1, 7189 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7190 }; 7191 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7192 [LastPromotedArithmeticType] = { 7193 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7194 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7195 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7196 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7197 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7198 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7199 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7200 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7201 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7202 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7203 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7204 }; 7205 7206 assert(L < LastPromotedArithmeticType); 7207 assert(R < LastPromotedArithmeticType); 7208 int Idx = ConversionsTable[L][R]; 7209 7210 // Fast path: the table gives us a concrete answer. 7211 if (Idx != Dep) return getArithmeticType(Idx); 7212 7213 // Slow path: we need to compare widths. 7214 // An invariant is that the signed type has higher rank. 7215 CanQualType LT = getArithmeticType(L), 7216 RT = getArithmeticType(R); 7217 unsigned LW = S.Context.getIntWidth(LT), 7218 RW = S.Context.getIntWidth(RT); 7219 7220 // If they're different widths, use the signed type. 7221 if (LW > RW) return LT; 7222 else if (LW < RW) return RT; 7223 7224 // Otherwise, use the unsigned type of the signed type's rank. 7225 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7226 assert(L == SLL || R == SLL); 7227 return S.Context.UnsignedLongLongTy; 7228 } 7229 7230 /// \brief Helper method to factor out the common pattern of adding overloads 7231 /// for '++' and '--' builtin operators. 7232 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7233 bool HasVolatile, 7234 bool HasRestrict) { 7235 QualType ParamTypes[2] = { 7236 S.Context.getLValueReferenceType(CandidateTy), 7237 S.Context.IntTy 7238 }; 7239 7240 // Non-volatile version. 7241 if (Args.size() == 1) 7242 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7243 else 7244 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7245 7246 // Use a heuristic to reduce number of builtin candidates in the set: 7247 // add volatile version only if there are conversions to a volatile type. 7248 if (HasVolatile) { 7249 ParamTypes[0] = 7250 S.Context.getLValueReferenceType( 7251 S.Context.getVolatileType(CandidateTy)); 7252 if (Args.size() == 1) 7253 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7254 else 7255 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7256 } 7257 7258 // Add restrict version only if there are conversions to a restrict type 7259 // and our candidate type is a non-restrict-qualified pointer. 7260 if (HasRestrict && CandidateTy->isAnyPointerType() && 7261 !CandidateTy.isRestrictQualified()) { 7262 ParamTypes[0] 7263 = S.Context.getLValueReferenceType( 7264 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7265 if (Args.size() == 1) 7266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7267 else 7268 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7269 7270 if (HasVolatile) { 7271 ParamTypes[0] 7272 = S.Context.getLValueReferenceType( 7273 S.Context.getCVRQualifiedType(CandidateTy, 7274 (Qualifiers::Volatile | 7275 Qualifiers::Restrict))); 7276 if (Args.size() == 1) 7277 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7278 else 7279 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7280 } 7281 } 7282 7283 } 7284 7285 public: 7286 BuiltinOperatorOverloadBuilder( 7287 Sema &S, ArrayRef<Expr *> Args, 7288 Qualifiers VisibleTypeConversionsQuals, 7289 bool HasArithmeticOrEnumeralCandidateType, 7290 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7291 OverloadCandidateSet &CandidateSet) 7292 : S(S), Args(Args), 7293 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7294 HasArithmeticOrEnumeralCandidateType( 7295 HasArithmeticOrEnumeralCandidateType), 7296 CandidateTypes(CandidateTypes), 7297 CandidateSet(CandidateSet) { 7298 // Validate some of our static helper constants in debug builds. 7299 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7300 "Invalid first promoted integral type"); 7301 assert(getArithmeticType(LastPromotedIntegralType - 1) 7302 == S.Context.UnsignedInt128Ty && 7303 "Invalid last promoted integral type"); 7304 assert(getArithmeticType(FirstPromotedArithmeticType) 7305 == S.Context.FloatTy && 7306 "Invalid first promoted arithmetic type"); 7307 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7308 == S.Context.UnsignedInt128Ty && 7309 "Invalid last promoted arithmetic type"); 7310 } 7311 7312 // C++ [over.built]p3: 7313 // 7314 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7315 // is either volatile or empty, there exist candidate operator 7316 // functions of the form 7317 // 7318 // VQ T& operator++(VQ T&); 7319 // T operator++(VQ T&, int); 7320 // 7321 // C++ [over.built]p4: 7322 // 7323 // For every pair (T, VQ), where T is an arithmetic type other 7324 // than bool, and VQ is either volatile or empty, there exist 7325 // candidate operator functions of the form 7326 // 7327 // VQ T& operator--(VQ T&); 7328 // T operator--(VQ T&, int); 7329 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7330 if (!HasArithmeticOrEnumeralCandidateType) 7331 return; 7332 7333 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7334 Arith < NumArithmeticTypes; ++Arith) { 7335 addPlusPlusMinusMinusStyleOverloads( 7336 getArithmeticType(Arith), 7337 VisibleTypeConversionsQuals.hasVolatile(), 7338 VisibleTypeConversionsQuals.hasRestrict()); 7339 } 7340 } 7341 7342 // C++ [over.built]p5: 7343 // 7344 // For every pair (T, VQ), where T is a cv-qualified or 7345 // cv-unqualified object type, and VQ is either volatile or 7346 // empty, there exist candidate operator functions of the form 7347 // 7348 // T*VQ& operator++(T*VQ&); 7349 // T*VQ& operator--(T*VQ&); 7350 // T* operator++(T*VQ&, int); 7351 // T* operator--(T*VQ&, int); 7352 void addPlusPlusMinusMinusPointerOverloads() { 7353 for (BuiltinCandidateTypeSet::iterator 7354 Ptr = CandidateTypes[0].pointer_begin(), 7355 PtrEnd = CandidateTypes[0].pointer_end(); 7356 Ptr != PtrEnd; ++Ptr) { 7357 // Skip pointer types that aren't pointers to object types. 7358 if (!(*Ptr)->getPointeeType()->isObjectType()) 7359 continue; 7360 7361 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7362 (!(*Ptr).isVolatileQualified() && 7363 VisibleTypeConversionsQuals.hasVolatile()), 7364 (!(*Ptr).isRestrictQualified() && 7365 VisibleTypeConversionsQuals.hasRestrict())); 7366 } 7367 } 7368 7369 // C++ [over.built]p6: 7370 // For every cv-qualified or cv-unqualified object type T, there 7371 // exist candidate operator functions of the form 7372 // 7373 // T& operator*(T*); 7374 // 7375 // C++ [over.built]p7: 7376 // For every function type T that does not have cv-qualifiers or a 7377 // ref-qualifier, there exist candidate operator functions of the form 7378 // T& operator*(T*); 7379 void addUnaryStarPointerOverloads() { 7380 for (BuiltinCandidateTypeSet::iterator 7381 Ptr = CandidateTypes[0].pointer_begin(), 7382 PtrEnd = CandidateTypes[0].pointer_end(); 7383 Ptr != PtrEnd; ++Ptr) { 7384 QualType ParamTy = *Ptr; 7385 QualType PointeeTy = ParamTy->getPointeeType(); 7386 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7387 continue; 7388 7389 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7390 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7391 continue; 7392 7393 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7394 &ParamTy, Args, CandidateSet); 7395 } 7396 } 7397 7398 // C++ [over.built]p9: 7399 // For every promoted arithmetic type T, there exist candidate 7400 // operator functions of the form 7401 // 7402 // T operator+(T); 7403 // T operator-(T); 7404 void addUnaryPlusOrMinusArithmeticOverloads() { 7405 if (!HasArithmeticOrEnumeralCandidateType) 7406 return; 7407 7408 for (unsigned Arith = FirstPromotedArithmeticType; 7409 Arith < LastPromotedArithmeticType; ++Arith) { 7410 QualType ArithTy = getArithmeticType(Arith); 7411 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7412 } 7413 7414 // Extension: We also add these operators for vector types. 7415 for (BuiltinCandidateTypeSet::iterator 7416 Vec = CandidateTypes[0].vector_begin(), 7417 VecEnd = CandidateTypes[0].vector_end(); 7418 Vec != VecEnd; ++Vec) { 7419 QualType VecTy = *Vec; 7420 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7421 } 7422 } 7423 7424 // C++ [over.built]p8: 7425 // For every type T, there exist candidate operator functions of 7426 // the form 7427 // 7428 // T* operator+(T*); 7429 void addUnaryPlusPointerOverloads() { 7430 for (BuiltinCandidateTypeSet::iterator 7431 Ptr = CandidateTypes[0].pointer_begin(), 7432 PtrEnd = CandidateTypes[0].pointer_end(); 7433 Ptr != PtrEnd; ++Ptr) { 7434 QualType ParamTy = *Ptr; 7435 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7436 } 7437 } 7438 7439 // C++ [over.built]p10: 7440 // For every promoted integral type T, there exist candidate 7441 // operator functions of the form 7442 // 7443 // T operator~(T); 7444 void addUnaryTildePromotedIntegralOverloads() { 7445 if (!HasArithmeticOrEnumeralCandidateType) 7446 return; 7447 7448 for (unsigned Int = FirstPromotedIntegralType; 7449 Int < LastPromotedIntegralType; ++Int) { 7450 QualType IntTy = getArithmeticType(Int); 7451 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7452 } 7453 7454 // Extension: We also add this operator for vector types. 7455 for (BuiltinCandidateTypeSet::iterator 7456 Vec = CandidateTypes[0].vector_begin(), 7457 VecEnd = CandidateTypes[0].vector_end(); 7458 Vec != VecEnd; ++Vec) { 7459 QualType VecTy = *Vec; 7460 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7461 } 7462 } 7463 7464 // C++ [over.match.oper]p16: 7465 // For every pointer to member type T, there exist candidate operator 7466 // functions of the form 7467 // 7468 // bool operator==(T,T); 7469 // bool operator!=(T,T); 7470 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7471 /// Set of (canonical) types that we've already handled. 7472 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7473 7474 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7475 for (BuiltinCandidateTypeSet::iterator 7476 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7477 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7478 MemPtr != MemPtrEnd; 7479 ++MemPtr) { 7480 // Don't add the same builtin candidate twice. 7481 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7482 continue; 7483 7484 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7485 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7486 } 7487 } 7488 } 7489 7490 // C++ [over.built]p15: 7491 // 7492 // For every T, where T is an enumeration type, a pointer type, or 7493 // std::nullptr_t, there exist candidate operator functions of the form 7494 // 7495 // bool operator<(T, T); 7496 // bool operator>(T, T); 7497 // bool operator<=(T, T); 7498 // bool operator>=(T, T); 7499 // bool operator==(T, T); 7500 // bool operator!=(T, T); 7501 void addRelationalPointerOrEnumeralOverloads() { 7502 // C++ [over.match.oper]p3: 7503 // [...]the built-in candidates include all of the candidate operator 7504 // functions defined in 13.6 that, compared to the given operator, [...] 7505 // do not have the same parameter-type-list as any non-template non-member 7506 // candidate. 7507 // 7508 // Note that in practice, this only affects enumeration types because there 7509 // aren't any built-in candidates of record type, and a user-defined operator 7510 // must have an operand of record or enumeration type. Also, the only other 7511 // overloaded operator with enumeration arguments, operator=, 7512 // cannot be overloaded for enumeration types, so this is the only place 7513 // where we must suppress candidates like this. 7514 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7515 UserDefinedBinaryOperators; 7516 7517 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7518 if (CandidateTypes[ArgIdx].enumeration_begin() != 7519 CandidateTypes[ArgIdx].enumeration_end()) { 7520 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7521 CEnd = CandidateSet.end(); 7522 C != CEnd; ++C) { 7523 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7524 continue; 7525 7526 if (C->Function->isFunctionTemplateSpecialization()) 7527 continue; 7528 7529 QualType FirstParamType = 7530 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7531 QualType SecondParamType = 7532 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7533 7534 // Skip if either parameter isn't of enumeral type. 7535 if (!FirstParamType->isEnumeralType() || 7536 !SecondParamType->isEnumeralType()) 7537 continue; 7538 7539 // Add this operator to the set of known user-defined operators. 7540 UserDefinedBinaryOperators.insert( 7541 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7542 S.Context.getCanonicalType(SecondParamType))); 7543 } 7544 } 7545 } 7546 7547 /// Set of (canonical) types that we've already handled. 7548 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7549 7550 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7551 for (BuiltinCandidateTypeSet::iterator 7552 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7553 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7554 Ptr != PtrEnd; ++Ptr) { 7555 // Don't add the same builtin candidate twice. 7556 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7557 continue; 7558 7559 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7560 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7561 } 7562 for (BuiltinCandidateTypeSet::iterator 7563 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7564 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7565 Enum != EnumEnd; ++Enum) { 7566 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7567 7568 // Don't add the same builtin candidate twice, or if a user defined 7569 // candidate exists. 7570 if (!AddedTypes.insert(CanonType).second || 7571 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7572 CanonType))) 7573 continue; 7574 7575 QualType ParamTypes[2] = { *Enum, *Enum }; 7576 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7577 } 7578 7579 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7580 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7581 if (AddedTypes.insert(NullPtrTy).second && 7582 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7583 NullPtrTy))) { 7584 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7585 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7586 CandidateSet); 7587 } 7588 } 7589 } 7590 } 7591 7592 // C++ [over.built]p13: 7593 // 7594 // For every cv-qualified or cv-unqualified object type T 7595 // there exist candidate operator functions of the form 7596 // 7597 // T* operator+(T*, ptrdiff_t); 7598 // T& operator[](T*, ptrdiff_t); [BELOW] 7599 // T* operator-(T*, ptrdiff_t); 7600 // T* operator+(ptrdiff_t, T*); 7601 // T& operator[](ptrdiff_t, T*); [BELOW] 7602 // 7603 // C++ [over.built]p14: 7604 // 7605 // For every T, where T is a pointer to object type, there 7606 // exist candidate operator functions of the form 7607 // 7608 // ptrdiff_t operator-(T, T); 7609 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7610 /// Set of (canonical) types that we've already handled. 7611 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7612 7613 for (int Arg = 0; Arg < 2; ++Arg) { 7614 QualType AsymmetricParamTypes[2] = { 7615 S.Context.getPointerDiffType(), 7616 S.Context.getPointerDiffType(), 7617 }; 7618 for (BuiltinCandidateTypeSet::iterator 7619 Ptr = CandidateTypes[Arg].pointer_begin(), 7620 PtrEnd = CandidateTypes[Arg].pointer_end(); 7621 Ptr != PtrEnd; ++Ptr) { 7622 QualType PointeeTy = (*Ptr)->getPointeeType(); 7623 if (!PointeeTy->isObjectType()) 7624 continue; 7625 7626 AsymmetricParamTypes[Arg] = *Ptr; 7627 if (Arg == 0 || Op == OO_Plus) { 7628 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7629 // T* operator+(ptrdiff_t, T*); 7630 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7631 } 7632 if (Op == OO_Minus) { 7633 // ptrdiff_t operator-(T, T); 7634 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7635 continue; 7636 7637 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7638 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7639 Args, CandidateSet); 7640 } 7641 } 7642 } 7643 } 7644 7645 // C++ [over.built]p12: 7646 // 7647 // For every pair of promoted arithmetic types L and R, there 7648 // exist candidate operator functions of the form 7649 // 7650 // LR operator*(L, R); 7651 // LR operator/(L, R); 7652 // LR operator+(L, R); 7653 // LR operator-(L, R); 7654 // bool operator<(L, R); 7655 // bool operator>(L, R); 7656 // bool operator<=(L, R); 7657 // bool operator>=(L, R); 7658 // bool operator==(L, R); 7659 // bool operator!=(L, R); 7660 // 7661 // where LR is the result of the usual arithmetic conversions 7662 // between types L and R. 7663 // 7664 // C++ [over.built]p24: 7665 // 7666 // For every pair of promoted arithmetic types L and R, there exist 7667 // candidate operator functions of the form 7668 // 7669 // LR operator?(bool, L, R); 7670 // 7671 // where LR is the result of the usual arithmetic conversions 7672 // between types L and R. 7673 // Our candidates ignore the first parameter. 7674 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7675 if (!HasArithmeticOrEnumeralCandidateType) 7676 return; 7677 7678 for (unsigned Left = FirstPromotedArithmeticType; 7679 Left < LastPromotedArithmeticType; ++Left) { 7680 for (unsigned Right = FirstPromotedArithmeticType; 7681 Right < LastPromotedArithmeticType; ++Right) { 7682 QualType LandR[2] = { getArithmeticType(Left), 7683 getArithmeticType(Right) }; 7684 QualType Result = 7685 isComparison ? S.Context.BoolTy 7686 : getUsualArithmeticConversions(Left, Right); 7687 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7688 } 7689 } 7690 7691 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7692 // conditional operator for vector types. 7693 for (BuiltinCandidateTypeSet::iterator 7694 Vec1 = CandidateTypes[0].vector_begin(), 7695 Vec1End = CandidateTypes[0].vector_end(); 7696 Vec1 != Vec1End; ++Vec1) { 7697 for (BuiltinCandidateTypeSet::iterator 7698 Vec2 = CandidateTypes[1].vector_begin(), 7699 Vec2End = CandidateTypes[1].vector_end(); 7700 Vec2 != Vec2End; ++Vec2) { 7701 QualType LandR[2] = { *Vec1, *Vec2 }; 7702 QualType Result = S.Context.BoolTy; 7703 if (!isComparison) { 7704 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7705 Result = *Vec1; 7706 else 7707 Result = *Vec2; 7708 } 7709 7710 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7711 } 7712 } 7713 } 7714 7715 // C++ [over.built]p17: 7716 // 7717 // For every pair of promoted integral types L and R, there 7718 // exist candidate operator functions of the form 7719 // 7720 // LR operator%(L, R); 7721 // LR operator&(L, R); 7722 // LR operator^(L, R); 7723 // LR operator|(L, R); 7724 // L operator<<(L, R); 7725 // L operator>>(L, R); 7726 // 7727 // where LR is the result of the usual arithmetic conversions 7728 // between types L and R. 7729 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7730 if (!HasArithmeticOrEnumeralCandidateType) 7731 return; 7732 7733 for (unsigned Left = FirstPromotedIntegralType; 7734 Left < LastPromotedIntegralType; ++Left) { 7735 for (unsigned Right = FirstPromotedIntegralType; 7736 Right < LastPromotedIntegralType; ++Right) { 7737 QualType LandR[2] = { getArithmeticType(Left), 7738 getArithmeticType(Right) }; 7739 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7740 ? LandR[0] 7741 : getUsualArithmeticConversions(Left, Right); 7742 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7743 } 7744 } 7745 } 7746 7747 // C++ [over.built]p20: 7748 // 7749 // For every pair (T, VQ), where T is an enumeration or 7750 // pointer to member type and VQ is either volatile or 7751 // empty, there exist candidate operator functions of the form 7752 // 7753 // VQ T& operator=(VQ T&, T); 7754 void addAssignmentMemberPointerOrEnumeralOverloads() { 7755 /// Set of (canonical) types that we've already handled. 7756 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7757 7758 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7759 for (BuiltinCandidateTypeSet::iterator 7760 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7761 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7762 Enum != EnumEnd; ++Enum) { 7763 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7764 continue; 7765 7766 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7767 } 7768 7769 for (BuiltinCandidateTypeSet::iterator 7770 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7771 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7772 MemPtr != MemPtrEnd; ++MemPtr) { 7773 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7774 continue; 7775 7776 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7777 } 7778 } 7779 } 7780 7781 // C++ [over.built]p19: 7782 // 7783 // For every pair (T, VQ), where T is any type and VQ is either 7784 // volatile or empty, there exist candidate operator functions 7785 // of the form 7786 // 7787 // T*VQ& operator=(T*VQ&, T*); 7788 // 7789 // C++ [over.built]p21: 7790 // 7791 // For every pair (T, VQ), where T is a cv-qualified or 7792 // cv-unqualified object type and VQ is either volatile or 7793 // empty, there exist candidate operator functions of the form 7794 // 7795 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7796 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7797 void addAssignmentPointerOverloads(bool isEqualOp) { 7798 /// Set of (canonical) types that we've already handled. 7799 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7800 7801 for (BuiltinCandidateTypeSet::iterator 7802 Ptr = CandidateTypes[0].pointer_begin(), 7803 PtrEnd = CandidateTypes[0].pointer_end(); 7804 Ptr != PtrEnd; ++Ptr) { 7805 // If this is operator=, keep track of the builtin candidates we added. 7806 if (isEqualOp) 7807 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7808 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7809 continue; 7810 7811 // non-volatile version 7812 QualType ParamTypes[2] = { 7813 S.Context.getLValueReferenceType(*Ptr), 7814 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7815 }; 7816 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7817 /*IsAssigmentOperator=*/ isEqualOp); 7818 7819 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7820 VisibleTypeConversionsQuals.hasVolatile(); 7821 if (NeedVolatile) { 7822 // volatile version 7823 ParamTypes[0] = 7824 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7825 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7826 /*IsAssigmentOperator=*/isEqualOp); 7827 } 7828 7829 if (!(*Ptr).isRestrictQualified() && 7830 VisibleTypeConversionsQuals.hasRestrict()) { 7831 // restrict version 7832 ParamTypes[0] 7833 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7834 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7835 /*IsAssigmentOperator=*/isEqualOp); 7836 7837 if (NeedVolatile) { 7838 // volatile restrict version 7839 ParamTypes[0] 7840 = S.Context.getLValueReferenceType( 7841 S.Context.getCVRQualifiedType(*Ptr, 7842 (Qualifiers::Volatile | 7843 Qualifiers::Restrict))); 7844 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7845 /*IsAssigmentOperator=*/isEqualOp); 7846 } 7847 } 7848 } 7849 7850 if (isEqualOp) { 7851 for (BuiltinCandidateTypeSet::iterator 7852 Ptr = CandidateTypes[1].pointer_begin(), 7853 PtrEnd = CandidateTypes[1].pointer_end(); 7854 Ptr != PtrEnd; ++Ptr) { 7855 // Make sure we don't add the same candidate twice. 7856 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7857 continue; 7858 7859 QualType ParamTypes[2] = { 7860 S.Context.getLValueReferenceType(*Ptr), 7861 *Ptr, 7862 }; 7863 7864 // non-volatile version 7865 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7866 /*IsAssigmentOperator=*/true); 7867 7868 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7869 VisibleTypeConversionsQuals.hasVolatile(); 7870 if (NeedVolatile) { 7871 // volatile version 7872 ParamTypes[0] = 7873 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7874 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7875 /*IsAssigmentOperator=*/true); 7876 } 7877 7878 if (!(*Ptr).isRestrictQualified() && 7879 VisibleTypeConversionsQuals.hasRestrict()) { 7880 // restrict version 7881 ParamTypes[0] 7882 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7883 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7884 /*IsAssigmentOperator=*/true); 7885 7886 if (NeedVolatile) { 7887 // volatile restrict version 7888 ParamTypes[0] 7889 = S.Context.getLValueReferenceType( 7890 S.Context.getCVRQualifiedType(*Ptr, 7891 (Qualifiers::Volatile | 7892 Qualifiers::Restrict))); 7893 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7894 /*IsAssigmentOperator=*/true); 7895 } 7896 } 7897 } 7898 } 7899 } 7900 7901 // C++ [over.built]p18: 7902 // 7903 // For every triple (L, VQ, R), where L is an arithmetic type, 7904 // VQ is either volatile or empty, and R is a promoted 7905 // arithmetic type, there exist candidate operator functions of 7906 // the form 7907 // 7908 // VQ L& operator=(VQ L&, R); 7909 // VQ L& operator*=(VQ L&, R); 7910 // VQ L& operator/=(VQ L&, R); 7911 // VQ L& operator+=(VQ L&, R); 7912 // VQ L& operator-=(VQ L&, R); 7913 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7914 if (!HasArithmeticOrEnumeralCandidateType) 7915 return; 7916 7917 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7918 for (unsigned Right = FirstPromotedArithmeticType; 7919 Right < LastPromotedArithmeticType; ++Right) { 7920 QualType ParamTypes[2]; 7921 ParamTypes[1] = getArithmeticType(Right); 7922 7923 // Add this built-in operator as a candidate (VQ is empty). 7924 ParamTypes[0] = 7925 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7926 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7927 /*IsAssigmentOperator=*/isEqualOp); 7928 7929 // Add this built-in operator as a candidate (VQ is 'volatile'). 7930 if (VisibleTypeConversionsQuals.hasVolatile()) { 7931 ParamTypes[0] = 7932 S.Context.getVolatileType(getArithmeticType(Left)); 7933 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7934 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7935 /*IsAssigmentOperator=*/isEqualOp); 7936 } 7937 } 7938 } 7939 7940 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7941 for (BuiltinCandidateTypeSet::iterator 7942 Vec1 = CandidateTypes[0].vector_begin(), 7943 Vec1End = CandidateTypes[0].vector_end(); 7944 Vec1 != Vec1End; ++Vec1) { 7945 for (BuiltinCandidateTypeSet::iterator 7946 Vec2 = CandidateTypes[1].vector_begin(), 7947 Vec2End = CandidateTypes[1].vector_end(); 7948 Vec2 != Vec2End; ++Vec2) { 7949 QualType ParamTypes[2]; 7950 ParamTypes[1] = *Vec2; 7951 // Add this built-in operator as a candidate (VQ is empty). 7952 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7953 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7954 /*IsAssigmentOperator=*/isEqualOp); 7955 7956 // Add this built-in operator as a candidate (VQ is 'volatile'). 7957 if (VisibleTypeConversionsQuals.hasVolatile()) { 7958 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7959 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7960 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7961 /*IsAssigmentOperator=*/isEqualOp); 7962 } 7963 } 7964 } 7965 } 7966 7967 // C++ [over.built]p22: 7968 // 7969 // For every triple (L, VQ, R), where L is an integral type, VQ 7970 // is either volatile or empty, and R is a promoted integral 7971 // type, there exist candidate operator functions of the form 7972 // 7973 // VQ L& operator%=(VQ L&, R); 7974 // VQ L& operator<<=(VQ L&, R); 7975 // VQ L& operator>>=(VQ L&, R); 7976 // VQ L& operator&=(VQ L&, R); 7977 // VQ L& operator^=(VQ L&, R); 7978 // VQ L& operator|=(VQ L&, R); 7979 void addAssignmentIntegralOverloads() { 7980 if (!HasArithmeticOrEnumeralCandidateType) 7981 return; 7982 7983 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7984 for (unsigned Right = FirstPromotedIntegralType; 7985 Right < LastPromotedIntegralType; ++Right) { 7986 QualType ParamTypes[2]; 7987 ParamTypes[1] = getArithmeticType(Right); 7988 7989 // Add this built-in operator as a candidate (VQ is empty). 7990 ParamTypes[0] = 7991 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7993 if (VisibleTypeConversionsQuals.hasVolatile()) { 7994 // Add this built-in operator as a candidate (VQ is 'volatile'). 7995 ParamTypes[0] = getArithmeticType(Left); 7996 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7997 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7998 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7999 } 8000 } 8001 } 8002 } 8003 8004 // C++ [over.operator]p23: 8005 // 8006 // There also exist candidate operator functions of the form 8007 // 8008 // bool operator!(bool); 8009 // bool operator&&(bool, bool); 8010 // bool operator||(bool, bool); 8011 void addExclaimOverload() { 8012 QualType ParamTy = S.Context.BoolTy; 8013 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8014 /*IsAssignmentOperator=*/false, 8015 /*NumContextualBoolArguments=*/1); 8016 } 8017 void addAmpAmpOrPipePipeOverload() { 8018 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8019 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8020 /*IsAssignmentOperator=*/false, 8021 /*NumContextualBoolArguments=*/2); 8022 } 8023 8024 // C++ [over.built]p13: 8025 // 8026 // For every cv-qualified or cv-unqualified object type T there 8027 // exist candidate operator functions of the form 8028 // 8029 // T* operator+(T*, ptrdiff_t); [ABOVE] 8030 // T& operator[](T*, ptrdiff_t); 8031 // T* operator-(T*, ptrdiff_t); [ABOVE] 8032 // T* operator+(ptrdiff_t, T*); [ABOVE] 8033 // T& operator[](ptrdiff_t, T*); 8034 void addSubscriptOverloads() { 8035 for (BuiltinCandidateTypeSet::iterator 8036 Ptr = CandidateTypes[0].pointer_begin(), 8037 PtrEnd = CandidateTypes[0].pointer_end(); 8038 Ptr != PtrEnd; ++Ptr) { 8039 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8040 QualType PointeeType = (*Ptr)->getPointeeType(); 8041 if (!PointeeType->isObjectType()) 8042 continue; 8043 8044 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8045 8046 // T& operator[](T*, ptrdiff_t) 8047 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8048 } 8049 8050 for (BuiltinCandidateTypeSet::iterator 8051 Ptr = CandidateTypes[1].pointer_begin(), 8052 PtrEnd = CandidateTypes[1].pointer_end(); 8053 Ptr != PtrEnd; ++Ptr) { 8054 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8055 QualType PointeeType = (*Ptr)->getPointeeType(); 8056 if (!PointeeType->isObjectType()) 8057 continue; 8058 8059 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8060 8061 // T& operator[](ptrdiff_t, T*) 8062 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8063 } 8064 } 8065 8066 // C++ [over.built]p11: 8067 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8068 // C1 is the same type as C2 or is a derived class of C2, T is an object 8069 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8070 // there exist candidate operator functions of the form 8071 // 8072 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8073 // 8074 // where CV12 is the union of CV1 and CV2. 8075 void addArrowStarOverloads() { 8076 for (BuiltinCandidateTypeSet::iterator 8077 Ptr = CandidateTypes[0].pointer_begin(), 8078 PtrEnd = CandidateTypes[0].pointer_end(); 8079 Ptr != PtrEnd; ++Ptr) { 8080 QualType C1Ty = (*Ptr); 8081 QualType C1; 8082 QualifierCollector Q1; 8083 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8084 if (!isa<RecordType>(C1)) 8085 continue; 8086 // heuristic to reduce number of builtin candidates in the set. 8087 // Add volatile/restrict version only if there are conversions to a 8088 // volatile/restrict type. 8089 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8090 continue; 8091 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8092 continue; 8093 for (BuiltinCandidateTypeSet::iterator 8094 MemPtr = CandidateTypes[1].member_pointer_begin(), 8095 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8096 MemPtr != MemPtrEnd; ++MemPtr) { 8097 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8098 QualType C2 = QualType(mptr->getClass(), 0); 8099 C2 = C2.getUnqualifiedType(); 8100 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 8101 break; 8102 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8103 // build CV12 T& 8104 QualType T = mptr->getPointeeType(); 8105 if (!VisibleTypeConversionsQuals.hasVolatile() && 8106 T.isVolatileQualified()) 8107 continue; 8108 if (!VisibleTypeConversionsQuals.hasRestrict() && 8109 T.isRestrictQualified()) 8110 continue; 8111 T = Q1.apply(S.Context, T); 8112 QualType ResultTy = S.Context.getLValueReferenceType(T); 8113 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8114 } 8115 } 8116 } 8117 8118 // Note that we don't consider the first argument, since it has been 8119 // contextually converted to bool long ago. The candidates below are 8120 // therefore added as binary. 8121 // 8122 // C++ [over.built]p25: 8123 // For every type T, where T is a pointer, pointer-to-member, or scoped 8124 // enumeration type, there exist candidate operator functions of the form 8125 // 8126 // T operator?(bool, T, T); 8127 // 8128 void addConditionalOperatorOverloads() { 8129 /// Set of (canonical) types that we've already handled. 8130 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8131 8132 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8133 for (BuiltinCandidateTypeSet::iterator 8134 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8135 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8136 Ptr != PtrEnd; ++Ptr) { 8137 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8138 continue; 8139 8140 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8141 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8142 } 8143 8144 for (BuiltinCandidateTypeSet::iterator 8145 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8146 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8147 MemPtr != MemPtrEnd; ++MemPtr) { 8148 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8149 continue; 8150 8151 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8152 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8153 } 8154 8155 if (S.getLangOpts().CPlusPlus11) { 8156 for (BuiltinCandidateTypeSet::iterator 8157 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8158 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8159 Enum != EnumEnd; ++Enum) { 8160 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8161 continue; 8162 8163 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8164 continue; 8165 8166 QualType ParamTypes[2] = { *Enum, *Enum }; 8167 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8168 } 8169 } 8170 } 8171 } 8172 }; 8173 8174 } // end anonymous namespace 8175 8176 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8177 /// operator overloads to the candidate set (C++ [over.built]), based 8178 /// on the operator @p Op and the arguments given. For example, if the 8179 /// operator is a binary '+', this routine might add "int 8180 /// operator+(int, int)" to cover integer addition. 8181 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8182 SourceLocation OpLoc, 8183 ArrayRef<Expr *> Args, 8184 OverloadCandidateSet &CandidateSet) { 8185 // Find all of the types that the arguments can convert to, but only 8186 // if the operator we're looking at has built-in operator candidates 8187 // that make use of these types. Also record whether we encounter non-record 8188 // candidate types or either arithmetic or enumeral candidate types. 8189 Qualifiers VisibleTypeConversionsQuals; 8190 VisibleTypeConversionsQuals.addConst(); 8191 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8192 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8193 8194 bool HasNonRecordCandidateType = false; 8195 bool HasArithmeticOrEnumeralCandidateType = false; 8196 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8197 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8198 CandidateTypes.emplace_back(*this); 8199 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8200 OpLoc, 8201 true, 8202 (Op == OO_Exclaim || 8203 Op == OO_AmpAmp || 8204 Op == OO_PipePipe), 8205 VisibleTypeConversionsQuals); 8206 HasNonRecordCandidateType = HasNonRecordCandidateType || 8207 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8208 HasArithmeticOrEnumeralCandidateType = 8209 HasArithmeticOrEnumeralCandidateType || 8210 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8211 } 8212 8213 // Exit early when no non-record types have been added to the candidate set 8214 // for any of the arguments to the operator. 8215 // 8216 // We can't exit early for !, ||, or &&, since there we have always have 8217 // 'bool' overloads. 8218 if (!HasNonRecordCandidateType && 8219 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8220 return; 8221 8222 // Setup an object to manage the common state for building overloads. 8223 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8224 VisibleTypeConversionsQuals, 8225 HasArithmeticOrEnumeralCandidateType, 8226 CandidateTypes, CandidateSet); 8227 8228 // Dispatch over the operation to add in only those overloads which apply. 8229 switch (Op) { 8230 case OO_None: 8231 case NUM_OVERLOADED_OPERATORS: 8232 llvm_unreachable("Expected an overloaded operator"); 8233 8234 case OO_New: 8235 case OO_Delete: 8236 case OO_Array_New: 8237 case OO_Array_Delete: 8238 case OO_Call: 8239 llvm_unreachable( 8240 "Special operators don't use AddBuiltinOperatorCandidates"); 8241 8242 case OO_Comma: 8243 case OO_Arrow: 8244 case OO_Coawait: 8245 // C++ [over.match.oper]p3: 8246 // -- For the operator ',', the unary operator '&', the 8247 // operator '->', or the operator 'co_await', the 8248 // built-in candidates set is empty. 8249 break; 8250 8251 case OO_Plus: // '+' is either unary or binary 8252 if (Args.size() == 1) 8253 OpBuilder.addUnaryPlusPointerOverloads(); 8254 // Fall through. 8255 8256 case OO_Minus: // '-' is either unary or binary 8257 if (Args.size() == 1) { 8258 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8259 } else { 8260 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8261 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8262 } 8263 break; 8264 8265 case OO_Star: // '*' is either unary or binary 8266 if (Args.size() == 1) 8267 OpBuilder.addUnaryStarPointerOverloads(); 8268 else 8269 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8270 break; 8271 8272 case OO_Slash: 8273 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8274 break; 8275 8276 case OO_PlusPlus: 8277 case OO_MinusMinus: 8278 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8279 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8280 break; 8281 8282 case OO_EqualEqual: 8283 case OO_ExclaimEqual: 8284 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8285 // Fall through. 8286 8287 case OO_Less: 8288 case OO_Greater: 8289 case OO_LessEqual: 8290 case OO_GreaterEqual: 8291 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8292 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8293 break; 8294 8295 case OO_Percent: 8296 case OO_Caret: 8297 case OO_Pipe: 8298 case OO_LessLess: 8299 case OO_GreaterGreater: 8300 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8301 break; 8302 8303 case OO_Amp: // '&' is either unary or binary 8304 if (Args.size() == 1) 8305 // C++ [over.match.oper]p3: 8306 // -- For the operator ',', the unary operator '&', or the 8307 // operator '->', the built-in candidates set is empty. 8308 break; 8309 8310 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8311 break; 8312 8313 case OO_Tilde: 8314 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8315 break; 8316 8317 case OO_Equal: 8318 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8319 // Fall through. 8320 8321 case OO_PlusEqual: 8322 case OO_MinusEqual: 8323 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8324 // Fall through. 8325 8326 case OO_StarEqual: 8327 case OO_SlashEqual: 8328 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8329 break; 8330 8331 case OO_PercentEqual: 8332 case OO_LessLessEqual: 8333 case OO_GreaterGreaterEqual: 8334 case OO_AmpEqual: 8335 case OO_CaretEqual: 8336 case OO_PipeEqual: 8337 OpBuilder.addAssignmentIntegralOverloads(); 8338 break; 8339 8340 case OO_Exclaim: 8341 OpBuilder.addExclaimOverload(); 8342 break; 8343 8344 case OO_AmpAmp: 8345 case OO_PipePipe: 8346 OpBuilder.addAmpAmpOrPipePipeOverload(); 8347 break; 8348 8349 case OO_Subscript: 8350 OpBuilder.addSubscriptOverloads(); 8351 break; 8352 8353 case OO_ArrowStar: 8354 OpBuilder.addArrowStarOverloads(); 8355 break; 8356 8357 case OO_Conditional: 8358 OpBuilder.addConditionalOperatorOverloads(); 8359 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8360 break; 8361 } 8362 } 8363 8364 /// \brief Add function candidates found via argument-dependent lookup 8365 /// to the set of overloading candidates. 8366 /// 8367 /// This routine performs argument-dependent name lookup based on the 8368 /// given function name (which may also be an operator name) and adds 8369 /// all of the overload candidates found by ADL to the overload 8370 /// candidate set (C++ [basic.lookup.argdep]). 8371 void 8372 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8373 SourceLocation Loc, 8374 ArrayRef<Expr *> Args, 8375 TemplateArgumentListInfo *ExplicitTemplateArgs, 8376 OverloadCandidateSet& CandidateSet, 8377 bool PartialOverloading) { 8378 ADLResult Fns; 8379 8380 // FIXME: This approach for uniquing ADL results (and removing 8381 // redundant candidates from the set) relies on pointer-equality, 8382 // which means we need to key off the canonical decl. However, 8383 // always going back to the canonical decl might not get us the 8384 // right set of default arguments. What default arguments are 8385 // we supposed to consider on ADL candidates, anyway? 8386 8387 // FIXME: Pass in the explicit template arguments? 8388 ArgumentDependentLookup(Name, Loc, Args, Fns); 8389 8390 // Erase all of the candidates we already knew about. 8391 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8392 CandEnd = CandidateSet.end(); 8393 Cand != CandEnd; ++Cand) 8394 if (Cand->Function) { 8395 Fns.erase(Cand->Function); 8396 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8397 Fns.erase(FunTmpl); 8398 } 8399 8400 // For each of the ADL candidates we found, add it to the overload 8401 // set. 8402 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8403 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8404 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8405 if (ExplicitTemplateArgs) 8406 continue; 8407 8408 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8409 PartialOverloading); 8410 } else 8411 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8412 FoundDecl, ExplicitTemplateArgs, 8413 Args, CandidateSet, PartialOverloading); 8414 } 8415 } 8416 8417 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8418 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8419 // on Cand1 and Cand2 have conditions that evaluate to true. 8420 // 8421 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8422 // Cand1's first N enable_if attributes have precisely the same conditions as 8423 // Cand2's first N enable_if attributes (where N = the number of enable_if 8424 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8425 static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1, 8426 const FunctionDecl *Cand2) { 8427 8428 // FIXME: The next several lines are just 8429 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8430 // instead of reverse order which is how they're stored in the AST. 8431 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8432 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8433 8434 // Candidate 1 is better if it has strictly more attributes and 8435 // the common sequence is identical. 8436 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8437 return false; 8438 8439 auto Cand1I = Cand1Attrs.begin(); 8440 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8441 for (auto &Cand2A : Cand2Attrs) { 8442 Cand1ID.clear(); 8443 Cand2ID.clear(); 8444 8445 auto &Cand1A = *Cand1I++; 8446 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8447 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8448 if (Cand1ID != Cand2ID) 8449 return false; 8450 } 8451 8452 return true; 8453 } 8454 8455 /// isBetterOverloadCandidate - Determines whether the first overload 8456 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8457 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8458 const OverloadCandidate &Cand2, 8459 SourceLocation Loc, 8460 bool UserDefinedConversion) { 8461 // Define viable functions to be better candidates than non-viable 8462 // functions. 8463 if (!Cand2.Viable) 8464 return Cand1.Viable; 8465 else if (!Cand1.Viable) 8466 return false; 8467 8468 // C++ [over.match.best]p1: 8469 // 8470 // -- if F is a static member function, ICS1(F) is defined such 8471 // that ICS1(F) is neither better nor worse than ICS1(G) for 8472 // any function G, and, symmetrically, ICS1(G) is neither 8473 // better nor worse than ICS1(F). 8474 unsigned StartArg = 0; 8475 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8476 StartArg = 1; 8477 8478 // C++ [over.match.best]p1: 8479 // A viable function F1 is defined to be a better function than another 8480 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8481 // conversion sequence than ICSi(F2), and then... 8482 unsigned NumArgs = Cand1.NumConversions; 8483 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8484 bool HasBetterConversion = false; 8485 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8486 switch (CompareImplicitConversionSequences(S, 8487 Cand1.Conversions[ArgIdx], 8488 Cand2.Conversions[ArgIdx])) { 8489 case ImplicitConversionSequence::Better: 8490 // Cand1 has a better conversion sequence. 8491 HasBetterConversion = true; 8492 break; 8493 8494 case ImplicitConversionSequence::Worse: 8495 // Cand1 can't be better than Cand2. 8496 return false; 8497 8498 case ImplicitConversionSequence::Indistinguishable: 8499 // Do nothing. 8500 break; 8501 } 8502 } 8503 8504 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8505 // ICSj(F2), or, if not that, 8506 if (HasBetterConversion) 8507 return true; 8508 8509 // -- the context is an initialization by user-defined conversion 8510 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8511 // from the return type of F1 to the destination type (i.e., 8512 // the type of the entity being initialized) is a better 8513 // conversion sequence than the standard conversion sequence 8514 // from the return type of F2 to the destination type. 8515 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8516 isa<CXXConversionDecl>(Cand1.Function) && 8517 isa<CXXConversionDecl>(Cand2.Function)) { 8518 // First check whether we prefer one of the conversion functions over the 8519 // other. This only distinguishes the results in non-standard, extension 8520 // cases such as the conversion from a lambda closure type to a function 8521 // pointer or block. 8522 ImplicitConversionSequence::CompareKind Result = 8523 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8524 if (Result == ImplicitConversionSequence::Indistinguishable) 8525 Result = CompareStandardConversionSequences(S, 8526 Cand1.FinalConversion, 8527 Cand2.FinalConversion); 8528 8529 if (Result != ImplicitConversionSequence::Indistinguishable) 8530 return Result == ImplicitConversionSequence::Better; 8531 8532 // FIXME: Compare kind of reference binding if conversion functions 8533 // convert to a reference type used in direct reference binding, per 8534 // C++14 [over.match.best]p1 section 2 bullet 3. 8535 } 8536 8537 // -- F1 is a non-template function and F2 is a function template 8538 // specialization, or, if not that, 8539 bool Cand1IsSpecialization = Cand1.Function && 8540 Cand1.Function->getPrimaryTemplate(); 8541 bool Cand2IsSpecialization = Cand2.Function && 8542 Cand2.Function->getPrimaryTemplate(); 8543 if (Cand1IsSpecialization != Cand2IsSpecialization) 8544 return Cand2IsSpecialization; 8545 8546 // -- F1 and F2 are function template specializations, and the function 8547 // template for F1 is more specialized than the template for F2 8548 // according to the partial ordering rules described in 14.5.5.2, or, 8549 // if not that, 8550 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8551 if (FunctionTemplateDecl *BetterTemplate 8552 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8553 Cand2.Function->getPrimaryTemplate(), 8554 Loc, 8555 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8556 : TPOC_Call, 8557 Cand1.ExplicitCallArguments, 8558 Cand2.ExplicitCallArguments)) 8559 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8560 } 8561 8562 // Check for enable_if value-based overload resolution. 8563 if (Cand1.Function && Cand2.Function && 8564 (Cand1.Function->hasAttr<EnableIfAttr>() || 8565 Cand2.Function->hasAttr<EnableIfAttr>())) 8566 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8567 8568 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 8569 Cand1.Function && Cand2.Function) { 8570 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8571 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8572 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8573 } 8574 8575 return false; 8576 } 8577 8578 /// Determine whether two declarations are "equivalent" for the purposes of 8579 /// name lookup and overload resolution. This applies when the same internal/no 8580 /// linkage entity is defined by two modules (probably by textually including 8581 /// the same header). In such a case, we don't consider the declarations to 8582 /// declare the same entity, but we also don't want lookups with both 8583 /// declarations visible to be ambiguous in some cases (this happens when using 8584 /// a modularized libstdc++). 8585 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8586 const NamedDecl *B) { 8587 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8588 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8589 if (!VA || !VB) 8590 return false; 8591 8592 // The declarations must be declaring the same name as an internal linkage 8593 // entity in different modules. 8594 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8595 VB->getDeclContext()->getRedeclContext()) || 8596 getOwningModule(const_cast<ValueDecl *>(VA)) == 8597 getOwningModule(const_cast<ValueDecl *>(VB)) || 8598 VA->isExternallyVisible() || VB->isExternallyVisible()) 8599 return false; 8600 8601 // Check that the declarations appear to be equivalent. 8602 // 8603 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8604 // For constants and functions, we should check the initializer or body is 8605 // the same. For non-constant variables, we shouldn't allow it at all. 8606 if (Context.hasSameType(VA->getType(), VB->getType())) 8607 return true; 8608 8609 // Enum constants within unnamed enumerations will have different types, but 8610 // may still be similar enough to be interchangeable for our purposes. 8611 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8612 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8613 // Only handle anonymous enums. If the enumerations were named and 8614 // equivalent, they would have been merged to the same type. 8615 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8616 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8617 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8618 !Context.hasSameType(EnumA->getIntegerType(), 8619 EnumB->getIntegerType())) 8620 return false; 8621 // Allow this only if the value is the same for both enumerators. 8622 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8623 } 8624 } 8625 8626 // Nothing else is sufficiently similar. 8627 return false; 8628 } 8629 8630 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8631 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8632 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8633 8634 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8635 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8636 << !M << (M ? M->getFullModuleName() : ""); 8637 8638 for (auto *E : Equiv) { 8639 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8640 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8641 << !M << (M ? M->getFullModuleName() : ""); 8642 } 8643 } 8644 8645 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8646 unsigned NumArgs); 8647 8648 /// \brief Computes the best viable function (C++ 13.3.3) 8649 /// within an overload candidate set. 8650 /// 8651 /// \param Loc The location of the function name (or operator symbol) for 8652 /// which overload resolution occurs. 8653 /// 8654 /// \param Best If overload resolution was successful or found a deleted 8655 /// function, \p Best points to the candidate function found. 8656 /// 8657 /// \returns The result of overload resolution. 8658 OverloadingResult 8659 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8660 iterator &Best, 8661 bool UserDefinedConversion) { 8662 // Find the best viable function. 8663 Best = end(); 8664 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8665 if (Cand->Viable) 8666 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8667 UserDefinedConversion)) 8668 Best = Cand; 8669 } 8670 8671 // If we didn't find any viable functions, abort. 8672 if (Best == end()) 8673 return OR_No_Viable_Function; 8674 8675 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8676 8677 // Make sure that this function is better than every other viable 8678 // function. If not, we have an ambiguity. 8679 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8680 if (Cand->Viable && 8681 Cand != Best && 8682 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8683 UserDefinedConversion)) { 8684 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8685 Cand->Function)) { 8686 EquivalentCands.push_back(Cand->Function); 8687 continue; 8688 } 8689 8690 Best = end(); 8691 return OR_Ambiguous; 8692 } 8693 } 8694 8695 // Best is the best viable function. 8696 if (Best->Function && 8697 (Best->Function->isDeleted() || 8698 S.isFunctionConsideredUnavailable(Best->Function))) 8699 return OR_Deleted; 8700 8701 if (!EquivalentCands.empty()) 8702 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8703 EquivalentCands); 8704 8705 return OR_Success; 8706 } 8707 8708 namespace { 8709 8710 enum OverloadCandidateKind { 8711 oc_function, 8712 oc_method, 8713 oc_constructor, 8714 oc_function_template, 8715 oc_method_template, 8716 oc_constructor_template, 8717 oc_implicit_default_constructor, 8718 oc_implicit_copy_constructor, 8719 oc_implicit_move_constructor, 8720 oc_implicit_copy_assignment, 8721 oc_implicit_move_assignment, 8722 oc_implicit_inherited_constructor 8723 }; 8724 8725 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8726 FunctionDecl *Fn, 8727 std::string &Description) { 8728 bool isTemplate = false; 8729 8730 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8731 isTemplate = true; 8732 Description = S.getTemplateArgumentBindingsText( 8733 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8734 } 8735 8736 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8737 if (!Ctor->isImplicit()) 8738 return isTemplate ? oc_constructor_template : oc_constructor; 8739 8740 if (Ctor->getInheritedConstructor()) 8741 return oc_implicit_inherited_constructor; 8742 8743 if (Ctor->isDefaultConstructor()) 8744 return oc_implicit_default_constructor; 8745 8746 if (Ctor->isMoveConstructor()) 8747 return oc_implicit_move_constructor; 8748 8749 assert(Ctor->isCopyConstructor() && 8750 "unexpected sort of implicit constructor"); 8751 return oc_implicit_copy_constructor; 8752 } 8753 8754 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8755 // This actually gets spelled 'candidate function' for now, but 8756 // it doesn't hurt to split it out. 8757 if (!Meth->isImplicit()) 8758 return isTemplate ? oc_method_template : oc_method; 8759 8760 if (Meth->isMoveAssignmentOperator()) 8761 return oc_implicit_move_assignment; 8762 8763 if (Meth->isCopyAssignmentOperator()) 8764 return oc_implicit_copy_assignment; 8765 8766 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8767 return oc_method; 8768 } 8769 8770 return isTemplate ? oc_function_template : oc_function; 8771 } 8772 8773 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8774 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8775 if (!Ctor) return; 8776 8777 Ctor = Ctor->getInheritedConstructor(); 8778 if (!Ctor) return; 8779 8780 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8781 } 8782 8783 } // end anonymous namespace 8784 8785 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8786 const FunctionDecl *FD) { 8787 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8788 bool AlwaysTrue; 8789 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8790 return false; 8791 if (!AlwaysTrue) 8792 return false; 8793 } 8794 return true; 8795 } 8796 8797 // Notes the location of an overload candidate. 8798 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8799 bool TakingAddress) { 8800 std::string FnDesc; 8801 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8802 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8803 << (unsigned) K << FnDesc; 8804 if (TakingAddress && !isFunctionAlwaysEnabled(Context, Fn)) 8805 PD << ft_addr_enable_if; 8806 else 8807 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8808 Diag(Fn->getLocation(), PD); 8809 MaybeEmitInheritedConstructorNote(*this, Fn); 8810 } 8811 8812 // Notes the location of all overload candidates designated through 8813 // OverloadedExpr 8814 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8815 bool TakingAddress) { 8816 assert(OverloadedExpr->getType() == Context.OverloadTy); 8817 8818 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8819 OverloadExpr *OvlExpr = Ovl.Expression; 8820 8821 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8822 IEnd = OvlExpr->decls_end(); 8823 I != IEnd; ++I) { 8824 if (FunctionTemplateDecl *FunTmpl = 8825 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8826 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8827 TakingAddress); 8828 } else if (FunctionDecl *Fun 8829 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8830 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8831 } 8832 } 8833 } 8834 8835 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8836 /// "lead" diagnostic; it will be given two arguments, the source and 8837 /// target types of the conversion. 8838 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8839 Sema &S, 8840 SourceLocation CaretLoc, 8841 const PartialDiagnostic &PDiag) const { 8842 S.Diag(CaretLoc, PDiag) 8843 << Ambiguous.getFromType() << Ambiguous.getToType(); 8844 // FIXME: The note limiting machinery is borrowed from 8845 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8846 // refactoring here. 8847 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8848 unsigned CandsShown = 0; 8849 AmbiguousConversionSequence::const_iterator I, E; 8850 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8851 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8852 break; 8853 ++CandsShown; 8854 S.NoteOverloadCandidate(*I); 8855 } 8856 if (I != E) 8857 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8858 } 8859 8860 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8861 unsigned I) { 8862 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8863 assert(Conv.isBad()); 8864 assert(Cand->Function && "for now, candidate must be a function"); 8865 FunctionDecl *Fn = Cand->Function; 8866 8867 // There's a conversion slot for the object argument if this is a 8868 // non-constructor method. Note that 'I' corresponds the 8869 // conversion-slot index. 8870 bool isObjectArgument = false; 8871 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8872 if (I == 0) 8873 isObjectArgument = true; 8874 else 8875 I--; 8876 } 8877 8878 std::string FnDesc; 8879 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8880 8881 Expr *FromExpr = Conv.Bad.FromExpr; 8882 QualType FromTy = Conv.Bad.getFromType(); 8883 QualType ToTy = Conv.Bad.getToType(); 8884 8885 if (FromTy == S.Context.OverloadTy) { 8886 assert(FromExpr && "overload set argument came from implicit argument?"); 8887 Expr *E = FromExpr->IgnoreParens(); 8888 if (isa<UnaryOperator>(E)) 8889 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8890 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8891 8892 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8893 << (unsigned) FnKind << FnDesc 8894 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8895 << ToTy << Name << I+1; 8896 MaybeEmitInheritedConstructorNote(S, Fn); 8897 return; 8898 } 8899 8900 // Do some hand-waving analysis to see if the non-viability is due 8901 // to a qualifier mismatch. 8902 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8903 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8904 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8905 CToTy = RT->getPointeeType(); 8906 else { 8907 // TODO: detect and diagnose the full richness of const mismatches. 8908 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8909 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8910 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8911 } 8912 8913 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8914 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8915 Qualifiers FromQs = CFromTy.getQualifiers(); 8916 Qualifiers ToQs = CToTy.getQualifiers(); 8917 8918 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8920 << (unsigned) FnKind << FnDesc 8921 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8922 << FromTy 8923 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8924 << (unsigned) isObjectArgument << I+1; 8925 MaybeEmitInheritedConstructorNote(S, Fn); 8926 return; 8927 } 8928 8929 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8930 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8931 << (unsigned) FnKind << FnDesc 8932 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8933 << FromTy 8934 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8935 << (unsigned) isObjectArgument << I+1; 8936 MaybeEmitInheritedConstructorNote(S, Fn); 8937 return; 8938 } 8939 8940 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8941 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8942 << (unsigned) FnKind << FnDesc 8943 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8944 << FromTy 8945 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8946 << (unsigned) isObjectArgument << I+1; 8947 MaybeEmitInheritedConstructorNote(S, Fn); 8948 return; 8949 } 8950 8951 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8952 assert(CVR && "unexpected qualifiers mismatch"); 8953 8954 if (isObjectArgument) { 8955 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8956 << (unsigned) FnKind << FnDesc 8957 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8958 << FromTy << (CVR - 1); 8959 } else { 8960 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8961 << (unsigned) FnKind << FnDesc 8962 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8963 << FromTy << (CVR - 1) << I+1; 8964 } 8965 MaybeEmitInheritedConstructorNote(S, Fn); 8966 return; 8967 } 8968 8969 // Special diagnostic for failure to convert an initializer list, since 8970 // telling the user that it has type void is not useful. 8971 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8972 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8973 << (unsigned) FnKind << FnDesc 8974 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8975 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8976 MaybeEmitInheritedConstructorNote(S, Fn); 8977 return; 8978 } 8979 8980 // Diagnose references or pointers to incomplete types differently, 8981 // since it's far from impossible that the incompleteness triggered 8982 // the failure. 8983 QualType TempFromTy = FromTy.getNonReferenceType(); 8984 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8985 TempFromTy = PTy->getPointeeType(); 8986 if (TempFromTy->isIncompleteType()) { 8987 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8988 << (unsigned) FnKind << FnDesc 8989 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8990 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8991 MaybeEmitInheritedConstructorNote(S, Fn); 8992 return; 8993 } 8994 8995 // Diagnose base -> derived pointer conversions. 8996 unsigned BaseToDerivedConversion = 0; 8997 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8998 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8999 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9000 FromPtrTy->getPointeeType()) && 9001 !FromPtrTy->getPointeeType()->isIncompleteType() && 9002 !ToPtrTy->getPointeeType()->isIncompleteType() && 9003 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 9004 FromPtrTy->getPointeeType())) 9005 BaseToDerivedConversion = 1; 9006 } 9007 } else if (const ObjCObjectPointerType *FromPtrTy 9008 = FromTy->getAs<ObjCObjectPointerType>()) { 9009 if (const ObjCObjectPointerType *ToPtrTy 9010 = ToTy->getAs<ObjCObjectPointerType>()) 9011 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9012 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9013 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9014 FromPtrTy->getPointeeType()) && 9015 FromIface->isSuperClassOf(ToIface)) 9016 BaseToDerivedConversion = 2; 9017 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9018 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9019 !FromTy->isIncompleteType() && 9020 !ToRefTy->getPointeeType()->isIncompleteType() && 9021 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 9022 BaseToDerivedConversion = 3; 9023 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9024 ToTy.getNonReferenceType().getCanonicalType() == 9025 FromTy.getNonReferenceType().getCanonicalType()) { 9026 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9027 << (unsigned) FnKind << FnDesc 9028 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9029 << (unsigned) isObjectArgument << I + 1; 9030 MaybeEmitInheritedConstructorNote(S, Fn); 9031 return; 9032 } 9033 } 9034 9035 if (BaseToDerivedConversion) { 9036 S.Diag(Fn->getLocation(), 9037 diag::note_ovl_candidate_bad_base_to_derived_conv) 9038 << (unsigned) FnKind << FnDesc 9039 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9040 << (BaseToDerivedConversion - 1) 9041 << FromTy << ToTy << I+1; 9042 MaybeEmitInheritedConstructorNote(S, Fn); 9043 return; 9044 } 9045 9046 if (isa<ObjCObjectPointerType>(CFromTy) && 9047 isa<PointerType>(CToTy)) { 9048 Qualifiers FromQs = CFromTy.getQualifiers(); 9049 Qualifiers ToQs = CToTy.getQualifiers(); 9050 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9051 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9052 << (unsigned) FnKind << FnDesc 9053 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9054 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9055 MaybeEmitInheritedConstructorNote(S, Fn); 9056 return; 9057 } 9058 } 9059 9060 // Emit the generic diagnostic and, optionally, add the hints to it. 9061 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9062 FDiag << (unsigned) FnKind << FnDesc 9063 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9064 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9065 << (unsigned) (Cand->Fix.Kind); 9066 9067 // If we can fix the conversion, suggest the FixIts. 9068 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9069 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9070 FDiag << *HI; 9071 S.Diag(Fn->getLocation(), FDiag); 9072 9073 MaybeEmitInheritedConstructorNote(S, Fn); 9074 } 9075 9076 /// Additional arity mismatch diagnosis specific to a function overload 9077 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9078 /// over a candidate in any candidate set. 9079 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9080 unsigned NumArgs) { 9081 FunctionDecl *Fn = Cand->Function; 9082 unsigned MinParams = Fn->getMinRequiredArguments(); 9083 9084 // With invalid overloaded operators, it's possible that we think we 9085 // have an arity mismatch when in fact it looks like we have the 9086 // right number of arguments, because only overloaded operators have 9087 // the weird behavior of overloading member and non-member functions. 9088 // Just don't report anything. 9089 if (Fn->isInvalidDecl() && 9090 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9091 return true; 9092 9093 if (NumArgs < MinParams) { 9094 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9095 (Cand->FailureKind == ovl_fail_bad_deduction && 9096 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9097 } else { 9098 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9099 (Cand->FailureKind == ovl_fail_bad_deduction && 9100 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9101 } 9102 9103 return false; 9104 } 9105 9106 /// General arity mismatch diagnosis over a candidate in a candidate set. 9107 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9108 assert(isa<FunctionDecl>(D) && 9109 "The templated declaration should at least be a function" 9110 " when diagnosing bad template argument deduction due to too many" 9111 " or too few arguments"); 9112 9113 FunctionDecl *Fn = cast<FunctionDecl>(D); 9114 9115 // TODO: treat calls to a missing default constructor as a special case 9116 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9117 unsigned MinParams = Fn->getMinRequiredArguments(); 9118 9119 // at least / at most / exactly 9120 unsigned mode, modeCount; 9121 if (NumFormalArgs < MinParams) { 9122 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9123 FnTy->isTemplateVariadic()) 9124 mode = 0; // "at least" 9125 else 9126 mode = 2; // "exactly" 9127 modeCount = MinParams; 9128 } else { 9129 if (MinParams != FnTy->getNumParams()) 9130 mode = 1; // "at most" 9131 else 9132 mode = 2; // "exactly" 9133 modeCount = FnTy->getNumParams(); 9134 } 9135 9136 std::string Description; 9137 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9138 9139 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9140 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9141 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9142 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9143 else 9144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9145 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9146 << mode << modeCount << NumFormalArgs; 9147 MaybeEmitInheritedConstructorNote(S, Fn); 9148 } 9149 9150 /// Arity mismatch diagnosis specific to a function overload candidate. 9151 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9152 unsigned NumFormalArgs) { 9153 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9154 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9155 } 9156 9157 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9158 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9159 return FD->getDescribedFunctionTemplate(); 9160 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9161 return RD->getDescribedClassTemplate(); 9162 9163 llvm_unreachable("Unsupported: Getting the described template declaration" 9164 " for bad deduction diagnosis"); 9165 } 9166 9167 /// Diagnose a failed template-argument deduction. 9168 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9169 DeductionFailureInfo &DeductionFailure, 9170 unsigned NumArgs) { 9171 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9172 NamedDecl *ParamD; 9173 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9174 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9175 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9176 switch (DeductionFailure.Result) { 9177 case Sema::TDK_Success: 9178 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9179 9180 case Sema::TDK_Incomplete: { 9181 assert(ParamD && "no parameter found for incomplete deduction result"); 9182 S.Diag(Templated->getLocation(), 9183 diag::note_ovl_candidate_incomplete_deduction) 9184 << ParamD->getDeclName(); 9185 MaybeEmitInheritedConstructorNote(S, Templated); 9186 return; 9187 } 9188 9189 case Sema::TDK_Underqualified: { 9190 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9191 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9192 9193 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9194 9195 // Param will have been canonicalized, but it should just be a 9196 // qualified version of ParamD, so move the qualifiers to that. 9197 QualifierCollector Qs; 9198 Qs.strip(Param); 9199 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9200 assert(S.Context.hasSameType(Param, NonCanonParam)); 9201 9202 // Arg has also been canonicalized, but there's nothing we can do 9203 // about that. It also doesn't matter as much, because it won't 9204 // have any template parameters in it (because deduction isn't 9205 // done on dependent types). 9206 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9207 9208 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9209 << ParamD->getDeclName() << Arg << NonCanonParam; 9210 MaybeEmitInheritedConstructorNote(S, Templated); 9211 return; 9212 } 9213 9214 case Sema::TDK_Inconsistent: { 9215 assert(ParamD && "no parameter found for inconsistent deduction result"); 9216 int which = 0; 9217 if (isa<TemplateTypeParmDecl>(ParamD)) 9218 which = 0; 9219 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9220 which = 1; 9221 else { 9222 which = 2; 9223 } 9224 9225 S.Diag(Templated->getLocation(), 9226 diag::note_ovl_candidate_inconsistent_deduction) 9227 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9228 << *DeductionFailure.getSecondArg(); 9229 MaybeEmitInheritedConstructorNote(S, Templated); 9230 return; 9231 } 9232 9233 case Sema::TDK_InvalidExplicitArguments: 9234 assert(ParamD && "no parameter found for invalid explicit arguments"); 9235 if (ParamD->getDeclName()) 9236 S.Diag(Templated->getLocation(), 9237 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9238 << ParamD->getDeclName(); 9239 else { 9240 int index = 0; 9241 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9242 index = TTP->getIndex(); 9243 else if (NonTypeTemplateParmDecl *NTTP 9244 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9245 index = NTTP->getIndex(); 9246 else 9247 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9248 S.Diag(Templated->getLocation(), 9249 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9250 << (index + 1); 9251 } 9252 MaybeEmitInheritedConstructorNote(S, Templated); 9253 return; 9254 9255 case Sema::TDK_TooManyArguments: 9256 case Sema::TDK_TooFewArguments: 9257 DiagnoseArityMismatch(S, Templated, NumArgs); 9258 return; 9259 9260 case Sema::TDK_InstantiationDepth: 9261 S.Diag(Templated->getLocation(), 9262 diag::note_ovl_candidate_instantiation_depth); 9263 MaybeEmitInheritedConstructorNote(S, Templated); 9264 return; 9265 9266 case Sema::TDK_SubstitutionFailure: { 9267 // Format the template argument list into the argument string. 9268 SmallString<128> TemplateArgString; 9269 if (TemplateArgumentList *Args = 9270 DeductionFailure.getTemplateArgumentList()) { 9271 TemplateArgString = " "; 9272 TemplateArgString += S.getTemplateArgumentBindingsText( 9273 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9274 } 9275 9276 // If this candidate was disabled by enable_if, say so. 9277 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9278 if (PDiag && PDiag->second.getDiagID() == 9279 diag::err_typename_nested_not_found_enable_if) { 9280 // FIXME: Use the source range of the condition, and the fully-qualified 9281 // name of the enable_if template. These are both present in PDiag. 9282 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9283 << "'enable_if'" << TemplateArgString; 9284 return; 9285 } 9286 9287 // Format the SFINAE diagnostic into the argument string. 9288 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9289 // formatted message in another diagnostic. 9290 SmallString<128> SFINAEArgString; 9291 SourceRange R; 9292 if (PDiag) { 9293 SFINAEArgString = ": "; 9294 R = SourceRange(PDiag->first, PDiag->first); 9295 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9296 } 9297 9298 S.Diag(Templated->getLocation(), 9299 diag::note_ovl_candidate_substitution_failure) 9300 << TemplateArgString << SFINAEArgString << R; 9301 MaybeEmitInheritedConstructorNote(S, Templated); 9302 return; 9303 } 9304 9305 case Sema::TDK_FailedOverloadResolution: { 9306 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9307 S.Diag(Templated->getLocation(), 9308 diag::note_ovl_candidate_failed_overload_resolution) 9309 << R.Expression->getName(); 9310 return; 9311 } 9312 9313 case Sema::TDK_NonDeducedMismatch: { 9314 // FIXME: Provide a source location to indicate what we couldn't match. 9315 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9316 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9317 if (FirstTA.getKind() == TemplateArgument::Template && 9318 SecondTA.getKind() == TemplateArgument::Template) { 9319 TemplateName FirstTN = FirstTA.getAsTemplate(); 9320 TemplateName SecondTN = SecondTA.getAsTemplate(); 9321 if (FirstTN.getKind() == TemplateName::Template && 9322 SecondTN.getKind() == TemplateName::Template) { 9323 if (FirstTN.getAsTemplateDecl()->getName() == 9324 SecondTN.getAsTemplateDecl()->getName()) { 9325 // FIXME: This fixes a bad diagnostic where both templates are named 9326 // the same. This particular case is a bit difficult since: 9327 // 1) It is passed as a string to the diagnostic printer. 9328 // 2) The diagnostic printer only attempts to find a better 9329 // name for types, not decls. 9330 // Ideally, this should folded into the diagnostic printer. 9331 S.Diag(Templated->getLocation(), 9332 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9333 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9334 return; 9335 } 9336 } 9337 } 9338 // FIXME: For generic lambda parameters, check if the function is a lambda 9339 // call operator, and if so, emit a prettier and more informative 9340 // diagnostic that mentions 'auto' and lambda in addition to 9341 // (or instead of?) the canonical template type parameters. 9342 S.Diag(Templated->getLocation(), 9343 diag::note_ovl_candidate_non_deduced_mismatch) 9344 << FirstTA << SecondTA; 9345 return; 9346 } 9347 // TODO: diagnose these individually, then kill off 9348 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9349 case Sema::TDK_MiscellaneousDeductionFailure: 9350 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9351 MaybeEmitInheritedConstructorNote(S, Templated); 9352 return; 9353 } 9354 } 9355 9356 /// Diagnose a failed template-argument deduction, for function calls. 9357 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9358 unsigned NumArgs) { 9359 unsigned TDK = Cand->DeductionFailure.Result; 9360 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9361 if (CheckArityMismatch(S, Cand, NumArgs)) 9362 return; 9363 } 9364 DiagnoseBadDeduction(S, Cand->Function, // pattern 9365 Cand->DeductionFailure, NumArgs); 9366 } 9367 9368 /// CUDA: diagnose an invalid call across targets. 9369 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9370 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9371 FunctionDecl *Callee = Cand->Function; 9372 9373 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9374 CalleeTarget = S.IdentifyCUDATarget(Callee); 9375 9376 std::string FnDesc; 9377 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9378 9379 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9380 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9381 9382 // This could be an implicit constructor for which we could not infer the 9383 // target due to a collsion. Diagnose that case. 9384 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9385 if (Meth != nullptr && Meth->isImplicit()) { 9386 CXXRecordDecl *ParentClass = Meth->getParent(); 9387 Sema::CXXSpecialMember CSM; 9388 9389 switch (FnKind) { 9390 default: 9391 return; 9392 case oc_implicit_default_constructor: 9393 CSM = Sema::CXXDefaultConstructor; 9394 break; 9395 case oc_implicit_copy_constructor: 9396 CSM = Sema::CXXCopyConstructor; 9397 break; 9398 case oc_implicit_move_constructor: 9399 CSM = Sema::CXXMoveConstructor; 9400 break; 9401 case oc_implicit_copy_assignment: 9402 CSM = Sema::CXXCopyAssignment; 9403 break; 9404 case oc_implicit_move_assignment: 9405 CSM = Sema::CXXMoveAssignment; 9406 break; 9407 }; 9408 9409 bool ConstRHS = false; 9410 if (Meth->getNumParams()) { 9411 if (const ReferenceType *RT = 9412 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9413 ConstRHS = RT->getPointeeType().isConstQualified(); 9414 } 9415 } 9416 9417 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9418 /* ConstRHS */ ConstRHS, 9419 /* Diagnose */ true); 9420 } 9421 } 9422 9423 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9424 FunctionDecl *Callee = Cand->Function; 9425 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9426 9427 S.Diag(Callee->getLocation(), 9428 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9429 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9430 } 9431 9432 /// Generates a 'note' diagnostic for an overload candidate. We've 9433 /// already generated a primary error at the call site. 9434 /// 9435 /// It really does need to be a single diagnostic with its caret 9436 /// pointed at the candidate declaration. Yes, this creates some 9437 /// major challenges of technical writing. Yes, this makes pointing 9438 /// out problems with specific arguments quite awkward. It's still 9439 /// better than generating twenty screens of text for every failed 9440 /// overload. 9441 /// 9442 /// It would be great to be able to express per-candidate problems 9443 /// more richly for those diagnostic clients that cared, but we'd 9444 /// still have to be just as careful with the default diagnostics. 9445 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9446 unsigned NumArgs) { 9447 FunctionDecl *Fn = Cand->Function; 9448 9449 // Note deleted candidates, but only if they're viable. 9450 if (Cand->Viable && (Fn->isDeleted() || 9451 S.isFunctionConsideredUnavailable(Fn))) { 9452 std::string FnDesc; 9453 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9454 9455 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9456 << FnKind << FnDesc 9457 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9458 MaybeEmitInheritedConstructorNote(S, Fn); 9459 return; 9460 } 9461 9462 // We don't really have anything else to say about viable candidates. 9463 if (Cand->Viable) { 9464 S.NoteOverloadCandidate(Fn); 9465 return; 9466 } 9467 9468 switch (Cand->FailureKind) { 9469 case ovl_fail_too_many_arguments: 9470 case ovl_fail_too_few_arguments: 9471 return DiagnoseArityMismatch(S, Cand, NumArgs); 9472 9473 case ovl_fail_bad_deduction: 9474 return DiagnoseBadDeduction(S, Cand, NumArgs); 9475 9476 case ovl_fail_illegal_constructor: { 9477 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9478 << (Fn->getPrimaryTemplate() ? 1 : 0); 9479 MaybeEmitInheritedConstructorNote(S, Fn); 9480 return; 9481 } 9482 9483 case ovl_fail_trivial_conversion: 9484 case ovl_fail_bad_final_conversion: 9485 case ovl_fail_final_conversion_not_exact: 9486 return S.NoteOverloadCandidate(Fn); 9487 9488 case ovl_fail_bad_conversion: { 9489 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9490 for (unsigned N = Cand->NumConversions; I != N; ++I) 9491 if (Cand->Conversions[I].isBad()) 9492 return DiagnoseBadConversion(S, Cand, I); 9493 9494 // FIXME: this currently happens when we're called from SemaInit 9495 // when user-conversion overload fails. Figure out how to handle 9496 // those conditions and diagnose them well. 9497 return S.NoteOverloadCandidate(Fn); 9498 } 9499 9500 case ovl_fail_bad_target: 9501 return DiagnoseBadTarget(S, Cand); 9502 9503 case ovl_fail_enable_if: 9504 return DiagnoseFailedEnableIfAttr(S, Cand); 9505 } 9506 } 9507 9508 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9509 // Desugar the type of the surrogate down to a function type, 9510 // retaining as many typedefs as possible while still showing 9511 // the function type (and, therefore, its parameter types). 9512 QualType FnType = Cand->Surrogate->getConversionType(); 9513 bool isLValueReference = false; 9514 bool isRValueReference = false; 9515 bool isPointer = false; 9516 if (const LValueReferenceType *FnTypeRef = 9517 FnType->getAs<LValueReferenceType>()) { 9518 FnType = FnTypeRef->getPointeeType(); 9519 isLValueReference = true; 9520 } else if (const RValueReferenceType *FnTypeRef = 9521 FnType->getAs<RValueReferenceType>()) { 9522 FnType = FnTypeRef->getPointeeType(); 9523 isRValueReference = true; 9524 } 9525 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9526 FnType = FnTypePtr->getPointeeType(); 9527 isPointer = true; 9528 } 9529 // Desugar down to a function type. 9530 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9531 // Reconstruct the pointer/reference as appropriate. 9532 if (isPointer) FnType = S.Context.getPointerType(FnType); 9533 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9534 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9535 9536 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9537 << FnType; 9538 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9539 } 9540 9541 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9542 SourceLocation OpLoc, 9543 OverloadCandidate *Cand) { 9544 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9545 std::string TypeStr("operator"); 9546 TypeStr += Opc; 9547 TypeStr += "("; 9548 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9549 if (Cand->NumConversions == 1) { 9550 TypeStr += ")"; 9551 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9552 } else { 9553 TypeStr += ", "; 9554 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9555 TypeStr += ")"; 9556 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9557 } 9558 } 9559 9560 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9561 OverloadCandidate *Cand) { 9562 unsigned NoOperands = Cand->NumConversions; 9563 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9564 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9565 if (ICS.isBad()) break; // all meaningless after first invalid 9566 if (!ICS.isAmbiguous()) continue; 9567 9568 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9569 S.PDiag(diag::note_ambiguous_type_conversion)); 9570 } 9571 } 9572 9573 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9574 if (Cand->Function) 9575 return Cand->Function->getLocation(); 9576 if (Cand->IsSurrogate) 9577 return Cand->Surrogate->getLocation(); 9578 return SourceLocation(); 9579 } 9580 9581 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9582 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9583 case Sema::TDK_Success: 9584 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9585 9586 case Sema::TDK_Invalid: 9587 case Sema::TDK_Incomplete: 9588 return 1; 9589 9590 case Sema::TDK_Underqualified: 9591 case Sema::TDK_Inconsistent: 9592 return 2; 9593 9594 case Sema::TDK_SubstitutionFailure: 9595 case Sema::TDK_NonDeducedMismatch: 9596 case Sema::TDK_MiscellaneousDeductionFailure: 9597 return 3; 9598 9599 case Sema::TDK_InstantiationDepth: 9600 case Sema::TDK_FailedOverloadResolution: 9601 return 4; 9602 9603 case Sema::TDK_InvalidExplicitArguments: 9604 return 5; 9605 9606 case Sema::TDK_TooManyArguments: 9607 case Sema::TDK_TooFewArguments: 9608 return 6; 9609 } 9610 llvm_unreachable("Unhandled deduction result"); 9611 } 9612 9613 namespace { 9614 struct CompareOverloadCandidatesForDisplay { 9615 Sema &S; 9616 size_t NumArgs; 9617 9618 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9619 : S(S), NumArgs(nArgs) {} 9620 9621 bool operator()(const OverloadCandidate *L, 9622 const OverloadCandidate *R) { 9623 // Fast-path this check. 9624 if (L == R) return false; 9625 9626 // Order first by viability. 9627 if (L->Viable) { 9628 if (!R->Viable) return true; 9629 9630 // TODO: introduce a tri-valued comparison for overload 9631 // candidates. Would be more worthwhile if we had a sort 9632 // that could exploit it. 9633 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9634 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9635 } else if (R->Viable) 9636 return false; 9637 9638 assert(L->Viable == R->Viable); 9639 9640 // Criteria by which we can sort non-viable candidates: 9641 if (!L->Viable) { 9642 // 1. Arity mismatches come after other candidates. 9643 if (L->FailureKind == ovl_fail_too_many_arguments || 9644 L->FailureKind == ovl_fail_too_few_arguments) { 9645 if (R->FailureKind == ovl_fail_too_many_arguments || 9646 R->FailureKind == ovl_fail_too_few_arguments) { 9647 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9648 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9649 if (LDist == RDist) { 9650 if (L->FailureKind == R->FailureKind) 9651 // Sort non-surrogates before surrogates. 9652 return !L->IsSurrogate && R->IsSurrogate; 9653 // Sort candidates requiring fewer parameters than there were 9654 // arguments given after candidates requiring more parameters 9655 // than there were arguments given. 9656 return L->FailureKind == ovl_fail_too_many_arguments; 9657 } 9658 return LDist < RDist; 9659 } 9660 return false; 9661 } 9662 if (R->FailureKind == ovl_fail_too_many_arguments || 9663 R->FailureKind == ovl_fail_too_few_arguments) 9664 return true; 9665 9666 // 2. Bad conversions come first and are ordered by the number 9667 // of bad conversions and quality of good conversions. 9668 if (L->FailureKind == ovl_fail_bad_conversion) { 9669 if (R->FailureKind != ovl_fail_bad_conversion) 9670 return true; 9671 9672 // The conversion that can be fixed with a smaller number of changes, 9673 // comes first. 9674 unsigned numLFixes = L->Fix.NumConversionsFixed; 9675 unsigned numRFixes = R->Fix.NumConversionsFixed; 9676 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9677 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9678 if (numLFixes != numRFixes) { 9679 return numLFixes < numRFixes; 9680 } 9681 9682 // If there's any ordering between the defined conversions... 9683 // FIXME: this might not be transitive. 9684 assert(L->NumConversions == R->NumConversions); 9685 9686 int leftBetter = 0; 9687 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9688 for (unsigned E = L->NumConversions; I != E; ++I) { 9689 switch (CompareImplicitConversionSequences(S, 9690 L->Conversions[I], 9691 R->Conversions[I])) { 9692 case ImplicitConversionSequence::Better: 9693 leftBetter++; 9694 break; 9695 9696 case ImplicitConversionSequence::Worse: 9697 leftBetter--; 9698 break; 9699 9700 case ImplicitConversionSequence::Indistinguishable: 9701 break; 9702 } 9703 } 9704 if (leftBetter > 0) return true; 9705 if (leftBetter < 0) return false; 9706 9707 } else if (R->FailureKind == ovl_fail_bad_conversion) 9708 return false; 9709 9710 if (L->FailureKind == ovl_fail_bad_deduction) { 9711 if (R->FailureKind != ovl_fail_bad_deduction) 9712 return true; 9713 9714 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9715 return RankDeductionFailure(L->DeductionFailure) 9716 < RankDeductionFailure(R->DeductionFailure); 9717 } else if (R->FailureKind == ovl_fail_bad_deduction) 9718 return false; 9719 9720 // TODO: others? 9721 } 9722 9723 // Sort everything else by location. 9724 SourceLocation LLoc = GetLocationForCandidate(L); 9725 SourceLocation RLoc = GetLocationForCandidate(R); 9726 9727 // Put candidates without locations (e.g. builtins) at the end. 9728 if (LLoc.isInvalid()) return false; 9729 if (RLoc.isInvalid()) return true; 9730 9731 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9732 } 9733 }; 9734 } 9735 9736 /// CompleteNonViableCandidate - Normally, overload resolution only 9737 /// computes up to the first. Produces the FixIt set if possible. 9738 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9739 ArrayRef<Expr *> Args) { 9740 assert(!Cand->Viable); 9741 9742 // Don't do anything on failures other than bad conversion. 9743 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9744 9745 // We only want the FixIts if all the arguments can be corrected. 9746 bool Unfixable = false; 9747 // Use a implicit copy initialization to check conversion fixes. 9748 Cand->Fix.setConversionChecker(TryCopyInitialization); 9749 9750 // Skip forward to the first bad conversion. 9751 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9752 unsigned ConvCount = Cand->NumConversions; 9753 while (true) { 9754 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9755 ConvIdx++; 9756 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9757 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9758 break; 9759 } 9760 } 9761 9762 if (ConvIdx == ConvCount) 9763 return; 9764 9765 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9766 "remaining conversion is initialized?"); 9767 9768 // FIXME: this should probably be preserved from the overload 9769 // operation somehow. 9770 bool SuppressUserConversions = false; 9771 9772 const FunctionProtoType* Proto; 9773 unsigned ArgIdx = ConvIdx; 9774 9775 if (Cand->IsSurrogate) { 9776 QualType ConvType 9777 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9778 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9779 ConvType = ConvPtrType->getPointeeType(); 9780 Proto = ConvType->getAs<FunctionProtoType>(); 9781 ArgIdx--; 9782 } else if (Cand->Function) { 9783 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9784 if (isa<CXXMethodDecl>(Cand->Function) && 9785 !isa<CXXConstructorDecl>(Cand->Function)) 9786 ArgIdx--; 9787 } else { 9788 // Builtin binary operator with a bad first conversion. 9789 assert(ConvCount <= 3); 9790 for (; ConvIdx != ConvCount; ++ConvIdx) 9791 Cand->Conversions[ConvIdx] 9792 = TryCopyInitialization(S, Args[ConvIdx], 9793 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9794 SuppressUserConversions, 9795 /*InOverloadResolution*/ true, 9796 /*AllowObjCWritebackConversion=*/ 9797 S.getLangOpts().ObjCAutoRefCount); 9798 return; 9799 } 9800 9801 // Fill in the rest of the conversions. 9802 unsigned NumParams = Proto->getNumParams(); 9803 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9804 if (ArgIdx < NumParams) { 9805 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9806 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9807 /*InOverloadResolution=*/true, 9808 /*AllowObjCWritebackConversion=*/ 9809 S.getLangOpts().ObjCAutoRefCount); 9810 // Store the FixIt in the candidate if it exists. 9811 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9812 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9813 } 9814 else 9815 Cand->Conversions[ConvIdx].setEllipsis(); 9816 } 9817 } 9818 9819 /// PrintOverloadCandidates - When overload resolution fails, prints 9820 /// diagnostic messages containing the candidates in the candidate 9821 /// set. 9822 void OverloadCandidateSet::NoteCandidates(Sema &S, 9823 OverloadCandidateDisplayKind OCD, 9824 ArrayRef<Expr *> Args, 9825 StringRef Opc, 9826 SourceLocation OpLoc) { 9827 // Sort the candidates by viability and position. Sorting directly would 9828 // be prohibitive, so we make a set of pointers and sort those. 9829 SmallVector<OverloadCandidate*, 32> Cands; 9830 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9831 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9832 if (Cand->Viable) 9833 Cands.push_back(Cand); 9834 else if (OCD == OCD_AllCandidates) { 9835 CompleteNonViableCandidate(S, Cand, Args); 9836 if (Cand->Function || Cand->IsSurrogate) 9837 Cands.push_back(Cand); 9838 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9839 // want to list every possible builtin candidate. 9840 } 9841 } 9842 9843 std::sort(Cands.begin(), Cands.end(), 9844 CompareOverloadCandidatesForDisplay(S, Args.size())); 9845 9846 bool ReportedAmbiguousConversions = false; 9847 9848 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9849 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9850 unsigned CandsShown = 0; 9851 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9852 OverloadCandidate *Cand = *I; 9853 9854 // Set an arbitrary limit on the number of candidate functions we'll spam 9855 // the user with. FIXME: This limit should depend on details of the 9856 // candidate list. 9857 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9858 break; 9859 } 9860 ++CandsShown; 9861 9862 if (Cand->Function) 9863 NoteFunctionCandidate(S, Cand, Args.size()); 9864 else if (Cand->IsSurrogate) 9865 NoteSurrogateCandidate(S, Cand); 9866 else { 9867 assert(Cand->Viable && 9868 "Non-viable built-in candidates are not added to Cands."); 9869 // Generally we only see ambiguities including viable builtin 9870 // operators if overload resolution got screwed up by an 9871 // ambiguous user-defined conversion. 9872 // 9873 // FIXME: It's quite possible for different conversions to see 9874 // different ambiguities, though. 9875 if (!ReportedAmbiguousConversions) { 9876 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9877 ReportedAmbiguousConversions = true; 9878 } 9879 9880 // If this is a viable builtin, print it. 9881 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9882 } 9883 } 9884 9885 if (I != E) 9886 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9887 } 9888 9889 static SourceLocation 9890 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9891 return Cand->Specialization ? Cand->Specialization->getLocation() 9892 : SourceLocation(); 9893 } 9894 9895 namespace { 9896 struct CompareTemplateSpecCandidatesForDisplay { 9897 Sema &S; 9898 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9899 9900 bool operator()(const TemplateSpecCandidate *L, 9901 const TemplateSpecCandidate *R) { 9902 // Fast-path this check. 9903 if (L == R) 9904 return false; 9905 9906 // Assuming that both candidates are not matches... 9907 9908 // Sort by the ranking of deduction failures. 9909 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9910 return RankDeductionFailure(L->DeductionFailure) < 9911 RankDeductionFailure(R->DeductionFailure); 9912 9913 // Sort everything else by location. 9914 SourceLocation LLoc = GetLocationForCandidate(L); 9915 SourceLocation RLoc = GetLocationForCandidate(R); 9916 9917 // Put candidates without locations (e.g. builtins) at the end. 9918 if (LLoc.isInvalid()) 9919 return false; 9920 if (RLoc.isInvalid()) 9921 return true; 9922 9923 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9924 } 9925 }; 9926 } 9927 9928 /// Diagnose a template argument deduction failure. 9929 /// We are treating these failures as overload failures due to bad 9930 /// deductions. 9931 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9932 DiagnoseBadDeduction(S, Specialization, // pattern 9933 DeductionFailure, /*NumArgs=*/0); 9934 } 9935 9936 void TemplateSpecCandidateSet::destroyCandidates() { 9937 for (iterator i = begin(), e = end(); i != e; ++i) { 9938 i->DeductionFailure.Destroy(); 9939 } 9940 } 9941 9942 void TemplateSpecCandidateSet::clear() { 9943 destroyCandidates(); 9944 Candidates.clear(); 9945 } 9946 9947 /// NoteCandidates - When no template specialization match is found, prints 9948 /// diagnostic messages containing the non-matching specializations that form 9949 /// the candidate set. 9950 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9951 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9952 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9953 // Sort the candidates by position (assuming no candidate is a match). 9954 // Sorting directly would be prohibitive, so we make a set of pointers 9955 // and sort those. 9956 SmallVector<TemplateSpecCandidate *, 32> Cands; 9957 Cands.reserve(size()); 9958 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9959 if (Cand->Specialization) 9960 Cands.push_back(Cand); 9961 // Otherwise, this is a non-matching builtin candidate. We do not, 9962 // in general, want to list every possible builtin candidate. 9963 } 9964 9965 std::sort(Cands.begin(), Cands.end(), 9966 CompareTemplateSpecCandidatesForDisplay(S)); 9967 9968 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9969 // for generalization purposes (?). 9970 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9971 9972 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9973 unsigned CandsShown = 0; 9974 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9975 TemplateSpecCandidate *Cand = *I; 9976 9977 // Set an arbitrary limit on the number of candidates we'll spam 9978 // the user with. FIXME: This limit should depend on details of the 9979 // candidate list. 9980 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9981 break; 9982 ++CandsShown; 9983 9984 assert(Cand->Specialization && 9985 "Non-matching built-in candidates are not added to Cands."); 9986 Cand->NoteDeductionFailure(S); 9987 } 9988 9989 if (I != E) 9990 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9991 } 9992 9993 // [PossiblyAFunctionType] --> [Return] 9994 // NonFunctionType --> NonFunctionType 9995 // R (A) --> R(A) 9996 // R (*)(A) --> R (A) 9997 // R (&)(A) --> R (A) 9998 // R (S::*)(A) --> R (A) 9999 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10000 QualType Ret = PossiblyAFunctionType; 10001 if (const PointerType *ToTypePtr = 10002 PossiblyAFunctionType->getAs<PointerType>()) 10003 Ret = ToTypePtr->getPointeeType(); 10004 else if (const ReferenceType *ToTypeRef = 10005 PossiblyAFunctionType->getAs<ReferenceType>()) 10006 Ret = ToTypeRef->getPointeeType(); 10007 else if (const MemberPointerType *MemTypePtr = 10008 PossiblyAFunctionType->getAs<MemberPointerType>()) 10009 Ret = MemTypePtr->getPointeeType(); 10010 Ret = 10011 Context.getCanonicalType(Ret).getUnqualifiedType(); 10012 return Ret; 10013 } 10014 10015 namespace { 10016 // A helper class to help with address of function resolution 10017 // - allows us to avoid passing around all those ugly parameters 10018 class AddressOfFunctionResolver { 10019 Sema& S; 10020 Expr* SourceExpr; 10021 const QualType& TargetType; 10022 QualType TargetFunctionType; // Extracted function type from target type 10023 10024 bool Complain; 10025 //DeclAccessPair& ResultFunctionAccessPair; 10026 ASTContext& Context; 10027 10028 bool TargetTypeIsNonStaticMemberFunction; 10029 bool FoundNonTemplateFunction; 10030 bool StaticMemberFunctionFromBoundPointer; 10031 bool HasComplained; 10032 10033 OverloadExpr::FindResult OvlExprInfo; 10034 OverloadExpr *OvlExpr; 10035 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10036 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10037 TemplateSpecCandidateSet FailedCandidates; 10038 10039 public: 10040 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10041 const QualType &TargetType, bool Complain) 10042 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10043 Complain(Complain), Context(S.getASTContext()), 10044 TargetTypeIsNonStaticMemberFunction( 10045 !!TargetType->getAs<MemberPointerType>()), 10046 FoundNonTemplateFunction(false), 10047 StaticMemberFunctionFromBoundPointer(false), 10048 HasComplained(false), 10049 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10050 OvlExpr(OvlExprInfo.Expression), 10051 FailedCandidates(OvlExpr->getNameLoc()) { 10052 ExtractUnqualifiedFunctionTypeFromTargetType(); 10053 10054 if (TargetFunctionType->isFunctionType()) { 10055 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10056 if (!UME->isImplicitAccess() && 10057 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10058 StaticMemberFunctionFromBoundPointer = true; 10059 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10060 DeclAccessPair dap; 10061 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10062 OvlExpr, false, &dap)) { 10063 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10064 if (!Method->isStatic()) { 10065 // If the target type is a non-function type and the function found 10066 // is a non-static member function, pretend as if that was the 10067 // target, it's the only possible type to end up with. 10068 TargetTypeIsNonStaticMemberFunction = true; 10069 10070 // And skip adding the function if its not in the proper form. 10071 // We'll diagnose this due to an empty set of functions. 10072 if (!OvlExprInfo.HasFormOfMemberPointer) 10073 return; 10074 } 10075 10076 Matches.push_back(std::make_pair(dap, Fn)); 10077 } 10078 return; 10079 } 10080 10081 if (OvlExpr->hasExplicitTemplateArgs()) 10082 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 10083 10084 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10085 // C++ [over.over]p4: 10086 // If more than one function is selected, [...] 10087 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10088 if (FoundNonTemplateFunction) 10089 EliminateAllTemplateMatches(); 10090 else 10091 EliminateAllExceptMostSpecializedTemplate(); 10092 } 10093 } 10094 10095 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10096 Matches.size() > 1) 10097 EliminateSuboptimalCudaMatches(); 10098 } 10099 10100 bool hasComplained() const { return HasComplained; } 10101 10102 private: 10103 // Is A considered a better overload candidate for the desired type than B? 10104 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10105 return hasBetterEnableIfAttrs(S, A, B); 10106 } 10107 10108 // Returns true if we've eliminated any (read: all but one) candidates, false 10109 // otherwise. 10110 bool eliminiateSuboptimalOverloadCandidates() { 10111 // Same algorithm as overload resolution -- one pass to pick the "best", 10112 // another pass to be sure that nothing is better than the best. 10113 auto Best = Matches.begin(); 10114 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10115 if (isBetterCandidate(I->second, Best->second)) 10116 Best = I; 10117 10118 const FunctionDecl *BestFn = Best->second; 10119 auto IsBestOrInferiorToBest = [this, BestFn]( 10120 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10121 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10122 }; 10123 10124 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10125 // option, so we can potentially give the user a better error 10126 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10127 return false; 10128 Matches[0] = *Best; 10129 Matches.resize(1); 10130 return true; 10131 } 10132 10133 bool isTargetTypeAFunction() const { 10134 return TargetFunctionType->isFunctionType(); 10135 } 10136 10137 // [ToType] [Return] 10138 10139 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10140 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10141 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10142 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10143 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10144 } 10145 10146 // return true if any matching specializations were found 10147 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10148 const DeclAccessPair& CurAccessFunPair) { 10149 if (CXXMethodDecl *Method 10150 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10151 // Skip non-static function templates when converting to pointer, and 10152 // static when converting to member pointer. 10153 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10154 return false; 10155 } 10156 else if (TargetTypeIsNonStaticMemberFunction) 10157 return false; 10158 10159 // C++ [over.over]p2: 10160 // If the name is a function template, template argument deduction is 10161 // done (14.8.2.2), and if the argument deduction succeeds, the 10162 // resulting template argument list is used to generate a single 10163 // function template specialization, which is added to the set of 10164 // overloaded functions considered. 10165 FunctionDecl *Specialization = nullptr; 10166 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10167 if (Sema::TemplateDeductionResult Result 10168 = S.DeduceTemplateArguments(FunctionTemplate, 10169 &OvlExplicitTemplateArgs, 10170 TargetFunctionType, Specialization, 10171 Info, /*InOverloadResolution=*/true)) { 10172 // Make a note of the failed deduction for diagnostics. 10173 FailedCandidates.addCandidate() 10174 .set(FunctionTemplate->getTemplatedDecl(), 10175 MakeDeductionFailureInfo(Context, Result, Info)); 10176 return false; 10177 } 10178 10179 // Template argument deduction ensures that we have an exact match or 10180 // compatible pointer-to-function arguments that would be adjusted by ICS. 10181 // This function template specicalization works. 10182 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 10183 assert(S.isSameOrCompatibleFunctionType( 10184 Context.getCanonicalType(Specialization->getType()), 10185 Context.getCanonicalType(TargetFunctionType)) || 10186 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())); 10187 10188 if (!isFunctionAlwaysEnabled(S.Context, Specialization)) 10189 return false; 10190 10191 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10192 return true; 10193 } 10194 10195 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10196 const DeclAccessPair& CurAccessFunPair) { 10197 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10198 // Skip non-static functions when converting to pointer, and static 10199 // when converting to member pointer. 10200 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10201 return false; 10202 } 10203 else if (TargetTypeIsNonStaticMemberFunction) 10204 return false; 10205 10206 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10207 if (S.getLangOpts().CUDA) 10208 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10209 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10210 return false; 10211 10212 // If any candidate has a placeholder return type, trigger its deduction 10213 // now. 10214 if (S.getLangOpts().CPlusPlus14 && 10215 FunDecl->getReturnType()->isUndeducedType() && 10216 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10217 HasComplained |= Complain; 10218 return false; 10219 } 10220 10221 if (!isFunctionAlwaysEnabled(S.Context, FunDecl)) 10222 return false; 10223 10224 QualType ResultTy; 10225 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10226 FunDecl->getType()) || 10227 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10228 ResultTy) || 10229 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) { 10230 Matches.push_back(std::make_pair( 10231 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10232 FoundNonTemplateFunction = true; 10233 return true; 10234 } 10235 } 10236 10237 return false; 10238 } 10239 10240 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10241 bool Ret = false; 10242 10243 // If the overload expression doesn't have the form of a pointer to 10244 // member, don't try to convert it to a pointer-to-member type. 10245 if (IsInvalidFormOfPointerToMemberFunction()) 10246 return false; 10247 10248 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10249 E = OvlExpr->decls_end(); 10250 I != E; ++I) { 10251 // Look through any using declarations to find the underlying function. 10252 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10253 10254 // C++ [over.over]p3: 10255 // Non-member functions and static member functions match 10256 // targets of type "pointer-to-function" or "reference-to-function." 10257 // Nonstatic member functions match targets of 10258 // type "pointer-to-member-function." 10259 // Note that according to DR 247, the containing class does not matter. 10260 if (FunctionTemplateDecl *FunctionTemplate 10261 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10262 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10263 Ret = true; 10264 } 10265 // If we have explicit template arguments supplied, skip non-templates. 10266 else if (!OvlExpr->hasExplicitTemplateArgs() && 10267 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10268 Ret = true; 10269 } 10270 assert(Ret || Matches.empty()); 10271 return Ret; 10272 } 10273 10274 void EliminateAllExceptMostSpecializedTemplate() { 10275 // [...] and any given function template specialization F1 is 10276 // eliminated if the set contains a second function template 10277 // specialization whose function template is more specialized 10278 // than the function template of F1 according to the partial 10279 // ordering rules of 14.5.5.2. 10280 10281 // The algorithm specified above is quadratic. We instead use a 10282 // two-pass algorithm (similar to the one used to identify the 10283 // best viable function in an overload set) that identifies the 10284 // best function template (if it exists). 10285 10286 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10287 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10288 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10289 10290 // TODO: It looks like FailedCandidates does not serve much purpose 10291 // here, since the no_viable diagnostic has index 0. 10292 UnresolvedSetIterator Result = S.getMostSpecialized( 10293 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10294 SourceExpr->getLocStart(), S.PDiag(), 10295 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10296 .second->getDeclName(), 10297 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10298 Complain, TargetFunctionType); 10299 10300 if (Result != MatchesCopy.end()) { 10301 // Make it the first and only element 10302 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10303 Matches[0].second = cast<FunctionDecl>(*Result); 10304 Matches.resize(1); 10305 } else 10306 HasComplained |= Complain; 10307 } 10308 10309 void EliminateAllTemplateMatches() { 10310 // [...] any function template specializations in the set are 10311 // eliminated if the set also contains a non-template function, [...] 10312 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10313 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10314 ++I; 10315 else { 10316 Matches[I] = Matches[--N]; 10317 Matches.resize(N); 10318 } 10319 } 10320 } 10321 10322 void EliminateSuboptimalCudaMatches() { 10323 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10324 } 10325 10326 public: 10327 void ComplainNoMatchesFound() const { 10328 assert(Matches.empty()); 10329 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10330 << OvlExpr->getName() << TargetFunctionType 10331 << OvlExpr->getSourceRange(); 10332 if (FailedCandidates.empty()) 10333 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10334 /*TakingAddress=*/true); 10335 else { 10336 // We have some deduction failure messages. Use them to diagnose 10337 // the function templates, and diagnose the non-template candidates 10338 // normally. 10339 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10340 IEnd = OvlExpr->decls_end(); 10341 I != IEnd; ++I) 10342 if (FunctionDecl *Fun = 10343 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10344 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10345 /*TakingAddress=*/true); 10346 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10347 } 10348 } 10349 10350 bool IsInvalidFormOfPointerToMemberFunction() const { 10351 return TargetTypeIsNonStaticMemberFunction && 10352 !OvlExprInfo.HasFormOfMemberPointer; 10353 } 10354 10355 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10356 // TODO: Should we condition this on whether any functions might 10357 // have matched, or is it more appropriate to do that in callers? 10358 // TODO: a fixit wouldn't hurt. 10359 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10360 << TargetType << OvlExpr->getSourceRange(); 10361 } 10362 10363 bool IsStaticMemberFunctionFromBoundPointer() const { 10364 return StaticMemberFunctionFromBoundPointer; 10365 } 10366 10367 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10368 S.Diag(OvlExpr->getLocStart(), 10369 diag::err_invalid_form_pointer_member_function) 10370 << OvlExpr->getSourceRange(); 10371 } 10372 10373 void ComplainOfInvalidConversion() const { 10374 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10375 << OvlExpr->getName() << TargetType; 10376 } 10377 10378 void ComplainMultipleMatchesFound() const { 10379 assert(Matches.size() > 1); 10380 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10381 << OvlExpr->getName() 10382 << OvlExpr->getSourceRange(); 10383 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10384 /*TakingAddress=*/true); 10385 } 10386 10387 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10388 10389 int getNumMatches() const { return Matches.size(); } 10390 10391 FunctionDecl* getMatchingFunctionDecl() const { 10392 if (Matches.size() != 1) return nullptr; 10393 return Matches[0].second; 10394 } 10395 10396 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10397 if (Matches.size() != 1) return nullptr; 10398 return &Matches[0].first; 10399 } 10400 }; 10401 } 10402 10403 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10404 /// an overloaded function (C++ [over.over]), where @p From is an 10405 /// expression with overloaded function type and @p ToType is the type 10406 /// we're trying to resolve to. For example: 10407 /// 10408 /// @code 10409 /// int f(double); 10410 /// int f(int); 10411 /// 10412 /// int (*pfd)(double) = f; // selects f(double) 10413 /// @endcode 10414 /// 10415 /// This routine returns the resulting FunctionDecl if it could be 10416 /// resolved, and NULL otherwise. When @p Complain is true, this 10417 /// routine will emit diagnostics if there is an error. 10418 FunctionDecl * 10419 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10420 QualType TargetType, 10421 bool Complain, 10422 DeclAccessPair &FoundResult, 10423 bool *pHadMultipleCandidates) { 10424 assert(AddressOfExpr->getType() == Context.OverloadTy); 10425 10426 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10427 Complain); 10428 int NumMatches = Resolver.getNumMatches(); 10429 FunctionDecl *Fn = nullptr; 10430 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10431 if (NumMatches == 0 && ShouldComplain) { 10432 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10433 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10434 else 10435 Resolver.ComplainNoMatchesFound(); 10436 } 10437 else if (NumMatches > 1 && ShouldComplain) 10438 Resolver.ComplainMultipleMatchesFound(); 10439 else if (NumMatches == 1) { 10440 Fn = Resolver.getMatchingFunctionDecl(); 10441 assert(Fn); 10442 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10443 if (Complain) { 10444 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10445 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10446 else 10447 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10448 } 10449 } 10450 10451 if (pHadMultipleCandidates) 10452 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10453 return Fn; 10454 } 10455 10456 /// \brief Given an expression that refers to an overloaded function, try to 10457 /// resolve that overloaded function expression down to a single function. 10458 /// 10459 /// This routine can only resolve template-ids that refer to a single function 10460 /// template, where that template-id refers to a single template whose template 10461 /// arguments are either provided by the template-id or have defaults, 10462 /// as described in C++0x [temp.arg.explicit]p3. 10463 /// 10464 /// If no template-ids are found, no diagnostics are emitted and NULL is 10465 /// returned. 10466 FunctionDecl * 10467 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10468 bool Complain, 10469 DeclAccessPair *FoundResult) { 10470 // C++ [over.over]p1: 10471 // [...] [Note: any redundant set of parentheses surrounding the 10472 // overloaded function name is ignored (5.1). ] 10473 // C++ [over.over]p1: 10474 // [...] The overloaded function name can be preceded by the & 10475 // operator. 10476 10477 // If we didn't actually find any template-ids, we're done. 10478 if (!ovl->hasExplicitTemplateArgs()) 10479 return nullptr; 10480 10481 TemplateArgumentListInfo ExplicitTemplateArgs; 10482 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10483 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10484 10485 // Look through all of the overloaded functions, searching for one 10486 // whose type matches exactly. 10487 FunctionDecl *Matched = nullptr; 10488 for (UnresolvedSetIterator I = ovl->decls_begin(), 10489 E = ovl->decls_end(); I != E; ++I) { 10490 // C++0x [temp.arg.explicit]p3: 10491 // [...] In contexts where deduction is done and fails, or in contexts 10492 // where deduction is not done, if a template argument list is 10493 // specified and it, along with any default template arguments, 10494 // identifies a single function template specialization, then the 10495 // template-id is an lvalue for the function template specialization. 10496 FunctionTemplateDecl *FunctionTemplate 10497 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10498 10499 // C++ [over.over]p2: 10500 // If the name is a function template, template argument deduction is 10501 // done (14.8.2.2), and if the argument deduction succeeds, the 10502 // resulting template argument list is used to generate a single 10503 // function template specialization, which is added to the set of 10504 // overloaded functions considered. 10505 FunctionDecl *Specialization = nullptr; 10506 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10507 if (TemplateDeductionResult Result 10508 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10509 Specialization, Info, 10510 /*InOverloadResolution=*/true)) { 10511 // Make a note of the failed deduction for diagnostics. 10512 // TODO: Actually use the failed-deduction info? 10513 FailedCandidates.addCandidate() 10514 .set(FunctionTemplate->getTemplatedDecl(), 10515 MakeDeductionFailureInfo(Context, Result, Info)); 10516 continue; 10517 } 10518 10519 assert(Specialization && "no specialization and no error?"); 10520 10521 // Multiple matches; we can't resolve to a single declaration. 10522 if (Matched) { 10523 if (Complain) { 10524 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10525 << ovl->getName(); 10526 NoteAllOverloadCandidates(ovl); 10527 } 10528 return nullptr; 10529 } 10530 10531 Matched = Specialization; 10532 if (FoundResult) *FoundResult = I.getPair(); 10533 } 10534 10535 if (Matched && getLangOpts().CPlusPlus14 && 10536 Matched->getReturnType()->isUndeducedType() && 10537 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10538 return nullptr; 10539 10540 return Matched; 10541 } 10542 10543 10544 10545 10546 // Resolve and fix an overloaded expression that can be resolved 10547 // because it identifies a single function template specialization. 10548 // 10549 // Last three arguments should only be supplied if Complain = true 10550 // 10551 // Return true if it was logically possible to so resolve the 10552 // expression, regardless of whether or not it succeeded. Always 10553 // returns true if 'complain' is set. 10554 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10555 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10556 bool complain, SourceRange OpRangeForComplaining, 10557 QualType DestTypeForComplaining, 10558 unsigned DiagIDForComplaining) { 10559 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10560 10561 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10562 10563 DeclAccessPair found; 10564 ExprResult SingleFunctionExpression; 10565 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10566 ovl.Expression, /*complain*/ false, &found)) { 10567 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10568 SrcExpr = ExprError(); 10569 return true; 10570 } 10571 10572 // It is only correct to resolve to an instance method if we're 10573 // resolving a form that's permitted to be a pointer to member. 10574 // Otherwise we'll end up making a bound member expression, which 10575 // is illegal in all the contexts we resolve like this. 10576 if (!ovl.HasFormOfMemberPointer && 10577 isa<CXXMethodDecl>(fn) && 10578 cast<CXXMethodDecl>(fn)->isInstance()) { 10579 if (!complain) return false; 10580 10581 Diag(ovl.Expression->getExprLoc(), 10582 diag::err_bound_member_function) 10583 << 0 << ovl.Expression->getSourceRange(); 10584 10585 // TODO: I believe we only end up here if there's a mix of 10586 // static and non-static candidates (otherwise the expression 10587 // would have 'bound member' type, not 'overload' type). 10588 // Ideally we would note which candidate was chosen and why 10589 // the static candidates were rejected. 10590 SrcExpr = ExprError(); 10591 return true; 10592 } 10593 10594 // Fix the expression to refer to 'fn'. 10595 SingleFunctionExpression = 10596 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10597 10598 // If desired, do function-to-pointer decay. 10599 if (doFunctionPointerConverion) { 10600 SingleFunctionExpression = 10601 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10602 if (SingleFunctionExpression.isInvalid()) { 10603 SrcExpr = ExprError(); 10604 return true; 10605 } 10606 } 10607 } 10608 10609 if (!SingleFunctionExpression.isUsable()) { 10610 if (complain) { 10611 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10612 << ovl.Expression->getName() 10613 << DestTypeForComplaining 10614 << OpRangeForComplaining 10615 << ovl.Expression->getQualifierLoc().getSourceRange(); 10616 NoteAllOverloadCandidates(SrcExpr.get()); 10617 10618 SrcExpr = ExprError(); 10619 return true; 10620 } 10621 10622 return false; 10623 } 10624 10625 SrcExpr = SingleFunctionExpression; 10626 return true; 10627 } 10628 10629 /// \brief Add a single candidate to the overload set. 10630 static void AddOverloadedCallCandidate(Sema &S, 10631 DeclAccessPair FoundDecl, 10632 TemplateArgumentListInfo *ExplicitTemplateArgs, 10633 ArrayRef<Expr *> Args, 10634 OverloadCandidateSet &CandidateSet, 10635 bool PartialOverloading, 10636 bool KnownValid) { 10637 NamedDecl *Callee = FoundDecl.getDecl(); 10638 if (isa<UsingShadowDecl>(Callee)) 10639 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10640 10641 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10642 if (ExplicitTemplateArgs) { 10643 assert(!KnownValid && "Explicit template arguments?"); 10644 return; 10645 } 10646 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10647 /*SuppressUsedConversions=*/false, 10648 PartialOverloading); 10649 return; 10650 } 10651 10652 if (FunctionTemplateDecl *FuncTemplate 10653 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10654 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10655 ExplicitTemplateArgs, Args, CandidateSet, 10656 /*SuppressUsedConversions=*/false, 10657 PartialOverloading); 10658 return; 10659 } 10660 10661 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10662 } 10663 10664 /// \brief Add the overload candidates named by callee and/or found by argument 10665 /// dependent lookup to the given overload set. 10666 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10667 ArrayRef<Expr *> Args, 10668 OverloadCandidateSet &CandidateSet, 10669 bool PartialOverloading) { 10670 10671 #ifndef NDEBUG 10672 // Verify that ArgumentDependentLookup is consistent with the rules 10673 // in C++0x [basic.lookup.argdep]p3: 10674 // 10675 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10676 // and let Y be the lookup set produced by argument dependent 10677 // lookup (defined as follows). If X contains 10678 // 10679 // -- a declaration of a class member, or 10680 // 10681 // -- a block-scope function declaration that is not a 10682 // using-declaration, or 10683 // 10684 // -- a declaration that is neither a function or a function 10685 // template 10686 // 10687 // then Y is empty. 10688 10689 if (ULE->requiresADL()) { 10690 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10691 E = ULE->decls_end(); I != E; ++I) { 10692 assert(!(*I)->getDeclContext()->isRecord()); 10693 assert(isa<UsingShadowDecl>(*I) || 10694 !(*I)->getDeclContext()->isFunctionOrMethod()); 10695 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10696 } 10697 } 10698 #endif 10699 10700 // It would be nice to avoid this copy. 10701 TemplateArgumentListInfo TABuffer; 10702 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10703 if (ULE->hasExplicitTemplateArgs()) { 10704 ULE->copyTemplateArgumentsInto(TABuffer); 10705 ExplicitTemplateArgs = &TABuffer; 10706 } 10707 10708 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10709 E = ULE->decls_end(); I != E; ++I) 10710 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10711 CandidateSet, PartialOverloading, 10712 /*KnownValid*/ true); 10713 10714 if (ULE->requiresADL()) 10715 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10716 Args, ExplicitTemplateArgs, 10717 CandidateSet, PartialOverloading); 10718 } 10719 10720 /// Determine whether a declaration with the specified name could be moved into 10721 /// a different namespace. 10722 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10723 switch (Name.getCXXOverloadedOperator()) { 10724 case OO_New: case OO_Array_New: 10725 case OO_Delete: case OO_Array_Delete: 10726 return false; 10727 10728 default: 10729 return true; 10730 } 10731 } 10732 10733 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10734 /// template, where the non-dependent name was declared after the template 10735 /// was defined. This is common in code written for a compilers which do not 10736 /// correctly implement two-stage name lookup. 10737 /// 10738 /// Returns true if a viable candidate was found and a diagnostic was issued. 10739 static bool 10740 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10741 const CXXScopeSpec &SS, LookupResult &R, 10742 OverloadCandidateSet::CandidateSetKind CSK, 10743 TemplateArgumentListInfo *ExplicitTemplateArgs, 10744 ArrayRef<Expr *> Args, 10745 bool *DoDiagnoseEmptyLookup = nullptr) { 10746 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10747 return false; 10748 10749 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10750 if (DC->isTransparentContext()) 10751 continue; 10752 10753 SemaRef.LookupQualifiedName(R, DC); 10754 10755 if (!R.empty()) { 10756 R.suppressDiagnostics(); 10757 10758 if (isa<CXXRecordDecl>(DC)) { 10759 // Don't diagnose names we find in classes; we get much better 10760 // diagnostics for these from DiagnoseEmptyLookup. 10761 R.clear(); 10762 if (DoDiagnoseEmptyLookup) 10763 *DoDiagnoseEmptyLookup = true; 10764 return false; 10765 } 10766 10767 OverloadCandidateSet Candidates(FnLoc, CSK); 10768 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10769 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10770 ExplicitTemplateArgs, Args, 10771 Candidates, false, /*KnownValid*/ false); 10772 10773 OverloadCandidateSet::iterator Best; 10774 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10775 // No viable functions. Don't bother the user with notes for functions 10776 // which don't work and shouldn't be found anyway. 10777 R.clear(); 10778 return false; 10779 } 10780 10781 // Find the namespaces where ADL would have looked, and suggest 10782 // declaring the function there instead. 10783 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10784 Sema::AssociatedClassSet AssociatedClasses; 10785 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10786 AssociatedNamespaces, 10787 AssociatedClasses); 10788 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10789 if (canBeDeclaredInNamespace(R.getLookupName())) { 10790 DeclContext *Std = SemaRef.getStdNamespace(); 10791 for (Sema::AssociatedNamespaceSet::iterator 10792 it = AssociatedNamespaces.begin(), 10793 end = AssociatedNamespaces.end(); it != end; ++it) { 10794 // Never suggest declaring a function within namespace 'std'. 10795 if (Std && Std->Encloses(*it)) 10796 continue; 10797 10798 // Never suggest declaring a function within a namespace with a 10799 // reserved name, like __gnu_cxx. 10800 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10801 if (NS && 10802 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10803 continue; 10804 10805 SuggestedNamespaces.insert(*it); 10806 } 10807 } 10808 10809 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10810 << R.getLookupName(); 10811 if (SuggestedNamespaces.empty()) { 10812 SemaRef.Diag(Best->Function->getLocation(), 10813 diag::note_not_found_by_two_phase_lookup) 10814 << R.getLookupName() << 0; 10815 } else if (SuggestedNamespaces.size() == 1) { 10816 SemaRef.Diag(Best->Function->getLocation(), 10817 diag::note_not_found_by_two_phase_lookup) 10818 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10819 } else { 10820 // FIXME: It would be useful to list the associated namespaces here, 10821 // but the diagnostics infrastructure doesn't provide a way to produce 10822 // a localized representation of a list of items. 10823 SemaRef.Diag(Best->Function->getLocation(), 10824 diag::note_not_found_by_two_phase_lookup) 10825 << R.getLookupName() << 2; 10826 } 10827 10828 // Try to recover by calling this function. 10829 return true; 10830 } 10831 10832 R.clear(); 10833 } 10834 10835 return false; 10836 } 10837 10838 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10839 /// template, where the non-dependent operator was declared after the template 10840 /// was defined. 10841 /// 10842 /// Returns true if a viable candidate was found and a diagnostic was issued. 10843 static bool 10844 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10845 SourceLocation OpLoc, 10846 ArrayRef<Expr *> Args) { 10847 DeclarationName OpName = 10848 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10849 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10850 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10851 OverloadCandidateSet::CSK_Operator, 10852 /*ExplicitTemplateArgs=*/nullptr, Args); 10853 } 10854 10855 namespace { 10856 class BuildRecoveryCallExprRAII { 10857 Sema &SemaRef; 10858 public: 10859 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10860 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10861 SemaRef.IsBuildingRecoveryCallExpr = true; 10862 } 10863 10864 ~BuildRecoveryCallExprRAII() { 10865 SemaRef.IsBuildingRecoveryCallExpr = false; 10866 } 10867 }; 10868 10869 } 10870 10871 static std::unique_ptr<CorrectionCandidateCallback> 10872 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10873 bool HasTemplateArgs, bool AllowTypoCorrection) { 10874 if (!AllowTypoCorrection) 10875 return llvm::make_unique<NoTypoCorrectionCCC>(); 10876 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10877 HasTemplateArgs, ME); 10878 } 10879 10880 /// Attempts to recover from a call where no functions were found. 10881 /// 10882 /// Returns true if new candidates were found. 10883 static ExprResult 10884 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10885 UnresolvedLookupExpr *ULE, 10886 SourceLocation LParenLoc, 10887 MutableArrayRef<Expr *> Args, 10888 SourceLocation RParenLoc, 10889 bool EmptyLookup, bool AllowTypoCorrection) { 10890 // Do not try to recover if it is already building a recovery call. 10891 // This stops infinite loops for template instantiations like 10892 // 10893 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10894 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10895 // 10896 if (SemaRef.IsBuildingRecoveryCallExpr) 10897 return ExprError(); 10898 BuildRecoveryCallExprRAII RCE(SemaRef); 10899 10900 CXXScopeSpec SS; 10901 SS.Adopt(ULE->getQualifierLoc()); 10902 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10903 10904 TemplateArgumentListInfo TABuffer; 10905 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10906 if (ULE->hasExplicitTemplateArgs()) { 10907 ULE->copyTemplateArgumentsInto(TABuffer); 10908 ExplicitTemplateArgs = &TABuffer; 10909 } 10910 10911 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10912 Sema::LookupOrdinaryName); 10913 bool DoDiagnoseEmptyLookup = EmptyLookup; 10914 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10915 OverloadCandidateSet::CSK_Normal, 10916 ExplicitTemplateArgs, Args, 10917 &DoDiagnoseEmptyLookup) && 10918 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 10919 S, SS, R, 10920 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 10921 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 10922 ExplicitTemplateArgs, Args))) 10923 return ExprError(); 10924 10925 assert(!R.empty() && "lookup results empty despite recovery"); 10926 10927 // Build an implicit member call if appropriate. Just drop the 10928 // casts and such from the call, we don't really care. 10929 ExprResult NewFn = ExprError(); 10930 if ((*R.begin())->isCXXClassMember()) 10931 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 10932 ExplicitTemplateArgs, S); 10933 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10934 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10935 ExplicitTemplateArgs); 10936 else 10937 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10938 10939 if (NewFn.isInvalid()) 10940 return ExprError(); 10941 10942 // This shouldn't cause an infinite loop because we're giving it 10943 // an expression with viable lookup results, which should never 10944 // end up here. 10945 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10946 MultiExprArg(Args.data(), Args.size()), 10947 RParenLoc); 10948 } 10949 10950 /// \brief Constructs and populates an OverloadedCandidateSet from 10951 /// the given function. 10952 /// \returns true when an the ExprResult output parameter has been set. 10953 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10954 UnresolvedLookupExpr *ULE, 10955 MultiExprArg Args, 10956 SourceLocation RParenLoc, 10957 OverloadCandidateSet *CandidateSet, 10958 ExprResult *Result) { 10959 #ifndef NDEBUG 10960 if (ULE->requiresADL()) { 10961 // To do ADL, we must have found an unqualified name. 10962 assert(!ULE->getQualifier() && "qualified name with ADL"); 10963 10964 // We don't perform ADL for implicit declarations of builtins. 10965 // Verify that this was correctly set up. 10966 FunctionDecl *F; 10967 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10968 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10969 F->getBuiltinID() && F->isImplicit()) 10970 llvm_unreachable("performing ADL for builtin"); 10971 10972 // We don't perform ADL in C. 10973 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10974 } 10975 #endif 10976 10977 UnbridgedCastsSet UnbridgedCasts; 10978 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10979 *Result = ExprError(); 10980 return true; 10981 } 10982 10983 // Add the functions denoted by the callee to the set of candidate 10984 // functions, including those from argument-dependent lookup. 10985 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10986 10987 if (getLangOpts().MSVCCompat && 10988 CurContext->isDependentContext() && !isSFINAEContext() && 10989 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10990 10991 OverloadCandidateSet::iterator Best; 10992 if (CandidateSet->empty() || 10993 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 10994 OR_No_Viable_Function) { 10995 // In Microsoft mode, if we are inside a template class member function then 10996 // create a type dependent CallExpr. The goal is to postpone name lookup 10997 // to instantiation time to be able to search into type dependent base 10998 // classes. 10999 CallExpr *CE = new (Context) CallExpr( 11000 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11001 CE->setTypeDependent(true); 11002 CE->setValueDependent(true); 11003 CE->setInstantiationDependent(true); 11004 *Result = CE; 11005 return true; 11006 } 11007 } 11008 11009 if (CandidateSet->empty()) 11010 return false; 11011 11012 UnbridgedCasts.restore(); 11013 return false; 11014 } 11015 11016 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11017 /// the completed call expression. If overload resolution fails, emits 11018 /// diagnostics and returns ExprError() 11019 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11020 UnresolvedLookupExpr *ULE, 11021 SourceLocation LParenLoc, 11022 MultiExprArg Args, 11023 SourceLocation RParenLoc, 11024 Expr *ExecConfig, 11025 OverloadCandidateSet *CandidateSet, 11026 OverloadCandidateSet::iterator *Best, 11027 OverloadingResult OverloadResult, 11028 bool AllowTypoCorrection) { 11029 if (CandidateSet->empty()) 11030 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11031 RParenLoc, /*EmptyLookup=*/true, 11032 AllowTypoCorrection); 11033 11034 switch (OverloadResult) { 11035 case OR_Success: { 11036 FunctionDecl *FDecl = (*Best)->Function; 11037 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11038 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11039 return ExprError(); 11040 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11041 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11042 ExecConfig); 11043 } 11044 11045 case OR_No_Viable_Function: { 11046 // Try to recover by looking for viable functions which the user might 11047 // have meant to call. 11048 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11049 Args, RParenLoc, 11050 /*EmptyLookup=*/false, 11051 AllowTypoCorrection); 11052 if (!Recovery.isInvalid()) 11053 return Recovery; 11054 11055 SemaRef.Diag(Fn->getLocStart(), 11056 diag::err_ovl_no_viable_function_in_call) 11057 << ULE->getName() << Fn->getSourceRange(); 11058 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11059 break; 11060 } 11061 11062 case OR_Ambiguous: 11063 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11064 << ULE->getName() << Fn->getSourceRange(); 11065 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11066 break; 11067 11068 case OR_Deleted: { 11069 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11070 << (*Best)->Function->isDeleted() 11071 << ULE->getName() 11072 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11073 << Fn->getSourceRange(); 11074 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11075 11076 // We emitted an error for the unvailable/deleted function call but keep 11077 // the call in the AST. 11078 FunctionDecl *FDecl = (*Best)->Function; 11079 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11080 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11081 ExecConfig); 11082 } 11083 } 11084 11085 // Overload resolution failed. 11086 return ExprError(); 11087 } 11088 11089 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11090 /// (which eventually refers to the declaration Func) and the call 11091 /// arguments Args/NumArgs, attempt to resolve the function call down 11092 /// to a specific function. If overload resolution succeeds, returns 11093 /// the call expression produced by overload resolution. 11094 /// Otherwise, emits diagnostics and returns ExprError. 11095 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11096 UnresolvedLookupExpr *ULE, 11097 SourceLocation LParenLoc, 11098 MultiExprArg Args, 11099 SourceLocation RParenLoc, 11100 Expr *ExecConfig, 11101 bool AllowTypoCorrection) { 11102 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11103 OverloadCandidateSet::CSK_Normal); 11104 ExprResult result; 11105 11106 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11107 &result)) 11108 return result; 11109 11110 OverloadCandidateSet::iterator Best; 11111 OverloadingResult OverloadResult = 11112 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11113 11114 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11115 RParenLoc, ExecConfig, &CandidateSet, 11116 &Best, OverloadResult, 11117 AllowTypoCorrection); 11118 } 11119 11120 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11121 return Functions.size() > 1 || 11122 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11123 } 11124 11125 /// \brief Create a unary operation that may resolve to an overloaded 11126 /// operator. 11127 /// 11128 /// \param OpLoc The location of the operator itself (e.g., '*'). 11129 /// 11130 /// \param OpcIn The UnaryOperator::Opcode that describes this 11131 /// operator. 11132 /// 11133 /// \param Fns The set of non-member functions that will be 11134 /// considered by overload resolution. The caller needs to build this 11135 /// set based on the context using, e.g., 11136 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11137 /// set should not contain any member functions; those will be added 11138 /// by CreateOverloadedUnaryOp(). 11139 /// 11140 /// \param Input The input argument. 11141 ExprResult 11142 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 11143 const UnresolvedSetImpl &Fns, 11144 Expr *Input) { 11145 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 11146 11147 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11148 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11149 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11150 // TODO: provide better source location info. 11151 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11152 11153 if (checkPlaceholderForOverload(*this, Input)) 11154 return ExprError(); 11155 11156 Expr *Args[2] = { Input, nullptr }; 11157 unsigned NumArgs = 1; 11158 11159 // For post-increment and post-decrement, add the implicit '0' as 11160 // the second argument, so that we know this is a post-increment or 11161 // post-decrement. 11162 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11163 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11164 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11165 SourceLocation()); 11166 NumArgs = 2; 11167 } 11168 11169 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11170 11171 if (Input->isTypeDependent()) { 11172 if (Fns.empty()) 11173 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11174 VK_RValue, OK_Ordinary, OpLoc); 11175 11176 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11177 UnresolvedLookupExpr *Fn 11178 = UnresolvedLookupExpr::Create(Context, NamingClass, 11179 NestedNameSpecifierLoc(), OpNameInfo, 11180 /*ADL*/ true, IsOverloaded(Fns), 11181 Fns.begin(), Fns.end()); 11182 return new (Context) 11183 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11184 VK_RValue, OpLoc, false); 11185 } 11186 11187 // Build an empty overload set. 11188 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11189 11190 // Add the candidates from the given function set. 11191 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11192 11193 // Add operator candidates that are member functions. 11194 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11195 11196 // Add candidates from ADL. 11197 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11198 /*ExplicitTemplateArgs*/nullptr, 11199 CandidateSet); 11200 11201 // Add builtin operator candidates. 11202 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11203 11204 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11205 11206 // Perform overload resolution. 11207 OverloadCandidateSet::iterator Best; 11208 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11209 case OR_Success: { 11210 // We found a built-in operator or an overloaded operator. 11211 FunctionDecl *FnDecl = Best->Function; 11212 11213 if (FnDecl) { 11214 // We matched an overloaded operator. Build a call to that 11215 // operator. 11216 11217 // Convert the arguments. 11218 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11219 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11220 11221 ExprResult InputRes = 11222 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11223 Best->FoundDecl, Method); 11224 if (InputRes.isInvalid()) 11225 return ExprError(); 11226 Input = InputRes.get(); 11227 } else { 11228 // Convert the arguments. 11229 ExprResult InputInit 11230 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11231 Context, 11232 FnDecl->getParamDecl(0)), 11233 SourceLocation(), 11234 Input); 11235 if (InputInit.isInvalid()) 11236 return ExprError(); 11237 Input = InputInit.get(); 11238 } 11239 11240 // Build the actual expression node. 11241 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11242 HadMultipleCandidates, OpLoc); 11243 if (FnExpr.isInvalid()) 11244 return ExprError(); 11245 11246 // Determine the result type. 11247 QualType ResultTy = FnDecl->getReturnType(); 11248 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11249 ResultTy = ResultTy.getNonLValueExprType(Context); 11250 11251 Args[0] = Input; 11252 CallExpr *TheCall = 11253 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11254 ResultTy, VK, OpLoc, false); 11255 11256 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11257 return ExprError(); 11258 11259 return MaybeBindToTemporary(TheCall); 11260 } else { 11261 // We matched a built-in operator. Convert the arguments, then 11262 // break out so that we will build the appropriate built-in 11263 // operator node. 11264 ExprResult InputRes = 11265 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11266 Best->Conversions[0], AA_Passing); 11267 if (InputRes.isInvalid()) 11268 return ExprError(); 11269 Input = InputRes.get(); 11270 break; 11271 } 11272 } 11273 11274 case OR_No_Viable_Function: 11275 // This is an erroneous use of an operator which can be overloaded by 11276 // a non-member function. Check for non-member operators which were 11277 // defined too late to be candidates. 11278 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11279 // FIXME: Recover by calling the found function. 11280 return ExprError(); 11281 11282 // No viable function; fall through to handling this as a 11283 // built-in operator, which will produce an error message for us. 11284 break; 11285 11286 case OR_Ambiguous: 11287 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11288 << UnaryOperator::getOpcodeStr(Opc) 11289 << Input->getType() 11290 << Input->getSourceRange(); 11291 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11292 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11293 return ExprError(); 11294 11295 case OR_Deleted: 11296 Diag(OpLoc, diag::err_ovl_deleted_oper) 11297 << Best->Function->isDeleted() 11298 << UnaryOperator::getOpcodeStr(Opc) 11299 << getDeletedOrUnavailableSuffix(Best->Function) 11300 << Input->getSourceRange(); 11301 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11302 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11303 return ExprError(); 11304 } 11305 11306 // Either we found no viable overloaded operator or we matched a 11307 // built-in operator. In either case, fall through to trying to 11308 // build a built-in operation. 11309 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11310 } 11311 11312 /// \brief Create a binary operation that may resolve to an overloaded 11313 /// operator. 11314 /// 11315 /// \param OpLoc The location of the operator itself (e.g., '+'). 11316 /// 11317 /// \param OpcIn The BinaryOperator::Opcode that describes this 11318 /// operator. 11319 /// 11320 /// \param Fns The set of non-member functions that will be 11321 /// considered by overload resolution. The caller needs to build this 11322 /// set based on the context using, e.g., 11323 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11324 /// set should not contain any member functions; those will be added 11325 /// by CreateOverloadedBinOp(). 11326 /// 11327 /// \param LHS Left-hand argument. 11328 /// \param RHS Right-hand argument. 11329 ExprResult 11330 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11331 unsigned OpcIn, 11332 const UnresolvedSetImpl &Fns, 11333 Expr *LHS, Expr *RHS) { 11334 Expr *Args[2] = { LHS, RHS }; 11335 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11336 11337 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11338 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11339 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11340 11341 // If either side is type-dependent, create an appropriate dependent 11342 // expression. 11343 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11344 if (Fns.empty()) { 11345 // If there are no functions to store, just build a dependent 11346 // BinaryOperator or CompoundAssignment. 11347 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11348 return new (Context) BinaryOperator( 11349 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11350 OpLoc, FPFeatures.fp_contract); 11351 11352 return new (Context) CompoundAssignOperator( 11353 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11354 Context.DependentTy, Context.DependentTy, OpLoc, 11355 FPFeatures.fp_contract); 11356 } 11357 11358 // FIXME: save results of ADL from here? 11359 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11360 // TODO: provide better source location info in DNLoc component. 11361 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11362 UnresolvedLookupExpr *Fn 11363 = UnresolvedLookupExpr::Create(Context, NamingClass, 11364 NestedNameSpecifierLoc(), OpNameInfo, 11365 /*ADL*/ true, IsOverloaded(Fns), 11366 Fns.begin(), Fns.end()); 11367 return new (Context) 11368 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11369 VK_RValue, OpLoc, FPFeatures.fp_contract); 11370 } 11371 11372 // Always do placeholder-like conversions on the RHS. 11373 if (checkPlaceholderForOverload(*this, Args[1])) 11374 return ExprError(); 11375 11376 // Do placeholder-like conversion on the LHS; note that we should 11377 // not get here with a PseudoObject LHS. 11378 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11379 if (checkPlaceholderForOverload(*this, Args[0])) 11380 return ExprError(); 11381 11382 // If this is the assignment operator, we only perform overload resolution 11383 // if the left-hand side is a class or enumeration type. This is actually 11384 // a hack. The standard requires that we do overload resolution between the 11385 // various built-in candidates, but as DR507 points out, this can lead to 11386 // problems. So we do it this way, which pretty much follows what GCC does. 11387 // Note that we go the traditional code path for compound assignment forms. 11388 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11389 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11390 11391 // If this is the .* operator, which is not overloadable, just 11392 // create a built-in binary operator. 11393 if (Opc == BO_PtrMemD) 11394 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11395 11396 // Build an empty overload set. 11397 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11398 11399 // Add the candidates from the given function set. 11400 AddFunctionCandidates(Fns, Args, CandidateSet); 11401 11402 // Add operator candidates that are member functions. 11403 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11404 11405 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11406 // performed for an assignment operator (nor for operator[] nor operator->, 11407 // which don't get here). 11408 if (Opc != BO_Assign) 11409 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11410 /*ExplicitTemplateArgs*/ nullptr, 11411 CandidateSet); 11412 11413 // Add builtin operator candidates. 11414 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11415 11416 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11417 11418 // Perform overload resolution. 11419 OverloadCandidateSet::iterator Best; 11420 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11421 case OR_Success: { 11422 // We found a built-in operator or an overloaded operator. 11423 FunctionDecl *FnDecl = Best->Function; 11424 11425 if (FnDecl) { 11426 // We matched an overloaded operator. Build a call to that 11427 // operator. 11428 11429 // Convert the arguments. 11430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11431 // Best->Access is only meaningful for class members. 11432 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11433 11434 ExprResult Arg1 = 11435 PerformCopyInitialization( 11436 InitializedEntity::InitializeParameter(Context, 11437 FnDecl->getParamDecl(0)), 11438 SourceLocation(), Args[1]); 11439 if (Arg1.isInvalid()) 11440 return ExprError(); 11441 11442 ExprResult Arg0 = 11443 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11444 Best->FoundDecl, Method); 11445 if (Arg0.isInvalid()) 11446 return ExprError(); 11447 Args[0] = Arg0.getAs<Expr>(); 11448 Args[1] = RHS = Arg1.getAs<Expr>(); 11449 } else { 11450 // Convert the arguments. 11451 ExprResult Arg0 = PerformCopyInitialization( 11452 InitializedEntity::InitializeParameter(Context, 11453 FnDecl->getParamDecl(0)), 11454 SourceLocation(), Args[0]); 11455 if (Arg0.isInvalid()) 11456 return ExprError(); 11457 11458 ExprResult Arg1 = 11459 PerformCopyInitialization( 11460 InitializedEntity::InitializeParameter(Context, 11461 FnDecl->getParamDecl(1)), 11462 SourceLocation(), Args[1]); 11463 if (Arg1.isInvalid()) 11464 return ExprError(); 11465 Args[0] = LHS = Arg0.getAs<Expr>(); 11466 Args[1] = RHS = Arg1.getAs<Expr>(); 11467 } 11468 11469 // Build the actual expression node. 11470 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11471 Best->FoundDecl, 11472 HadMultipleCandidates, OpLoc); 11473 if (FnExpr.isInvalid()) 11474 return ExprError(); 11475 11476 // Determine the result type. 11477 QualType ResultTy = FnDecl->getReturnType(); 11478 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11479 ResultTy = ResultTy.getNonLValueExprType(Context); 11480 11481 CXXOperatorCallExpr *TheCall = 11482 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11483 Args, ResultTy, VK, OpLoc, 11484 FPFeatures.fp_contract); 11485 11486 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11487 FnDecl)) 11488 return ExprError(); 11489 11490 ArrayRef<const Expr *> ArgsArray(Args, 2); 11491 // Cut off the implicit 'this'. 11492 if (isa<CXXMethodDecl>(FnDecl)) 11493 ArgsArray = ArgsArray.slice(1); 11494 11495 // Check for a self move. 11496 if (Op == OO_Equal) 11497 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11498 11499 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11500 TheCall->getSourceRange(), VariadicDoesNotApply); 11501 11502 return MaybeBindToTemporary(TheCall); 11503 } else { 11504 // We matched a built-in operator. Convert the arguments, then 11505 // break out so that we will build the appropriate built-in 11506 // operator node. 11507 ExprResult ArgsRes0 = 11508 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11509 Best->Conversions[0], AA_Passing); 11510 if (ArgsRes0.isInvalid()) 11511 return ExprError(); 11512 Args[0] = ArgsRes0.get(); 11513 11514 ExprResult ArgsRes1 = 11515 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11516 Best->Conversions[1], AA_Passing); 11517 if (ArgsRes1.isInvalid()) 11518 return ExprError(); 11519 Args[1] = ArgsRes1.get(); 11520 break; 11521 } 11522 } 11523 11524 case OR_No_Viable_Function: { 11525 // C++ [over.match.oper]p9: 11526 // If the operator is the operator , [...] and there are no 11527 // viable functions, then the operator is assumed to be the 11528 // built-in operator and interpreted according to clause 5. 11529 if (Opc == BO_Comma) 11530 break; 11531 11532 // For class as left operand for assignment or compound assigment 11533 // operator do not fall through to handling in built-in, but report that 11534 // no overloaded assignment operator found 11535 ExprResult Result = ExprError(); 11536 if (Args[0]->getType()->isRecordType() && 11537 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11538 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11539 << BinaryOperator::getOpcodeStr(Opc) 11540 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11541 if (Args[0]->getType()->isIncompleteType()) { 11542 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11543 << Args[0]->getType() 11544 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11545 } 11546 } else { 11547 // This is an erroneous use of an operator which can be overloaded by 11548 // a non-member function. Check for non-member operators which were 11549 // defined too late to be candidates. 11550 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11551 // FIXME: Recover by calling the found function. 11552 return ExprError(); 11553 11554 // No viable function; try to create a built-in operation, which will 11555 // produce an error. Then, show the non-viable candidates. 11556 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11557 } 11558 assert(Result.isInvalid() && 11559 "C++ binary operator overloading is missing candidates!"); 11560 if (Result.isInvalid()) 11561 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11562 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11563 return Result; 11564 } 11565 11566 case OR_Ambiguous: 11567 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11568 << BinaryOperator::getOpcodeStr(Opc) 11569 << Args[0]->getType() << Args[1]->getType() 11570 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11571 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11572 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11573 return ExprError(); 11574 11575 case OR_Deleted: 11576 if (isImplicitlyDeleted(Best->Function)) { 11577 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11578 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11579 << Context.getRecordType(Method->getParent()) 11580 << getSpecialMember(Method); 11581 11582 // The user probably meant to call this special member. Just 11583 // explain why it's deleted. 11584 NoteDeletedFunction(Method); 11585 return ExprError(); 11586 } else { 11587 Diag(OpLoc, diag::err_ovl_deleted_oper) 11588 << Best->Function->isDeleted() 11589 << BinaryOperator::getOpcodeStr(Opc) 11590 << getDeletedOrUnavailableSuffix(Best->Function) 11591 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11592 } 11593 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11594 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11595 return ExprError(); 11596 } 11597 11598 // We matched a built-in operator; build it. 11599 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11600 } 11601 11602 ExprResult 11603 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11604 SourceLocation RLoc, 11605 Expr *Base, Expr *Idx) { 11606 Expr *Args[2] = { Base, Idx }; 11607 DeclarationName OpName = 11608 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11609 11610 // If either side is type-dependent, create an appropriate dependent 11611 // expression. 11612 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11613 11614 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11615 // CHECKME: no 'operator' keyword? 11616 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11617 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11618 UnresolvedLookupExpr *Fn 11619 = UnresolvedLookupExpr::Create(Context, NamingClass, 11620 NestedNameSpecifierLoc(), OpNameInfo, 11621 /*ADL*/ true, /*Overloaded*/ false, 11622 UnresolvedSetIterator(), 11623 UnresolvedSetIterator()); 11624 // Can't add any actual overloads yet 11625 11626 return new (Context) 11627 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11628 Context.DependentTy, VK_RValue, RLoc, false); 11629 } 11630 11631 // Handle placeholders on both operands. 11632 if (checkPlaceholderForOverload(*this, Args[0])) 11633 return ExprError(); 11634 if (checkPlaceholderForOverload(*this, Args[1])) 11635 return ExprError(); 11636 11637 // Build an empty overload set. 11638 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11639 11640 // Subscript can only be overloaded as a member function. 11641 11642 // Add operator candidates that are member functions. 11643 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11644 11645 // Add builtin operator candidates. 11646 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11647 11648 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11649 11650 // Perform overload resolution. 11651 OverloadCandidateSet::iterator Best; 11652 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11653 case OR_Success: { 11654 // We found a built-in operator or an overloaded operator. 11655 FunctionDecl *FnDecl = Best->Function; 11656 11657 if (FnDecl) { 11658 // We matched an overloaded operator. Build a call to that 11659 // operator. 11660 11661 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11662 11663 // Convert the arguments. 11664 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11665 ExprResult Arg0 = 11666 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11667 Best->FoundDecl, Method); 11668 if (Arg0.isInvalid()) 11669 return ExprError(); 11670 Args[0] = Arg0.get(); 11671 11672 // Convert the arguments. 11673 ExprResult InputInit 11674 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11675 Context, 11676 FnDecl->getParamDecl(0)), 11677 SourceLocation(), 11678 Args[1]); 11679 if (InputInit.isInvalid()) 11680 return ExprError(); 11681 11682 Args[1] = InputInit.getAs<Expr>(); 11683 11684 // Build the actual expression node. 11685 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11686 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11687 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11688 Best->FoundDecl, 11689 HadMultipleCandidates, 11690 OpLocInfo.getLoc(), 11691 OpLocInfo.getInfo()); 11692 if (FnExpr.isInvalid()) 11693 return ExprError(); 11694 11695 // Determine the result type 11696 QualType ResultTy = FnDecl->getReturnType(); 11697 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11698 ResultTy = ResultTy.getNonLValueExprType(Context); 11699 11700 CXXOperatorCallExpr *TheCall = 11701 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11702 FnExpr.get(), Args, 11703 ResultTy, VK, RLoc, 11704 false); 11705 11706 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11707 return ExprError(); 11708 11709 return MaybeBindToTemporary(TheCall); 11710 } else { 11711 // We matched a built-in operator. Convert the arguments, then 11712 // break out so that we will build the appropriate built-in 11713 // operator node. 11714 ExprResult ArgsRes0 = 11715 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11716 Best->Conversions[0], AA_Passing); 11717 if (ArgsRes0.isInvalid()) 11718 return ExprError(); 11719 Args[0] = ArgsRes0.get(); 11720 11721 ExprResult ArgsRes1 = 11722 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11723 Best->Conversions[1], AA_Passing); 11724 if (ArgsRes1.isInvalid()) 11725 return ExprError(); 11726 Args[1] = ArgsRes1.get(); 11727 11728 break; 11729 } 11730 } 11731 11732 case OR_No_Viable_Function: { 11733 if (CandidateSet.empty()) 11734 Diag(LLoc, diag::err_ovl_no_oper) 11735 << Args[0]->getType() << /*subscript*/ 0 11736 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11737 else 11738 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11739 << Args[0]->getType() 11740 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11741 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11742 "[]", LLoc); 11743 return ExprError(); 11744 } 11745 11746 case OR_Ambiguous: 11747 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11748 << "[]" 11749 << Args[0]->getType() << Args[1]->getType() 11750 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11751 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11752 "[]", LLoc); 11753 return ExprError(); 11754 11755 case OR_Deleted: 11756 Diag(LLoc, diag::err_ovl_deleted_oper) 11757 << Best->Function->isDeleted() << "[]" 11758 << getDeletedOrUnavailableSuffix(Best->Function) 11759 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11760 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11761 "[]", LLoc); 11762 return ExprError(); 11763 } 11764 11765 // We matched a built-in operator; build it. 11766 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11767 } 11768 11769 /// BuildCallToMemberFunction - Build a call to a member 11770 /// function. MemExpr is the expression that refers to the member 11771 /// function (and includes the object parameter), Args/NumArgs are the 11772 /// arguments to the function call (not including the object 11773 /// parameter). The caller needs to validate that the member 11774 /// expression refers to a non-static member function or an overloaded 11775 /// member function. 11776 ExprResult 11777 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11778 SourceLocation LParenLoc, 11779 MultiExprArg Args, 11780 SourceLocation RParenLoc) { 11781 assert(MemExprE->getType() == Context.BoundMemberTy || 11782 MemExprE->getType() == Context.OverloadTy); 11783 11784 // Dig out the member expression. This holds both the object 11785 // argument and the member function we're referring to. 11786 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11787 11788 // Determine whether this is a call to a pointer-to-member function. 11789 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11790 assert(op->getType() == Context.BoundMemberTy); 11791 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11792 11793 QualType fnType = 11794 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11795 11796 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11797 QualType resultType = proto->getCallResultType(Context); 11798 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11799 11800 // Check that the object type isn't more qualified than the 11801 // member function we're calling. 11802 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11803 11804 QualType objectType = op->getLHS()->getType(); 11805 if (op->getOpcode() == BO_PtrMemI) 11806 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11807 Qualifiers objectQuals = objectType.getQualifiers(); 11808 11809 Qualifiers difference = objectQuals - funcQuals; 11810 difference.removeObjCGCAttr(); 11811 difference.removeAddressSpace(); 11812 if (difference) { 11813 std::string qualsString = difference.getAsString(); 11814 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11815 << fnType.getUnqualifiedType() 11816 << qualsString 11817 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11818 } 11819 11820 CXXMemberCallExpr *call 11821 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11822 resultType, valueKind, RParenLoc); 11823 11824 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11825 call, nullptr)) 11826 return ExprError(); 11827 11828 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11829 return ExprError(); 11830 11831 if (CheckOtherCall(call, proto)) 11832 return ExprError(); 11833 11834 return MaybeBindToTemporary(call); 11835 } 11836 11837 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 11838 return new (Context) 11839 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 11840 11841 UnbridgedCastsSet UnbridgedCasts; 11842 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11843 return ExprError(); 11844 11845 MemberExpr *MemExpr; 11846 CXXMethodDecl *Method = nullptr; 11847 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11848 NestedNameSpecifier *Qualifier = nullptr; 11849 if (isa<MemberExpr>(NakedMemExpr)) { 11850 MemExpr = cast<MemberExpr>(NakedMemExpr); 11851 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11852 FoundDecl = MemExpr->getFoundDecl(); 11853 Qualifier = MemExpr->getQualifier(); 11854 UnbridgedCasts.restore(); 11855 } else { 11856 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11857 Qualifier = UnresExpr->getQualifier(); 11858 11859 QualType ObjectType = UnresExpr->getBaseType(); 11860 Expr::Classification ObjectClassification 11861 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11862 : UnresExpr->getBase()->Classify(Context); 11863 11864 // Add overload candidates 11865 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11866 OverloadCandidateSet::CSK_Normal); 11867 11868 // FIXME: avoid copy. 11869 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11870 if (UnresExpr->hasExplicitTemplateArgs()) { 11871 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11872 TemplateArgs = &TemplateArgsBuffer; 11873 } 11874 11875 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11876 E = UnresExpr->decls_end(); I != E; ++I) { 11877 11878 NamedDecl *Func = *I; 11879 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11880 if (isa<UsingShadowDecl>(Func)) 11881 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11882 11883 11884 // Microsoft supports direct constructor calls. 11885 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11886 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11887 Args, CandidateSet); 11888 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11889 // If explicit template arguments were provided, we can't call a 11890 // non-template member function. 11891 if (TemplateArgs) 11892 continue; 11893 11894 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11895 ObjectClassification, Args, CandidateSet, 11896 /*SuppressUserConversions=*/false); 11897 } else { 11898 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11899 I.getPair(), ActingDC, TemplateArgs, 11900 ObjectType, ObjectClassification, 11901 Args, CandidateSet, 11902 /*SuppressUsedConversions=*/false); 11903 } 11904 } 11905 11906 DeclarationName DeclName = UnresExpr->getMemberName(); 11907 11908 UnbridgedCasts.restore(); 11909 11910 OverloadCandidateSet::iterator Best; 11911 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11912 Best)) { 11913 case OR_Success: 11914 Method = cast<CXXMethodDecl>(Best->Function); 11915 FoundDecl = Best->FoundDecl; 11916 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11917 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11918 return ExprError(); 11919 // If FoundDecl is different from Method (such as if one is a template 11920 // and the other a specialization), make sure DiagnoseUseOfDecl is 11921 // called on both. 11922 // FIXME: This would be more comprehensively addressed by modifying 11923 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11924 // being used. 11925 if (Method != FoundDecl.getDecl() && 11926 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11927 return ExprError(); 11928 break; 11929 11930 case OR_No_Viable_Function: 11931 Diag(UnresExpr->getMemberLoc(), 11932 diag::err_ovl_no_viable_member_function_in_call) 11933 << DeclName << MemExprE->getSourceRange(); 11934 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11935 // FIXME: Leaking incoming expressions! 11936 return ExprError(); 11937 11938 case OR_Ambiguous: 11939 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11940 << DeclName << MemExprE->getSourceRange(); 11941 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11942 // FIXME: Leaking incoming expressions! 11943 return ExprError(); 11944 11945 case OR_Deleted: 11946 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11947 << Best->Function->isDeleted() 11948 << DeclName 11949 << getDeletedOrUnavailableSuffix(Best->Function) 11950 << MemExprE->getSourceRange(); 11951 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11952 // FIXME: Leaking incoming expressions! 11953 return ExprError(); 11954 } 11955 11956 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11957 11958 // If overload resolution picked a static member, build a 11959 // non-member call based on that function. 11960 if (Method->isStatic()) { 11961 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11962 RParenLoc); 11963 } 11964 11965 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11966 } 11967 11968 QualType ResultType = Method->getReturnType(); 11969 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11970 ResultType = ResultType.getNonLValueExprType(Context); 11971 11972 assert(Method && "Member call to something that isn't a method?"); 11973 CXXMemberCallExpr *TheCall = 11974 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11975 ResultType, VK, RParenLoc); 11976 11977 // (CUDA B.1): Check for invalid calls between targets. 11978 if (getLangOpts().CUDA) { 11979 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11980 if (CheckCUDATarget(Caller, Method)) { 11981 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11982 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11983 << IdentifyCUDATarget(Caller); 11984 return ExprError(); 11985 } 11986 } 11987 } 11988 11989 // Check for a valid return type. 11990 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11991 TheCall, Method)) 11992 return ExprError(); 11993 11994 // Convert the object argument (for a non-static member function call). 11995 // We only need to do this if there was actually an overload; otherwise 11996 // it was done at lookup. 11997 if (!Method->isStatic()) { 11998 ExprResult ObjectArg = 11999 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12000 FoundDecl, Method); 12001 if (ObjectArg.isInvalid()) 12002 return ExprError(); 12003 MemExpr->setBase(ObjectArg.get()); 12004 } 12005 12006 // Convert the rest of the arguments 12007 const FunctionProtoType *Proto = 12008 Method->getType()->getAs<FunctionProtoType>(); 12009 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12010 RParenLoc)) 12011 return ExprError(); 12012 12013 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12014 12015 if (CheckFunctionCall(Method, TheCall, Proto)) 12016 return ExprError(); 12017 12018 // In the case the method to call was not selected by the overloading 12019 // resolution process, we still need to handle the enable_if attribute. Do 12020 // that here, so it will not hide previous -- and more relevant -- errors 12021 if (isa<MemberExpr>(NakedMemExpr)) { 12022 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12023 Diag(MemExprE->getLocStart(), 12024 diag::err_ovl_no_viable_member_function_in_call) 12025 << Method << Method->getSourceRange(); 12026 Diag(Method->getLocation(), 12027 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12028 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12029 return ExprError(); 12030 } 12031 } 12032 12033 if ((isa<CXXConstructorDecl>(CurContext) || 12034 isa<CXXDestructorDecl>(CurContext)) && 12035 TheCall->getMethodDecl()->isPure()) { 12036 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12037 12038 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12039 MemExpr->performsVirtualDispatch(getLangOpts())) { 12040 Diag(MemExpr->getLocStart(), 12041 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12042 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12043 << MD->getParent()->getDeclName(); 12044 12045 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12046 if (getLangOpts().AppleKext) 12047 Diag(MemExpr->getLocStart(), 12048 diag::note_pure_qualified_call_kext) 12049 << MD->getParent()->getDeclName() 12050 << MD->getDeclName(); 12051 } 12052 } 12053 return MaybeBindToTemporary(TheCall); 12054 } 12055 12056 /// BuildCallToObjectOfClassType - Build a call to an object of class 12057 /// type (C++ [over.call.object]), which can end up invoking an 12058 /// overloaded function call operator (@c operator()) or performing a 12059 /// user-defined conversion on the object argument. 12060 ExprResult 12061 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12062 SourceLocation LParenLoc, 12063 MultiExprArg Args, 12064 SourceLocation RParenLoc) { 12065 if (checkPlaceholderForOverload(*this, Obj)) 12066 return ExprError(); 12067 ExprResult Object = Obj; 12068 12069 UnbridgedCastsSet UnbridgedCasts; 12070 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12071 return ExprError(); 12072 12073 assert(Object.get()->getType()->isRecordType() && 12074 "Requires object type argument"); 12075 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12076 12077 // C++ [over.call.object]p1: 12078 // If the primary-expression E in the function call syntax 12079 // evaluates to a class object of type "cv T", then the set of 12080 // candidate functions includes at least the function call 12081 // operators of T. The function call operators of T are obtained by 12082 // ordinary lookup of the name operator() in the context of 12083 // (E).operator(). 12084 OverloadCandidateSet CandidateSet(LParenLoc, 12085 OverloadCandidateSet::CSK_Operator); 12086 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12087 12088 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12089 diag::err_incomplete_object_call, Object.get())) 12090 return true; 12091 12092 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12093 LookupQualifiedName(R, Record->getDecl()); 12094 R.suppressDiagnostics(); 12095 12096 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12097 Oper != OperEnd; ++Oper) { 12098 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12099 Object.get()->Classify(Context), 12100 Args, CandidateSet, 12101 /*SuppressUserConversions=*/ false); 12102 } 12103 12104 // C++ [over.call.object]p2: 12105 // In addition, for each (non-explicit in C++0x) conversion function 12106 // declared in T of the form 12107 // 12108 // operator conversion-type-id () cv-qualifier; 12109 // 12110 // where cv-qualifier is the same cv-qualification as, or a 12111 // greater cv-qualification than, cv, and where conversion-type-id 12112 // denotes the type "pointer to function of (P1,...,Pn) returning 12113 // R", or the type "reference to pointer to function of 12114 // (P1,...,Pn) returning R", or the type "reference to function 12115 // of (P1,...,Pn) returning R", a surrogate call function [...] 12116 // is also considered as a candidate function. Similarly, 12117 // surrogate call functions are added to the set of candidate 12118 // functions for each conversion function declared in an 12119 // accessible base class provided the function is not hidden 12120 // within T by another intervening declaration. 12121 const auto &Conversions = 12122 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12123 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12124 NamedDecl *D = *I; 12125 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12126 if (isa<UsingShadowDecl>(D)) 12127 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12128 12129 // Skip over templated conversion functions; they aren't 12130 // surrogates. 12131 if (isa<FunctionTemplateDecl>(D)) 12132 continue; 12133 12134 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12135 if (!Conv->isExplicit()) { 12136 // Strip the reference type (if any) and then the pointer type (if 12137 // any) to get down to what might be a function type. 12138 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12139 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12140 ConvType = ConvPtrType->getPointeeType(); 12141 12142 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12143 { 12144 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12145 Object.get(), Args, CandidateSet); 12146 } 12147 } 12148 } 12149 12150 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12151 12152 // Perform overload resolution. 12153 OverloadCandidateSet::iterator Best; 12154 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12155 Best)) { 12156 case OR_Success: 12157 // Overload resolution succeeded; we'll build the appropriate call 12158 // below. 12159 break; 12160 12161 case OR_No_Viable_Function: 12162 if (CandidateSet.empty()) 12163 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12164 << Object.get()->getType() << /*call*/ 1 12165 << Object.get()->getSourceRange(); 12166 else 12167 Diag(Object.get()->getLocStart(), 12168 diag::err_ovl_no_viable_object_call) 12169 << Object.get()->getType() << Object.get()->getSourceRange(); 12170 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12171 break; 12172 12173 case OR_Ambiguous: 12174 Diag(Object.get()->getLocStart(), 12175 diag::err_ovl_ambiguous_object_call) 12176 << Object.get()->getType() << Object.get()->getSourceRange(); 12177 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12178 break; 12179 12180 case OR_Deleted: 12181 Diag(Object.get()->getLocStart(), 12182 diag::err_ovl_deleted_object_call) 12183 << Best->Function->isDeleted() 12184 << Object.get()->getType() 12185 << getDeletedOrUnavailableSuffix(Best->Function) 12186 << Object.get()->getSourceRange(); 12187 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12188 break; 12189 } 12190 12191 if (Best == CandidateSet.end()) 12192 return true; 12193 12194 UnbridgedCasts.restore(); 12195 12196 if (Best->Function == nullptr) { 12197 // Since there is no function declaration, this is one of the 12198 // surrogate candidates. Dig out the conversion function. 12199 CXXConversionDecl *Conv 12200 = cast<CXXConversionDecl>( 12201 Best->Conversions[0].UserDefined.ConversionFunction); 12202 12203 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12204 Best->FoundDecl); 12205 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12206 return ExprError(); 12207 assert(Conv == Best->FoundDecl.getDecl() && 12208 "Found Decl & conversion-to-functionptr should be same, right?!"); 12209 // We selected one of the surrogate functions that converts the 12210 // object parameter to a function pointer. Perform the conversion 12211 // on the object argument, then let ActOnCallExpr finish the job. 12212 12213 // Create an implicit member expr to refer to the conversion operator. 12214 // and then call it. 12215 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12216 Conv, HadMultipleCandidates); 12217 if (Call.isInvalid()) 12218 return ExprError(); 12219 // Record usage of conversion in an implicit cast. 12220 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12221 CK_UserDefinedConversion, Call.get(), 12222 nullptr, VK_RValue); 12223 12224 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12225 } 12226 12227 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12228 12229 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12230 // that calls this method, using Object for the implicit object 12231 // parameter and passing along the remaining arguments. 12232 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12233 12234 // An error diagnostic has already been printed when parsing the declaration. 12235 if (Method->isInvalidDecl()) 12236 return ExprError(); 12237 12238 const FunctionProtoType *Proto = 12239 Method->getType()->getAs<FunctionProtoType>(); 12240 12241 unsigned NumParams = Proto->getNumParams(); 12242 12243 DeclarationNameInfo OpLocInfo( 12244 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12245 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12246 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12247 HadMultipleCandidates, 12248 OpLocInfo.getLoc(), 12249 OpLocInfo.getInfo()); 12250 if (NewFn.isInvalid()) 12251 return true; 12252 12253 // Build the full argument list for the method call (the implicit object 12254 // parameter is placed at the beginning of the list). 12255 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12256 MethodArgs[0] = Object.get(); 12257 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12258 12259 // Once we've built TheCall, all of the expressions are properly 12260 // owned. 12261 QualType ResultTy = Method->getReturnType(); 12262 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12263 ResultTy = ResultTy.getNonLValueExprType(Context); 12264 12265 CXXOperatorCallExpr *TheCall = new (Context) 12266 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12267 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12268 ResultTy, VK, RParenLoc, false); 12269 MethodArgs.reset(); 12270 12271 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12272 return true; 12273 12274 // We may have default arguments. If so, we need to allocate more 12275 // slots in the call for them. 12276 if (Args.size() < NumParams) 12277 TheCall->setNumArgs(Context, NumParams + 1); 12278 12279 bool IsError = false; 12280 12281 // Initialize the implicit object parameter. 12282 ExprResult ObjRes = 12283 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12284 Best->FoundDecl, Method); 12285 if (ObjRes.isInvalid()) 12286 IsError = true; 12287 else 12288 Object = ObjRes; 12289 TheCall->setArg(0, Object.get()); 12290 12291 // Check the argument types. 12292 for (unsigned i = 0; i != NumParams; i++) { 12293 Expr *Arg; 12294 if (i < Args.size()) { 12295 Arg = Args[i]; 12296 12297 // Pass the argument. 12298 12299 ExprResult InputInit 12300 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12301 Context, 12302 Method->getParamDecl(i)), 12303 SourceLocation(), Arg); 12304 12305 IsError |= InputInit.isInvalid(); 12306 Arg = InputInit.getAs<Expr>(); 12307 } else { 12308 ExprResult DefArg 12309 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12310 if (DefArg.isInvalid()) { 12311 IsError = true; 12312 break; 12313 } 12314 12315 Arg = DefArg.getAs<Expr>(); 12316 } 12317 12318 TheCall->setArg(i + 1, Arg); 12319 } 12320 12321 // If this is a variadic call, handle args passed through "...". 12322 if (Proto->isVariadic()) { 12323 // Promote the arguments (C99 6.5.2.2p7). 12324 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12325 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12326 nullptr); 12327 IsError |= Arg.isInvalid(); 12328 TheCall->setArg(i + 1, Arg.get()); 12329 } 12330 } 12331 12332 if (IsError) return true; 12333 12334 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12335 12336 if (CheckFunctionCall(Method, TheCall, Proto)) 12337 return true; 12338 12339 return MaybeBindToTemporary(TheCall); 12340 } 12341 12342 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12343 /// (if one exists), where @c Base is an expression of class type and 12344 /// @c Member is the name of the member we're trying to find. 12345 ExprResult 12346 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12347 bool *NoArrowOperatorFound) { 12348 assert(Base->getType()->isRecordType() && 12349 "left-hand side must have class type"); 12350 12351 if (checkPlaceholderForOverload(*this, Base)) 12352 return ExprError(); 12353 12354 SourceLocation Loc = Base->getExprLoc(); 12355 12356 // C++ [over.ref]p1: 12357 // 12358 // [...] An expression x->m is interpreted as (x.operator->())->m 12359 // for a class object x of type T if T::operator->() exists and if 12360 // the operator is selected as the best match function by the 12361 // overload resolution mechanism (13.3). 12362 DeclarationName OpName = 12363 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12364 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12365 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12366 12367 if (RequireCompleteType(Loc, Base->getType(), 12368 diag::err_typecheck_incomplete_tag, Base)) 12369 return ExprError(); 12370 12371 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12372 LookupQualifiedName(R, BaseRecord->getDecl()); 12373 R.suppressDiagnostics(); 12374 12375 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12376 Oper != OperEnd; ++Oper) { 12377 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12378 None, CandidateSet, /*SuppressUserConversions=*/false); 12379 } 12380 12381 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12382 12383 // Perform overload resolution. 12384 OverloadCandidateSet::iterator Best; 12385 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12386 case OR_Success: 12387 // Overload resolution succeeded; we'll build the call below. 12388 break; 12389 12390 case OR_No_Viable_Function: 12391 if (CandidateSet.empty()) { 12392 QualType BaseType = Base->getType(); 12393 if (NoArrowOperatorFound) { 12394 // Report this specific error to the caller instead of emitting a 12395 // diagnostic, as requested. 12396 *NoArrowOperatorFound = true; 12397 return ExprError(); 12398 } 12399 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12400 << BaseType << Base->getSourceRange(); 12401 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12402 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12403 << FixItHint::CreateReplacement(OpLoc, "."); 12404 } 12405 } else 12406 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12407 << "operator->" << Base->getSourceRange(); 12408 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12409 return ExprError(); 12410 12411 case OR_Ambiguous: 12412 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12413 << "->" << Base->getType() << Base->getSourceRange(); 12414 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12415 return ExprError(); 12416 12417 case OR_Deleted: 12418 Diag(OpLoc, diag::err_ovl_deleted_oper) 12419 << Best->Function->isDeleted() 12420 << "->" 12421 << getDeletedOrUnavailableSuffix(Best->Function) 12422 << Base->getSourceRange(); 12423 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12424 return ExprError(); 12425 } 12426 12427 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12428 12429 // Convert the object parameter. 12430 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12431 ExprResult BaseResult = 12432 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12433 Best->FoundDecl, Method); 12434 if (BaseResult.isInvalid()) 12435 return ExprError(); 12436 Base = BaseResult.get(); 12437 12438 // Build the operator call. 12439 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12440 HadMultipleCandidates, OpLoc); 12441 if (FnExpr.isInvalid()) 12442 return ExprError(); 12443 12444 QualType ResultTy = Method->getReturnType(); 12445 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12446 ResultTy = ResultTy.getNonLValueExprType(Context); 12447 CXXOperatorCallExpr *TheCall = 12448 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12449 Base, ResultTy, VK, OpLoc, false); 12450 12451 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12452 return ExprError(); 12453 12454 return MaybeBindToTemporary(TheCall); 12455 } 12456 12457 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12458 /// a literal operator described by the provided lookup results. 12459 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12460 DeclarationNameInfo &SuffixInfo, 12461 ArrayRef<Expr*> Args, 12462 SourceLocation LitEndLoc, 12463 TemplateArgumentListInfo *TemplateArgs) { 12464 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12465 12466 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12467 OverloadCandidateSet::CSK_Normal); 12468 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12469 /*SuppressUserConversions=*/true); 12470 12471 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12472 12473 // Perform overload resolution. This will usually be trivial, but might need 12474 // to perform substitutions for a literal operator template. 12475 OverloadCandidateSet::iterator Best; 12476 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12477 case OR_Success: 12478 case OR_Deleted: 12479 break; 12480 12481 case OR_No_Viable_Function: 12482 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12483 << R.getLookupName(); 12484 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12485 return ExprError(); 12486 12487 case OR_Ambiguous: 12488 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12489 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12490 return ExprError(); 12491 } 12492 12493 FunctionDecl *FD = Best->Function; 12494 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12495 HadMultipleCandidates, 12496 SuffixInfo.getLoc(), 12497 SuffixInfo.getInfo()); 12498 if (Fn.isInvalid()) 12499 return true; 12500 12501 // Check the argument types. This should almost always be a no-op, except 12502 // that array-to-pointer decay is applied to string literals. 12503 Expr *ConvArgs[2]; 12504 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12505 ExprResult InputInit = PerformCopyInitialization( 12506 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12507 SourceLocation(), Args[ArgIdx]); 12508 if (InputInit.isInvalid()) 12509 return true; 12510 ConvArgs[ArgIdx] = InputInit.get(); 12511 } 12512 12513 QualType ResultTy = FD->getReturnType(); 12514 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12515 ResultTy = ResultTy.getNonLValueExprType(Context); 12516 12517 UserDefinedLiteral *UDL = 12518 new (Context) UserDefinedLiteral(Context, Fn.get(), 12519 llvm::makeArrayRef(ConvArgs, Args.size()), 12520 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12521 12522 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12523 return ExprError(); 12524 12525 if (CheckFunctionCall(FD, UDL, nullptr)) 12526 return ExprError(); 12527 12528 return MaybeBindToTemporary(UDL); 12529 } 12530 12531 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12532 /// given LookupResult is non-empty, it is assumed to describe a member which 12533 /// will be invoked. Otherwise, the function will be found via argument 12534 /// dependent lookup. 12535 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12536 /// otherwise CallExpr is set to ExprError() and some non-success value 12537 /// is returned. 12538 Sema::ForRangeStatus 12539 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12540 SourceLocation RangeLoc, 12541 const DeclarationNameInfo &NameInfo, 12542 LookupResult &MemberLookup, 12543 OverloadCandidateSet *CandidateSet, 12544 Expr *Range, ExprResult *CallExpr) { 12545 Scope *S = nullptr; 12546 12547 CandidateSet->clear(); 12548 if (!MemberLookup.empty()) { 12549 ExprResult MemberRef = 12550 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12551 /*IsPtr=*/false, CXXScopeSpec(), 12552 /*TemplateKWLoc=*/SourceLocation(), 12553 /*FirstQualifierInScope=*/nullptr, 12554 MemberLookup, 12555 /*TemplateArgs=*/nullptr, S); 12556 if (MemberRef.isInvalid()) { 12557 *CallExpr = ExprError(); 12558 return FRS_DiagnosticIssued; 12559 } 12560 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12561 if (CallExpr->isInvalid()) { 12562 *CallExpr = ExprError(); 12563 return FRS_DiagnosticIssued; 12564 } 12565 } else { 12566 UnresolvedSet<0> FoundNames; 12567 UnresolvedLookupExpr *Fn = 12568 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12569 NestedNameSpecifierLoc(), NameInfo, 12570 /*NeedsADL=*/true, /*Overloaded=*/false, 12571 FoundNames.begin(), FoundNames.end()); 12572 12573 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12574 CandidateSet, CallExpr); 12575 if (CandidateSet->empty() || CandidateSetError) { 12576 *CallExpr = ExprError(); 12577 return FRS_NoViableFunction; 12578 } 12579 OverloadCandidateSet::iterator Best; 12580 OverloadingResult OverloadResult = 12581 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12582 12583 if (OverloadResult == OR_No_Viable_Function) { 12584 *CallExpr = ExprError(); 12585 return FRS_NoViableFunction; 12586 } 12587 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12588 Loc, nullptr, CandidateSet, &Best, 12589 OverloadResult, 12590 /*AllowTypoCorrection=*/false); 12591 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12592 *CallExpr = ExprError(); 12593 return FRS_DiagnosticIssued; 12594 } 12595 } 12596 return FRS_Success; 12597 } 12598 12599 12600 /// FixOverloadedFunctionReference - E is an expression that refers to 12601 /// a C++ overloaded function (possibly with some parentheses and 12602 /// perhaps a '&' around it). We have resolved the overloaded function 12603 /// to the function declaration Fn, so patch up the expression E to 12604 /// refer (possibly indirectly) to Fn. Returns the new expr. 12605 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12606 FunctionDecl *Fn) { 12607 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12608 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12609 Found, Fn); 12610 if (SubExpr == PE->getSubExpr()) 12611 return PE; 12612 12613 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12614 } 12615 12616 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12617 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12618 Found, Fn); 12619 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12620 SubExpr->getType()) && 12621 "Implicit cast type cannot be determined from overload"); 12622 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12623 if (SubExpr == ICE->getSubExpr()) 12624 return ICE; 12625 12626 return ImplicitCastExpr::Create(Context, ICE->getType(), 12627 ICE->getCastKind(), 12628 SubExpr, nullptr, 12629 ICE->getValueKind()); 12630 } 12631 12632 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12633 assert(UnOp->getOpcode() == UO_AddrOf && 12634 "Can only take the address of an overloaded function"); 12635 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12636 if (Method->isStatic()) { 12637 // Do nothing: static member functions aren't any different 12638 // from non-member functions. 12639 } else { 12640 // Fix the subexpression, which really has to be an 12641 // UnresolvedLookupExpr holding an overloaded member function 12642 // or template. 12643 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12644 Found, Fn); 12645 if (SubExpr == UnOp->getSubExpr()) 12646 return UnOp; 12647 12648 assert(isa<DeclRefExpr>(SubExpr) 12649 && "fixed to something other than a decl ref"); 12650 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12651 && "fixed to a member ref with no nested name qualifier"); 12652 12653 // We have taken the address of a pointer to member 12654 // function. Perform the computation here so that we get the 12655 // appropriate pointer to member type. 12656 QualType ClassType 12657 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12658 QualType MemPtrType 12659 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12660 12661 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12662 VK_RValue, OK_Ordinary, 12663 UnOp->getOperatorLoc()); 12664 } 12665 } 12666 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12667 Found, Fn); 12668 if (SubExpr == UnOp->getSubExpr()) 12669 return UnOp; 12670 12671 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12672 Context.getPointerType(SubExpr->getType()), 12673 VK_RValue, OK_Ordinary, 12674 UnOp->getOperatorLoc()); 12675 } 12676 12677 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12678 // FIXME: avoid copy. 12679 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12680 if (ULE->hasExplicitTemplateArgs()) { 12681 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12682 TemplateArgs = &TemplateArgsBuffer; 12683 } 12684 12685 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12686 ULE->getQualifierLoc(), 12687 ULE->getTemplateKeywordLoc(), 12688 Fn, 12689 /*enclosing*/ false, // FIXME? 12690 ULE->getNameLoc(), 12691 Fn->getType(), 12692 VK_LValue, 12693 Found.getDecl(), 12694 TemplateArgs); 12695 MarkDeclRefReferenced(DRE); 12696 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12697 return DRE; 12698 } 12699 12700 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12701 // FIXME: avoid copy. 12702 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12703 if (MemExpr->hasExplicitTemplateArgs()) { 12704 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12705 TemplateArgs = &TemplateArgsBuffer; 12706 } 12707 12708 Expr *Base; 12709 12710 // If we're filling in a static method where we used to have an 12711 // implicit member access, rewrite to a simple decl ref. 12712 if (MemExpr->isImplicitAccess()) { 12713 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12714 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12715 MemExpr->getQualifierLoc(), 12716 MemExpr->getTemplateKeywordLoc(), 12717 Fn, 12718 /*enclosing*/ false, 12719 MemExpr->getMemberLoc(), 12720 Fn->getType(), 12721 VK_LValue, 12722 Found.getDecl(), 12723 TemplateArgs); 12724 MarkDeclRefReferenced(DRE); 12725 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12726 return DRE; 12727 } else { 12728 SourceLocation Loc = MemExpr->getMemberLoc(); 12729 if (MemExpr->getQualifier()) 12730 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12731 CheckCXXThisCapture(Loc); 12732 Base = new (Context) CXXThisExpr(Loc, 12733 MemExpr->getBaseType(), 12734 /*isImplicit=*/true); 12735 } 12736 } else 12737 Base = MemExpr->getBase(); 12738 12739 ExprValueKind valueKind; 12740 QualType type; 12741 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12742 valueKind = VK_LValue; 12743 type = Fn->getType(); 12744 } else { 12745 valueKind = VK_RValue; 12746 type = Context.BoundMemberTy; 12747 } 12748 12749 MemberExpr *ME = MemberExpr::Create( 12750 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12751 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12752 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12753 OK_Ordinary); 12754 ME->setHadMultipleCandidates(true); 12755 MarkMemberReferenced(ME); 12756 return ME; 12757 } 12758 12759 llvm_unreachable("Invalid reference to overloaded function"); 12760 } 12761 12762 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12763 DeclAccessPair Found, 12764 FunctionDecl *Fn) { 12765 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12766 } 12767